I keep getting this error while running sess.run(init)
. I had basic tensorflow 1.3 knowledge, but now I'm using tensorflow 2.2 and keep getting these errors
import tensorflow as tf
sess=tf.compat.v1.InteractiveSession()
my_tensor=tf.random.uniform((4,4),minval=0,maxval=1)
my_var=tf.Variable(initial_value=my_tensor)
init=tf.compat.v1.global_variables_initializer()
sess.run(init)
sess.run(my_var)
RuntimeError Traceback(mostrecent call last)
<ipython-input-9-d2e99d8a0a79> in <module>
8 init=tf.compat.v1.global_variables_initializer()
9
---> 10 sess.run(init)
11 sess.run(my_var)
~\anaconda3\lib\site-packages\tensorflow\python\client \session.py in run(self, fetches, feed_dict, options, run_metadata)
956 try:
957 result = self._run(None, fetches, feed_dict, options_ptr,
--> 958 run_metadata_ptr)
959 if run_metadata:
960 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)
~\anaconda3\lib\site-packages\tensorflow\python\client \session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
1104 raise RuntimeError('Attempted to use a closed Session.')
1105 if self.graph.version == 0:
-> 1106 raise RuntimeError('The Session graph is empty. Add operations to the '
1107 'graph before calling run().')
1108
RuntimeError: The Session graph is empty. Add operations to the graph before calling run().
Tensorflow 2.x has a new feature Eager Execution which executes your operation as you add them to the graph, without the need to sess.run
. Actually there's no notion of session in Eager Execution mode. See Eager Execution for more details.
In your code, you have 2 options :
Recommended if you're in a development phase. This replaces tf.InteractiveSession in TF 1.x which you're using in your code
import tensorflow as tf
# no need for InteractiveSession(), eager execution is ON by default
my_tensor=tf.random.uniform((4,4),minval=0,maxval=1) # you now print the value of my_tensor
my_var=tf.Variable(initial_value=my_tensor) # you can now print my_var
# no need for global_variables_initializer()
# no need for sess.run
If you really want to maintain TF 1.x coding style, just disable eager execution.
import tensorflow as tf
tf.compat.v1.disable_eager_execution() # <<< Note this
sess=tf.compat.v1.InteractiveSession()
my_tensor=tf.random.uniform((4,4),minval=0,maxval=1)
my_var=tf.Variable(initial_value=my_tensor)
init=tf.compat.v1.global_variables_initializer()
sess.run(init)
sess.run(my_var)
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.