Working with multiple graphs

In [1]:
import tensorflow as tf

All operations are added to default graph if nothing is specified

In [32]:
tf.reset_default_graph()
a = tf.constant(2)
b = tf.constant(5)
c = a + b
In [33]:
g_default = tf.get_default_graph()
g_default.get_operations()
Out[33]:
[<tf.Operation 'Const' type=Const>,
 <tf.Operation 'Const_1' type=Const>,
 <tf.Operation 'add' type=Add>]

Building a new graph

NOTE: Do not use the tensors from another graph

In [52]:
g = tf.Graph()
g.get_operations()
Out[52]:
[]
In [53]:
with g.as_default():
    #x = a #cant use a here
    e = tf.constant(2)
    f = tf.constant(5)
    h = e*f
    print(g.get_operations())
#g is not default here
[<tf.Operation 'Const' type=Const>, <tf.Operation 'Const_1' type=Const>, <tf.Operation 'mul' type=Mul>]

List the operations under two graphs

In [54]:
g_default.get_operations()
Out[54]:
[<tf.Operation 'Const' type=Const>,
 <tf.Operation 'Const_1' type=Const>,
 <tf.Operation 'add' type=Add>]
In [55]:
g.get_operations()
Out[55]:
[<tf.Operation 'Const' type=Const>,
 <tf.Operation 'Const_1' type=Const>,
 <tf.Operation 'mul' type=Mul>]

Running default graph

In [56]:
with tf.Session() as sess:
    print(sess.run(c))
    #print(sess.run(h)) #breaks
7

Running the new graph

In [57]:
with g.as_default():
    with tf.Session() as sess:
        print(sess.run(h))
10