我在更深入地测试摘要之前,我有以下剪切代码
import tensorflow as tf
import numpy as np
def test_placeholders():
"Simply dump a placeholder to TensorBoard"
x = tf.placeholder(tf.float32, [])
sess = tf.Session()
summary = tf.summary.scalar("x", x)
train_writer = tf.summary.FileWriter('/tmp/tf/placeholder',
sess.graph, flush_secs=1)
r = sess.run(tf.global_variables_initializer())
s = sess.run(summary, feed_dict={x: 1.57})
train_writer.add_summary(s)
train_writer.close()
def test_merge():
"A simple function that make a loop computation and write down into TB"
x = tf.placeholder(tf.float32)
k = np.random.random() + 0.1
# Create a session
sess = tf.Session()
sess.run(tf.global_variables_initializer())
# define a single summary
summary_x = tf.summary.scalar("x", x)
train_writer = tf.summary.FileWriter('/tmp/tf/foo',
sess.graph, flush_secs=1)
# write some summaries
for i in range(0, 5):
# WORKS!
summary = sess.run(summary_x, feed_dict={x: k * i * i})
train_writer.add_summary(summary, i)
# write some summaries using merge_all
# (we have only one define summary)
merged = tf.summary.merge_all()
for i in range(5, 10):
# FAILS: You must feed a value for placeholder ...
summary = sess.run(merged, feed_dict={x: k * i * i})
train_writer.add_summary(summary, i)
train_writer.close()
if __name__ == '__main__':
test_placeholders() # if I comment this line ...
test_merge() # test_merge() works!?
所以基本上有两个函数可以创建一些循环并为TensorBoard写一些日志。
问题:
每个函数都可以很好地相互隔离,但是,当我按顺序运行时,第二个函数在这里失败
# FAILS: You must feed a value for placeholder ...
summary = sess.run(merged, feed_dict={x: k * i * i})
因为似乎合并包含来自前一个未填充的函数的内容。
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float
[[Node: Placeholder = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
Caused by op u'Placeholder', defined at:
深入研究代码,我发现TF将便利变量存储到默认容器中,例如:来自之前作品的图, _collections ,因此拨打电话
tf.reset_default_graph()
用作重置之前执行的所有内容。
问题:
用于隔离和处理多次TF执行的 tensorflow样式是什么,它们在同一进程中不会产生干扰?
答案 0 :(得分:1)
您遇到的问题与加载到同一图表的张量有关。
注意到test_merge
包含merged = tf.summary.merge_all()
这会合并默认图表中收集的所有摘要,并且所有内容都会加载到默认图表中,因此当您尝试评估summary = sess.run(merged, feed_dict={x: k * i * i})
时,它需要来自第一个函数的输入同样。如果更改了调用的顺序,您将看到代码执行。如果您需要单独的图表,则可能会出现问题,因此请尝试将所有内容加载到一个图表中 - 但如果您需要,则此答案可能有用Working with multiple graphs in TensorFlow。
答案 1 :(得分:0)
使用tf.reset_default_graph()
在代码的开头,将图形恢复为其默认值。有时Tensorflow会记住上一次运行的feed_dict。并且该feed_dict可能与当前会话不同