AttributeError: module 'tensorflow' has no attribute 'get_default_graph' [SOLVED]
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:
- Error
- Reason for Error
- Fix for the error
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
Fix 1
To fix the error, replace the code line tf.Session()
with tf.compat.v1.get_default_graph()
.
tf.get_default_graph()
to
tf.compat.v1.get_default_graph()
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)
Fix 2
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.
Fix 3
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 4
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.