如何替换已保存图形的输入,例如数据集迭代器的占位符?

How to replace the input of a saved graph, e.g. a placeholder by a Dataset iterator?

我有一个已保存的 Tensorflow 图,它​​通过 placeholderfeed_dict 参数消耗输入。

sess.run(my_tensor, feed_dict={input_image: image})

因为用 Dataset Iterator 提供的数据是 more efficient,我想加载保存的图表,将 input_image placeholder 替换为 Iterator 和 运行。我怎样才能做到这一点?有更好的方法吗?非常感谢带有代码示例的答案。

您可以通过序列化图表并使用 tf.import_graph_def 重新导入它来实现这一点,它有一个 input_map 参数用于在所需位置插入输入。

要做到这一点,您至少需要知道您替换的输入的名称和您希望执行的输出的名称(在我的示例中分别为 xy)。

import tensorflow as tf

# restore graph (built from scratch here for the example)
x = tf.placeholder(tf.int64, shape=(), name='x')
y = tf.square(x, name='y')

# just for display -- you don't need to create a Session for serialization
with tf.Session() as sess:
  print("with placeholder:")
  for i in range(10):
    print(sess.run(y, {x: i}))

# serialize the graph
graph_def = tf.get_default_graph().as_graph_def()

tf.reset_default_graph()

# build new pipeline
batch = tf.data.Dataset.range(10).make_one_shot_iterator().get_next()
# plug in new pipeline
[y] = tf.import_graph_def(graph_def, input_map={'x:0': batch}, return_elements=['y:0'])

# enjoy Dataset inputs!
with tf.Session() as sess:
  print('with Dataset:')
  try:
    while True:
      print(sess.run(y))
  except tf.errors.OutOfRangeError:
    pass        

请注意,占位符节点仍然存在,因为我没有费心在这里解析 graph_def 以将其删除 - 您可以将其删除作为改进,但我认为将其保留在这里也可以.

根据您恢复图形的方式,输入替换可能已经内置在加载程序中,这使事情变得更简单(无需返回到 GraphDef)。例如,如果您从 .meta 文件加载图形,则可以使用接受相同 input_map 参数的 tf.train.import_meta_graph

import tensorflow as tf

# build new pipeline
batch = tf.data.Dataset.range(10).make_one_shot_iterator().get_next()
# load your net and plug in new pipeline
# you need to know the name of the tensor where to plug-in your input
restorer = tf.train.import_meta_graph(graph_filepath, input_map={'x:0': batch})
y = tf.get_default_graph().get_tensor_by_name('y:0')

# enjoy Dataset inputs!
with tf.Session() as sess:
  # not needed here, but in practice you would also need to restore weights
  # restorer.restore(sess, weights_filepath)
  print('with Dataset:')
  try:
    while True:
      print(sess.run(y))
  except tf.errors.OutOfRangeError:
    pass