TF save/restore 图在 tf.GraphDef.ParseFromString() 失败

TF save/restore graph fails at tf.GraphDef.ParseFromString()

基于这个 我正在尝试 save/restore TF 图表但没有成功。

这里是节省程序:

with tf.Graph().as_default():
    variable_node = tf.Variable(1.0, name="variable_node")
    output_node = tf.mul(variable_node, 2.0, name="output_node")
    sess = tf.Session()
    init = tf.initialize_all_variables()
    sess.run(init)
    output = sess.run(output_node)
    tf.train.write_graph(sess.graph.as_graph_def(), summ_dir, 'model_00_g.pbtxt', as_text=True)
    #self.assertNear(2.0, output, 0.00001)
    saver = tf.train.Saver()
    saver.save(sess, saver_path)

生成带有文本图描述的 model_00_g.pbtxt。几乎从 freeze_graph_test.py.

复制粘贴

这里是reader:

with tf.Session() as sess:

    with tf.Graph().as_default():
        graph_def = tf.GraphDef()
        graph_path = '/mnt/code/test_00/log/2016-02-11.22-37-46/model_00_g.pbtxt'
        with open(graph_path, "rb") as f:
            proto_b = f.read()
            #print proto_b   # -> I can see it
            graph_def.ParseFromString(proto_b) # no luck..
            _ = tf.import_graph_def(graph_def, name="")

    print sess.graph_def

graph_def.ParseFromString() 处失败,DecodeError: Tag had invalid wire type.

我在 docker 集装箱 b.gcr.io/tensorflow/tensorflow:latest-devel 以防有什么不同。

ParseFromString 需要二进制序列化协议缓冲区,对于人类可读的表示,您需要像使用 here

一样使用 text_format.Merge

GraphDef.ParseFromString() 方法(通常,任何 Python protobuf 包装器上的 ParseFromString() 方法)需要二进制协议缓冲区格式的字符串。如果将 as_text=False 传递给 tf.train.write_graph(),则文件将采用适当的格式。

否则,您可以执行以下操作来阅读基于文本的格式:

from google.protobuf import text_format
# ...
graph_def = tf.GraphDef()
text_format.Merge(proto_b, graph_def) 

我试图通过 java API 加载模型,它只接受二进制文件。但在 python 中我们使用 contrib.Estimator 生成文本模型文件格式。 我在网上找到了一个 model file converter,似乎工作正常。 如果您有现有的文本格式模型文件,这也可能解决原始问题(使用二进制模型加载器)。