python – tensorflow摘要需要提供占位符,但我无法理解为什么

我在深入研究之前测试摘要,并且我有以下剪切代码

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})

因为似乎merged包含来自前一个未填充的函数的东西.

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执行的张量流样式是什么,它们之间不会产生干扰?

最佳答案 您遇到的问题与加载到同一图表的张量有关.

注意到test_merge包含merged = tf.summary.merge_all(),这会合并默认图中收集的所有摘要,并且所有内容都会加载到默认图中,因此当您尝试评估summary = sess.run时(merged,feed_dict = {x: k * i * i})它也需要第一个函数的输入.如果更改了调用的顺序,您将看到代码执行.如果你需要单独的图形,它可能会有问题,所以尝试将所有内容加载到一个图形 – 但如果你需要,那么这个答案可能是使用
Working with multiple graphs in TensorFlow.

点赞