使用tensorflow保存和恢复模型
我使用以下方法保存了神经网络的参数:使用tensorflow保存和恢复模型,tensorflow,python-2.x,Tensorflow,Python 2.x,我使用以下方法保存了神经网络的参数: parameters = { 'w_h1': w_h1, 'b_h1': b_h1, 'w_h2': w_h2, 'b_h2': b_h2, 'w_h3': w_h3, 'b_h3': b_h3, 'w_o': w_o, 'b_o': b_o } saver = tf.train.Saver(parameters) saver.save(sess, 'my-model', globa
parameters = {
'w_h1': w_h1,
'b_h1': b_h1,
'w_h2': w_h2,
'b_h2': b_h2,
'w_h3': w_h3,
'b_h3': b_h3,
'w_o': w_o,
'b_o': b_o
}
saver = tf.train.Saver(parameters)
saver.save(sess, 'my-model', global_step=epoch)
现在我的磁盘中有以下3个文件:
checkpoint
my-model-114000
my-model-114000.meta
我试过这样的方法:
with tf.Session() as sess:
new_saver = tf.train.import_meta_graph('my-model-114000.meta')
new_saver.restore(sess, 'my-model-114000')
我收到消息:
INFO:tensorflow:Restoring parameters from my-model-114000
但是,我无法恢复原始参数。我尝试了类似的方法(在使用tf.Session()作为sess的
w_h1=tf.get_default_graph().get_tensor_by_name(“w_h1:0”)
但是我收到消息了
KeyError: "The name 'w_h1:0' refers to a Tensor which does not exist. The operation, 'w_h1', does not exist in the graph."
但是,我无法恢复重量。我该怎么做
我曾经
for var in tf.all_variables():
print str(var)
为了知道保存了什么,我意识到它保存了很多东西(下面只是一个示例),但我认为我只保存了少量重要参数:
<tf.Variable 'Variable_21/Adam_3:0' shape=(50,) dtype=float32_ref>
<tf.Variable 'Variable_24/Adam_2:0' shape=(50, 50) dtype=float32_ref>
<tf.Variable 'Variable_24/Adam_3:0' shape=(50, 50) dtype=float32_ref>
<tf.Variable 'Variable_25/Adam_2:0' shape=(50,) dtype=float32_ref>
<tf.Variable 'Variable_25/Adam_3:0' shape=(50,) dtype=float32_ref>
<tf.Variable 'Variable_28/Adam_2:0' shape=(50, 1) dtype=float32_ref>
<tf.Variable 'Variable_28/Adam_3:0' shape=(50, 1) dtype=float32_ref>
<tf.Variable 'Variable_29/Adam_2:0' shape=(1,) dtype=float32_ref>
<tf.Variable 'Variable_29/Adam_3:0' shape=(1,) dtype=float32_ref>
>>>
>>>
像'Variable\u 21/Adam\u 3:0'这样的名称是您的变量名称,而“w\u h1”
不是,您应该使用w\u h1=tf.get\u default\u graph()获得这个张量。通过名称(“Variable\u 21/Adam\u 3:0”)获得张量
确保使用与保存期间相同的图形体系结构初始化tensorflow
图形。@紫外线:我怎么做?此外,即使我定义了要保存的参数,tensorflow也会保存所有变量?它可能是w_h1、w_h2或w_h3。但是,我怎么知道是哪一个呢?我以为我应该以“w_h1:0”的名称来恢复变量。在创建变量时,您可以使用任何您想要的名称来命名变量,如tf.variable(name=“w_h1”)
。恢复权重的问题是我没有命名变量。现在我就这么做!