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

Yix*_*ing 2 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
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,它打印None.我们如何执行内部定义的操作my_graph

mrr*_*rry 9

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

a = sess.graph.get_operation_by_name('a')
Run Code Online (Sandbox Code Playgroud)

...当你传递一个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.'
Run Code Online (Sandbox Code Playgroud)