2016-11-22 150 views
0

我在使用tensorflow的文本分类关注wildml博客。我已经改变了代码来保存图形高清如下:从.pb文件还原图形def时的Tensorflow错误

tf.train.write_graph(sess.graph_def,'./DeepLearn/model/','train.pb', as_text=False) 

在一个单独的文件我正在恢复图如下后来:

with tf.gfile.FastGFile(os.path.join('./DeepLearn/model/','train.pb'), 'rb') as f: 
    graph_def = tf.GraphDef() 
    graph_def.ParseFromString(f.read()) 
    _ = tf.import_graph_def(graph_def, name='') 
with tf.Session() as sess: 
    t = sess.graph.get_tensor_by_name('embedding/W:0') 
    sess.run(t) 

当我尝试运行的张量,并得到其价值,我收到以下错误:

tensorflow.python.framework.errors.FailedPreconditionError: Attempting to use uninitialized value embedding/W 

什么可能是此错误的可能原因。张量应该已经初始化,因为我从保存的图中恢复它。

+0

'sess.run(tf.initialize_all_variables())'? – sygi

+0

但是,我从以前保存的图加载张量,所以我不认为我需要使用此语句对其进行初始化。 – Nitin

+1

您仍然需要初始化变量,因为读取graphdef只会恢复图形本身,而不是变量的值。如果您想恢复需要从检查点加载的变量值。 –

回答

0

谢谢亚历山大! 是的,我需要加载图(从.pb文件)和权重(从检查点文件。)。使用下面的示例代码(从博客中获取),它适用于我。

with tf.Session() as persisted_sess: 
    print("load graph") 
    with gfile.FastGFile("/tmp/load/test.pb",'rb') as f: 
     graph_def = tf.GraphDef() 
     graph_def.ParseFromString(f.read()) 
     persisted_sess.graph.as_default() 
     tf.import_graph_def(graph_def, name='') 
    persisted_result = persisted_sess.graph.get_tensor_by_name("saved_result:0") 
    tf.add_to_collection(tf.GraphKeys.VARIABLES,persisted_result) 
    try: 
     saver = tf.train.Saver(tf.all_variables()) 
    except:pass 
     print("load data") 
    saver.restore(persisted_sess, "checkpoint.data") # now OK 
    print(persisted_result.eval()) 
    print("DONE")