AttributeError: module 'tensorflow' has no attribute 'Session' [SOLVED]
In this article, we have demonstrated how to fix the error "AttributeError: module 'tensorflow' has no attribute 'Session'" while running a TensorFlow code.
Table of contents:
- Error
- Reason for Error
- Fix for the error
In short, there is one conversion:
tf.Session() => tf.compat.v1.Session()
Error
Error on running a TensorFlow code:
AttributeError: module 'tensorflow' has no attribute 'Session'
Reason for Error
The reason for the error is that the code you are running is using an old TensorFlow API. The code follows the API of TensorFlow v1.x while the TensorFlow environment has version v2.x.
This particular API for Session has been renamed in TFv2.x / moved to compat.v1.
Fix for the error
Fix 1
To fix the error, replace the code line tf.Session()
with tf.compat.v1.Session()
.
tf.Session()
to
tf.compat.v1.Session()
Fix 2
If you do not want to update the code, then you can place the following code snippet at the top of the file:
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
This will update the API (note the use of compat.v1) and disable behaviour specific to version v2.
Fix 3
An alternative fix is to use TensorFlow version 1.x instead of 2.x. You can install the previous version of TensorFlow using pip command:
pip install tensorflow==1.15.5
If you want to build TensorFlow from source, clone the TensorFlow code and checkout to a previous version and then, build it.
git clone https://github.com/tensorflow/tensorflow.git
git checkout r1.15
Following the steps in this guide to build TensorFlow locally: build guide.
With this article at OpenGenus, you must have fixed the error easily. Continue working with TensorFlow code.