在tensorflow中恢复图失败,因为没有要保存的变量

jea*_*ean 6 python restore tensorflow

我知道堆栈和github等上有无数关于如何在Tensorflow中恢复训练模型的问题.我已阅读大部分(1,2,3).

我有几乎完全相同的问题3然而我想尽可能以不同的方式解决它,因为我的训练和我的测试需要在从shell调用的单独脚本中,我不想添加完全相同的行我用于在测试脚本中定义图形,因此我不能使用tensorflow FLAGS和其他基于手动重新运行图形的答案.

我也不想sess.run每个变量并手动映射它们,因为它解释为我的图表非常大(使用带有参数input_map的import_graph_def).

所以我运行一些图表并在特定的脚本中训练它.比如(但没有培训部分)

#Script 1
import tensorflow as tf
import cPickle as pickle

x=tf.Variable(42)
saver=tf.train.Saver()
sess=tf.Session()
#Saving the graph
graph_def=sess.graph_def
with open('graph.pkl','wb') as output:
  pickle.dump(graph_def,output,HIGHEST_PROTOCOL)


#Training the model
sess.run(tf.initialize_all_variables())
#Saving the variables
saver.save(sess,"pretrained_model.ckpt")
Run Code Online (Sandbox Code Playgroud)

我现在已经保存了图形和变量,所以我应该能够从另一个脚本运行我的测试模型,即使我的图形中有额外的训练节点.

#Script 2
import tensorflow as tf
import cPickle as pickle

sess=tf.Session()
with open('graph.pkl','rb') as input:
  graph_def=pickle.load(input)


tf.import_graph_def(graph_def,name='persisted')
Run Code Online (Sandbox Code Playgroud)

然后显然我想使用保护程序恢复变量,但我遇到了与3相同的问题,因为没有找到保存甚至创建保护程序的变量.所以我写不出来:

saver=tf.train.Saver()
saver.restore(sess,"pretrained_model.ckpt")
Run Code Online (Sandbox Code Playgroud)

有没有办法绕过这些限制,我认为通过导入图形它会恢复每个节点中未初始化的变量,但似乎不是我真的需要第二次重新运行它像大多数给出的答案?

Yar*_*tov 6

变量列表保存在Collection未保存的文件中GraphDef.Saver默认情况下,使用ops.GraphKeys.VARIABLES集合中的列表(可通过tf.all_variables()),如果您从而GraphDef不是使用Python API来构建模型,则该集合为空.您可以手动指定变量列表tf.train.Saver(var_list=['MyVariable1:0', 'MyVariable2:0',...]).

或者,GraphDef您可以使用MetaGraphDef哪个保存集合,最近添加了MetaGraphDef HowTo