我正在尝试在tensorflow中保存和恢复我的模型,我试图搜索并找到了很多教程但是他们都没有给出明确的说明,恢复模型时我应该使用在训练期间使用的相同程序或只是恢复模特??
这是张量流中的简单线性回归模型:
import numpy as np
import tensorflow as tf
tf.set_random_seed(777)
x_data = [[73., 80., 75.],
[93., 88., 93.],
[89., 91., 90.],
[96., 98., 100.],
[73., 66., 70.]]
y_data = [[152.],
[185.],
[180.],
[196.],
[142.]]
class regression_model():
def __init__(self):
input_x = tf.placeholder(tf.float32,shape=[None,3])
output_y=tf.placeholder(tf.float32,shape=[None,1])
self.placeholder={'input':input_x,'output':output_y}
weights= tf.get_variable('weights',shape=[3,1],dtype=tf.float32,initializer=tf.random_uniform_initializer(-0.01,0.01))
bias = tf.get_variable('bias',shape=[1],dtype=tf.float32,initializer=tf.random_uniform_initializer(-0.01,0.01))
result=tf.matmul(input_x,weights) + bias
cost=tf.square(result-output_y)
loss=tf.reduce_mean(cost)
train=tf.train.GradientDescentOptimizer(learning_rate=1e-5).minimize(loss)
self.out ={'result':result,'loss':loss,'train':train}
def exe_func(model):
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for step in range(2001):
out=sess.run(model.out,feed_dict={model.placeholder['input']:x_data,model.placeholder['output']:y_data})
print("loss", out['loss'], "prediction", out['result'])
if __name__=='__main__':
model=regression_model()
exe_func(model)
当我跑步时我得到这个输出:
...
loss 0.73689765 prediction [[152.12286]
[184.14502]
[180.76541]
[196.88777]
[140.74924]]
loss 0.7366613 prediction [[152.12263]
[184.1452 ]
[180.76535]
[196.88771]
[140.74948]]
Process finished with exit code 0
现在我如何保存此模型以及如何在新文件中恢复?我尝试了这个stackoverflow question并做了类似的事情:
def exe_func(model):
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for step in range(2001):
out=sess.run(model.out,feed_dict={model.placeholder['input']:x_data,model.placeholder['output']:y_data})
print("loss", out['loss'], "prediction", out['result'])
saver.save(sess, '/Users/exepaul/Desktop/only_rnn_1/')
if __name__=='__main__':
model=regression_model()
exe_func(model)
但是我没有得到如何使用这个保存的模型以及如何为模型提供输入并获得预测输出?
答案 0 :(得分:2)
@MPA答案很有帮助,但我不得不在@MPA答案中做一些修改以获得结果,我想提及其他人:
首先,如果你想保存和恢复图形,然后在稍后使用的那些操作中给出一个名称参数值,所以我改变了
这一行
1 Company - N business hours.
到此:
input_x = tf.placeholder(tf.float32,shape=[None,3])
和这一行
input_x = tf.placeholder(tf.float32,shape=[None,3],name='input')
到此:
result=tf.matmul(input_x,weights) + bias
现在在新文件中我运行这个程序:
result=tf.add(tf.matmul(input_x,weights),bias,name='result')
我得到了输出:
import tensorflow as tf
x_data = [[73., 80., 75.]]
with tf.Session() as sess:
saver = tf.train.import_meta_graph('/Users/exepaul/Desktop/.meta')
new=saver.restore(sess, tf.train.latest_checkpoint('/Users/exepaul/Desktop/'))
graph = tf.get_default_graph()
input_x = graph.get_tensor_by_name("input:0")
result = graph.get_tensor_by_name("result:0")
feed_dict = {input_x: x_data,}
predictions = result.eval(feed_dict=feed_dict)
print(predictions)
答案 1 :(得分:1)
您提供的“恢复”代码段只会重新启动培训过程。一旦训练了NN,就不必继续训练以获得预测。应修复所有模型参数,并仅评估给定输入的输出一次。请参阅以下示例:
with tf.Session() as sess:
saver = tf.train.import_meta_graph(savefile)
saver.restore(sess, tf.train.latest_checkpoint(savedir))
graph = tf.get_default_graph()
input_x = graph.get_tensor_by_name("input_x:0")
result = graph.get_tensor_by_name("result:0")
feed_dict = {input_x: x_data,}
predictions = result.eval(feed_dict=feed_dict)