Attributeerror module tensorflow has no attribute get_default_graph error mainly occurs because of importing get_default_graph sequential from the incorrect package. Actually, TensorFlow 2. x do not support session and TensorFlow 1. x is completely on top of the sessions. If we somehow write our code in TensorFlow 1. x friendly code and use TensorFlow 2.o installation in the Interpreter, Then we encounter this error.
Well, there are many situations where we encounter this error. But the root cause will be around the below cause –
- Explicitly writing the code where we create sessions and use get_default_graph externally.
- Invoking modules like sequential which ultimately import get_default_graph internally.
Attributeerror module tensorflow has no attribute get_default_graph ( Solution ) –
The easiest way to fix this kind of tensorflow-related AttributeError is using tf.compat.v1.get_default_graph() if using get_default_graph() externally. If the error is occurring implicitly then the solution varies with the module import statement. Anyways let’s explore both separately in the below sections.
Solution 1: Using tf.compat.v1.get_default_graph() –
If the Interpreter has installed the version of tensorflow is 2. x series. If the code has get_default_graph() then it generates the same error. To avoid this use tf.compat.v1.get_default_graph() . Here is the complete integrated code.
import tensorflow as tf sess = tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph(), config=session_conf) tf.compat.v1.keras.backend.set_session(sess)
Solution 2: Incorrect import –
Since the migration was quite impacting in release 1. x series to tensorflow 2.x, also it is just a few years ago. Since we have lot of code based on tensorflow 1.x is still available on the developer community. Because of the lack of description around it, sometimes we use older syntax. For example, keras is available as a module in tensorFlow now with an equivalent structure. All we need to change the import statement because of this package migration.
The correct way of Importing sequential –
from tensorflow.keras.models import Sequential
Incorrect way of Importing sequential –
from keras.models import Sequential
Here are some of the similar errors with same root cause and fix. Please go through them for better understanding.
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.