在初始化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
中定义的操作?
最佳答案
这是预期的行为,但我明白为什么它会令人惊讶!以下行返回一个 tf.Operation
对象:
a = sess.graph.get_operation_by_name('a')
...当您将 tf.Operation
对象传递给 Session.run()
时,TensorFlow 将执行该操作,但它会丢弃其输出并返回无
。
通过显式指定该操作的第 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.'
关于python - 在 tf.Graph() 下定义的 TensorFlow session 运行图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40558238/