python - 在 tf.Graph() 下定义的 TensorFlow session 运行图

标签 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 中定义的操作?

最佳答案

这是预期的行为,但我明白为什么它会令人惊讶!以下行返回一个 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/

相关文章:

php - 在 Laravel 中检索 session 值返回 null

java - 没有 cookie 的 Servlet session + 仅返回 JSON 的 ajax 请求

asp.net - 在 SessionPageStatePersister 中保持 ViewState

python - 在 Python 版剧作家中,如何获取与 ElementHandle 相关的元素( child 、 parent 、祖 parent 、 sibling )?

python - Tensorflow - 关于 mnist.train.next_batch()

python - Tensorflow - 损失不减少

python - 如何使用 tensorflow 中的 seq2seq 预测简单序列?

python - 在 Google App Engine 上分析/优化网站的最佳方式

python - 将优化输出转储到数组中

python - 转储 CSV 文件中包含一系列空白字段的行