在 Tensorflow 2 中 运行 sess.run 时出现 "graph is empty" 错误

Getting "graph is empty" error when running sess.run in Tensorflow 2

我在 运行 sess.run(init) 时不断收到此错误。我有基本的 tensorflow 1.3 知识,但现在我正在使用 tensorflow 2.2 并不断收到这些错误

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 有一个新功能 Eager Execution,它会在您将操作添加到图表时执行您的操作,而无需 sess.run。实际上,在 Eager Execution 模式下没有会话的概念。有关详细信息,请参阅 Eager Execution

在您的代码中,您有 2 个选项:

利用 Eager Execution

如果您处于开发阶段,推荐使用。这将替换您在代码

中使用的 TF 1.x 中的 tf.InteractiveSession
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

禁用急切执行

如果您真的想保持 TF 1.x 编码风格,只需禁用 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)