AttributeError: module 'tensorflow' has no attribute 'get_default_graph' [SOLVED]
Get FREE domain for 1st year and build your brand new site
In this article, we have demonstrated how to fix the error "AttributeError: module 'tensorflow' has no attribute 'get_default_graph'" while running a TensorFlow code. We have illustrated 4 fixes.
Table of contents:
- Reason for Error
- Fix for the error
Error on running a TensorFlow code:
AttributeError: module 'tensorflow' has no attribute 'get_default_graph'
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
The code snippet is used as follows:
import tensorflow as tf sess = tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph(), config=session_conf)
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.
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.
If you are working with Keras and have the following code line then it is the source of the error.
from keras.models import Sequential
The fix is to replace the above code line with:
from tensorflow.keras.models import Sequential
The reason is same that is API mismatch.
With this article at OpenGenus, you must have fixed the error easily. Continue working with TensorFlow code.