Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session'
When I am executing the command sess = tf.Session()
in Tensorflow 2.0 environment, I am getting an error message as below:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'tensorflow' has no attribute 'Session'
System Information:
- OS Platform and Distribution: Windows 10
- Python Version: 3.7.1
- Tensorflow Version: 2.0.0-alpha0 (installed with pip)
Steps to reproduce:
Installation:
- pip install --upgrade pip
- pip install tensorflow==2.0.0-alpha0
- pip install keras
- pip install numpy==1.16.2
Execution:
- Execute command: import tensorflow as tf
- Execute command: sess = tf.Session()
Solution 1:
According to TF 1:1 Symbols Map
, in TF 2.0 you should use tf.compat.v1.Session()
instead of tf.Session()
https://docs.google.com/spreadsheets/d/1FLFJLzg7WNP6JHODX5q8BDgptKafq_slHpnHVbJIteQ/edit#gid=0
To get TF 1.x like behaviour in TF 2.0 one can run
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
but then one cannot benefit of many improvements made in TF 2.0. For more details please refer to the migration guide https://www.tensorflow.org/guide/migrate
Solution 2:
TF2 runs Eager Execution by default, thus removing the need for Sessions. If you want to run static graphs, the more proper way is to use tf.function()
in TF2. While Session can still be accessed via tf.compat.v1.Session()
in TF2, I would discourage using it. It may be helpful to demonstrate this difference by comparing the difference in hello worlds:
TF1.x hello world:
import tensorflow as tf
msg = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(msg))
TF2.x hello world:
import tensorflow as tf
msg = tf.constant('Hello, TensorFlow!')
tf.print(msg)
For more info, see Effective TensorFlow 2
Solution 3:
I faced this problem when I first tried python after installing windows10 + python3.7(64bit) + anacconda3 + jupyter notebook.
I solved this problem by refering to "https://vispud.blogspot.com/2019/05/tensorflow200a0-attributeerror-module.html"
I agree with
I believe "Session()" has been removed with TF 2.0.
I inserted two lines. One is tf.compat.v1.disable_eager_execution()
and the other is sess = tf.compat.v1.Session()
My Hello.py is as follows:
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
hello = tf.constant('Hello, TensorFlow!')
sess = tf.compat.v1.Session()
print(sess.run(hello))