简体   繁体   English

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

[英]TensorFlow session run graph defined outside under tf.Graph()

When initializing tf.Session() , we can pass in a graph like tf.Session(graph=my_graph) , for example: 初始化tf.Session() ,我们可以传入像tf.Session(graph=my_graph)这样的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

In the example above, it prints None . 在上面的示例中,它打印None How can we execute an operation defined inside my_graph ? 我们如何执行my_graph定义的操作?

This is the intended behavior, but I can see why it would be surprising! 这是预期的行为,但我可以看出为什么会令人惊讶! The following line returns a tf.Operation object: 以下行返回tf.Operation对象:

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

...and when you pass a tf.Operation object to Session.run() , TensorFlow will execute the operation, but it will discard its outputs and return None . ...当您将tf.Operation对象传递给Session.run() ,TensorFlow将执行该操作,但它将丢弃其输出并返回None

The following program probably has the behavior you're expecting, by explicitly specifying the 0th output of that operation and retrieving a tf.Tensor object: 以下程序可能具有您期望的行为,方法是显式指定该操作的第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.'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM