Tensorflow freeze_graph 脚本在使用 Keras 定义的模型上失败

Tensorflow freeze_graph script failing on model defined with Keras

我正在尝试将使用 Keras 构建和训练的模型导出到我可以在 C++ 脚本中加载的原型缓冲区(如本例所示)。我生成了一个包含模型定义的 .pb 文件和一个包含检查点数据的 .ckpt 文件。但是,当我尝试使用 freeze_graph 脚本将它们合并到一个文件中时,出现错误:

ValueError: Fetch argument 'save/restore_all' of 'save/restore_all' cannot be interpreted as a Tensor. ("The name 'save/restore_all' refers to an Operation not in the graph.")

我正在这样保存模型:

with tf.Session() as sess:
    model = nndetector.architecture.models.vgg19((3, 50, 50))
    model.load_weights('/srv/nn/weights/scratch-vgg19.h5')
    init_op = tf.initialize_all_variables()
    sess.run(init_op)
    graph_def = sess.graph.as_graph_def()
    tf.train.write_graph(graph_def=graph_def, logdir='.',   name='model.pb', as_text=False)
    saver = tf.train.Saver()
    saver.save(sess, 'model.ckpt')

nndetector.architecture.models.vgg19((3, 50, 50)) 只是在 Keras 中定义的类似 vgg19 的模型。

我这样调用 freeze_graph 脚本:

bazel-bin/tensorflow/python/tools/freeze_graph --input_graph=[path-to-model.pb] --input_checkpoint=[path-to-model.ckpt] --output_graph=[output-path] --output_node_names=sigmoid --input_binary=True

如果我 运行 freeze_graph_test 脚本一切正常。

有人知道我做错了什么吗?

谢谢。

此致

菲利普

编辑

我试过打印 tf.train.Saver().as_saver_def().restore_op_name 其中 returns save/restore_all.

此外,我尝试了一个简单的纯张量流示例,但仍然出现相同的错误:

a = tf.Variable(tf.constant(1), name='a')
b = tf.Variable(tf.constant(2), name='b')
add = tf.add(a, b, 'sum')

with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
tf.train.write_graph(graph_def=sess.graph.as_graph_def(), logdir='.',     name='simple_as_binary.pb', as_text=False)
tf.train.Saver().save(sess, 'simple.ckpt')

而且我实际上也无法恢复 python 中的图表。使用下面的代码抛出 ValueError: No variables to save 如果我单独执行它而不是保存图形(也就是说,如果我在同一个脚本中保存和恢复模型,一切正常)。

with gfile.FastGFile('simple_as_binary.pb') as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())

with tf.Session() as sess:
    tf.import_graph_def(graph_def)
    saver = tf.train.Saver()
    saver.restore(sess, 'simple.ckpt')

我不确定这两个问题是否相关,或者我只是没有在 python 中正确恢复模型。

问题出在你原来程序中这两行的顺序:

tf.train.write_graph(graph_def=sess.graph.as_graph_def(), logdir='.',     name='simple_as_binary.pb', as_text=False)
tf.train.Saver().save(sess, 'simple.ckpt')

调用 tf.train.Saver() 向图中添加 一组节点,包括一个名为 "save/restore_all" 的节点。但是,此程序在 写出图形后调用它 ,因此您传递给 freeze_graph.py 的文件不包含进行重写所必需的那些节点。

颠倒这两行应该使脚本按预期工作:

tf.train.Saver().save(sess, 'simple.ckpt')
tf.train.write_graph(graph_def=sess.graph.as_graph_def(), logdir='.',     name='simple_as_binary.pb', as_text=False)

所以,我成功了。有点。

通过直接使用 tensorflow.python.client.graph_util.convert_variables_to_constants 而不是先将 GraphDef 和检查点保存到磁盘然后使用 freeze_graph tool/script,我已经能够保存 GraphDef 包含图形定义和转换为常量的变量。

编辑

mrry 更新了他的答案,这解决了我的 freeze_graph 不起作用的问题,但我也会留下这个答案,以防其他人发现它有用。