RuntimeError:The Session graph is empty.

 

raise RuntimeError('The Session graph is empty.  Add operations to the '
RuntimeError: The Session graph is empty.  Add operations to the graph before calling run().

 

2 Graph


1. Create a new graph and add operations

g = tf.Graph()
with g.as_default():
    
sess = tf.Session(graph=g) # session is run on graph g
sess.run # run session

The graph=g indication could not be omitted, or the Session object would just run the default graph, in which there is no op1.

If you use sess = tf.Session() in the above codes:

RuntimeError: The Session graph is empty.  Add operations to the graph before calling run().
 

2. Get the handle of the default graph

g = tf.get_default_graph()

3. Do not mix the default graph and the user created graph

g = tf.Graph()

# add ops to the default graph
a = tf.constant(3)

# add ops to the user created graph
with g.as_default():
   b = tf.constant(5)

The codes above are equivalent to the following codes. And the following codes are better in some sense. However, having more than one graph is never recommended.

g1 = tf.get_default_graph()
g2 = tf.Graph()

# add ops to the default graph
with g1.as_default():
    a = tf.constant(3)

# add ops to the user created graph
with g2.as_default():
    b = tf.constant(5)


 -- shawn233

From: Tensorflow | Stanford CS 20SI 

 

RuntimeError:The Session graph is empty._第1张图片

import tensorflow as tf
c=tf.constant(4.0)
assert c.graph is tf.get_default_graph() #看看主程序中新建的一个变量是不是在默认图里
g=tf.Graph()
with g.as_default():
    c=tf.constant(30.0)
    assert c.graph is g
'''
最终结果是没有报错
'''

 

你可能感兴趣的:(人工神经网络)