在tf.Graph()下定义的TensorFlow会话运行图

时间:2016-11-12 00:22:12

标签: python session tensorflow

初始化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中定义的操作?

1 个答案:

答案 0 :(得分:9)

这是预期的行为,但我明白为什么会出现这种情况!以下行返回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.'