Yixing Yixing - 21 days ago 6
Python Question

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
?

Answer

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