问题及解决方法

1、AttributeError: module ‘tensorflow’ has no attribute
解决办法:

>>> tf.compat.v1.disable_eager_execution()
>>> sess = tf.compat.v1.Session()

2、RuntimeError: The Session graph is empty.
解决办法:调整变量定义顺序。

>>> hello=tf.constant("Hello Tensorflow")
>>> sess = tf.compat.v1.Session()
>>> sess.run(hello)
b'Hello Tensorflow'

操作实录

F:\tensorflow-2.4.0>env\Scripts\activate

(env) F:\tensorflow-2.4.0>python
Python 3.7.4 (default, Aug 9 2019, 18:34:13) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32

Warning:
This Python interpreter is in a conda environment, but the environment has
not been activated. Libraries may fail to load. To activate this environment
please see https://conda.io/activation

Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
>>> hello=tf.constant("Hello Tensorflow")
2021-08-10 09:36:26.404274: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
##问题1:版本2.5.0没有Session属性
>>> sess=tf.Session()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'tensorflow' has no attribute 'Session'
##问题1的解决办法:
>>> tf.compat.v1.disable_eager_execution()
>>> sess = tf.compat.v1.Session()
##问题2:变量定义顺序错误,导致提示session为空
>>> sess.run(hello)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "F:\tensorflow-2.4.0\env\lib\site-packages\tensorflow\python\client\session.py", line 968, in run
run_metadata_ptr)
File "F:\tensorflow-2.4.0\env\lib\site-packages\tensorflow\python\client\session.py", line 1116, in _run
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:解决办法,调整正确定义顺序
>>> hello=tf.constant("Hello Tensorflow")
>>> sess = tf.compat.v1.Session()
>>> sess.run(hello)
b'Hello Tensorflow'
>>> print(sess.run(hello))
b'Hello Tensorflow'
>>>