How can I understand sess.as_default () and sess.graph.as_default ()?
I have read the docs sess.as_default ()
NB The default session is a property of the current thread. If you are creating a new thread and want to use the default session on that thread, you must explicitly add a using sess.as_default (): in this thread function.
I understand that if there are two more sessions when creating a new flow, we have to establish a session to run the TensorFlow code. So, for this, a session is selected and called as_default()
.
NB Entering a with sess.as_default (): block does not affect the current default chart. If you are using multiple graphs and sess.graph is different from tf.get_default_graph, you must explicitly type a with sess.graph.as_default (): block to make sess.graph the default graph.
In a block sess.as_default()
, in order to call a specific graph, do you need to call sess.graph.as_default()
to launch the chart?
source to share
The tf.Session API mentions that the chart is started in a session. The following code illustrates this:
import tensorflow as tf
graph1 = tf.Graph()
graph2 = tf.Graph()
with graph1.as_default() as graph:
a = tf.constant(0, name='a')
graph1_init_op = tf.global_variables_initializer()
with graph2.as_default() as graph:
a = tf.constant(1, name='a')
graph2_init_op = tf.global_variables_initializer()
sess1 = tf.Session(graph=graph1)
sess2 = tf.Session(graph=graph2)
sess1.run(graph1_init_op)
sess2.run(graph2_init_op)
# Both tensor names are a!
print(sess1.run(graph1.get_tensor_by_name('a:0'))) # prints 0
print(sess2.run(graph2.get_tensor_by_name('a:0'))) # prints 1
with sess1.as_default() as sess:
print(sess.run(sess.graph.get_tensor_by_name('a:0'))) # prints 0
with sess2.as_default() as sess:
print(sess.run(sess.graph.get_tensor_by_name('a:0'))) # prints 1
with graph2.as_default() as g:
with sess1.as_default() as sess:
print(tf.get_default_graph() == graph2) # prints True
print(tf.get_default_session() == sess1) # prints True
# This is the interesting line
print(sess.run(sess.graph.get_tensor_by_name('a:0'))) # prints 0
print(sess.run(g.get_tensor_by_name('a:0'))) # fails
print(tf.get_default_graph() == graph2) # prints False
print(tf.get_default_session() == sess1) # prints False
You don't need to call sess.graph.as_default()
to run the chart, but you need to get the correct tensors or operations on the chart to run it. Context allows you to get a graph or session using tf.get_default_graph
or tf.get_default_session
.
The interesting line above is the default session sess1
and it implicitly calls sess1.graph
which is the graph in sess1
which is graph1
, and therefore it prints 0.
On the line following it, it fails because it tries to perform the operation graph2
with sess1
.
source to share