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:
- Reason for Error
- Fix for the error
In short, there is one conversion:
tf.Session() => tf.compat.v1.Session()
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
To fix the error, replace the code line
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.
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.