【问题标题】:TensorFlow session run graph defined outside under tf.Graph()TensorFlow 会话运行图在 tf.Graph() 下定义
【发布时间】:2016-11-12 08:30:49
【问题描述】:

在初始化tf.Session()的时候,我们可以传入一个类似tf.Session(graph=my_graph)的图,例如:

import tensorflow as tf

# define graph
my_graph = tf.Graph()
with my_graph.as_default():
    a = tf.constant(100., tf.float32, name='a')

# run graph
with tf.Session(graph=my_graph) as sess:
    a = sess.graph.get_operation_by_name('a')
    print(sess.run(a))  # prints None

在上面的示例中,它打印None。我们如何执行my_graph中定义的操作?

【问题讨论】:

    标签: python session tensorflow


    【解决方案1】:

    这是预期的行为,但我明白为什么会令人惊讶!以下行返回一个tf.Operation 对象:

    a = sess.graph.get_operation_by_name('a')
    

    ...当您将tf.Operation 对象传递给Session.run() 时,TensorFlow 将执行该操作,但它会丢弃其输出并返回None

    通过显式指定该操作的第 0 个输出并检索 tf.Tensor 对象,以下程序可能具有您所期望的行为:

    with tf.Session(graph=my_graph) as sess:
        a = sess.graph.get_operation_by_name('a').outputs[0]
        # Or you could do:
        # a = sess.graph.get_tensor_by_name('a:0')
        print(sess.run(a))  # prints '100.'
    

    【讨论】:

      猜你喜欢
      • 2019-06-08
      • 2017-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-18
      • 1970-01-01
      • 2021-03-29
      • 1970-01-01
      相关资源
      最近更新 更多