简体   繁体   中英

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:

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 . How can we execute an operation defined inside my_graph ?

This is the intended behavior, but I can see why it would be surprising! The following line returns a tf.Operation object:

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 .

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:

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.'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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