How to Fix Module ‘TensorFlow’ Has No Attribute ‘get_default_graph’

Recently, I was working on a deep learning project to analyze customer data for a US retail company when I encountered an error that stopped me in my tracks: AttributeError: module ‘tensorflow’ has no attribute ‘get_default_graph’.

This error usually happens when attempting to run TensorFlow 1.x code in a TensorFlow 2.x environment.

The transition from TensorFlow 1.x to 2.x brought significant API changes, and understanding these differences is crucial for solving this error.

In this article, I will share several practical methods to resolve this issue, drawing on my decade of experience with Python and machine learning frameworks.

What Causes the ‘No Attribute get_default_graph’ Error?

The root cause of this error is the major API redesign in TensorFlow 2.0. In TensorFlow 1.x, the get_default_graph() function was commonly used to access the default computational graph.

However, TensorFlow 2.x embraces eager execution by default, which executes operations immediately rather than building a computational graph first.

This architectural shift eliminated the need for get_default_graph() in most cases, leading to its removal from the main namespace.

Read ModuleNotFoundError: No module named tensorflow Keras

Method 1: Use TensorFlow Compatibility Module

The simplest and most recommended approach is to use TensorFlow’s compatibility module, which provides access to TensorFlow 1.x functionality.

import tensorflow as tf

# Disable eager execution to mimic TF 1.x behavior
tf.compat.v1.disable_eager_execution()

# Use compatibility module to get the default graph (TF 1.x style)
graph = tf.compat.v1.get_default_graph()

# Define a simple computation in the graph
a = tf.constant(3)
b = tf.constant(4)
c = tf.add(a, b)

# Create a session to run the graph
with tf.compat.v1.Session(graph=graph) as sess:
    result = sess.run(c)
    print("Result of 3 + 4 is:", result)

Output:

Result of 3 + 4 is: 7

I executed the above example code and added the screenshot below.

module 'tensorflow' has no attribute 'get_default_graph'

This approach allows you to use TensorFlow 1.x functions within your TensorFlow 2.x code without needing to downgrade your entire installation.

It’s particularly useful when you’re working with legacy code or tutorials that haven’t been updated for TensorFlow 2.x.

Check out ModuleNotFoundError: No module named ‘tensorflow.keras.utils.np_utils’

Method 2: Disable Eager Execution

If you’re migrating a larger codebase that extensively uses TensorFlow 1.x graph-based execution, you might want to disable eager execution entirely:

import tensorflow as tf

# Disable eager execution (to use TensorFlow 1.x-style graph execution)
tf.compat.v1.disable_eager_execution()

# Access the default graph using the v1 compatibility module
graph = tf.compat.v1.get_default_graph()
print("Default graph obtained:", graph)

# Define a simple computation using the graph
a = tf.constant(6)
b = tf.constant(9)
c = tf.add(a, b)

# Run the graph using a Session
with tf.compat.v1.Session(graph=graph) as sess:
    result = sess.run(c)
    print("Result of 6 + 9 is:", result)

Output:

Result of 6 + 9 is: 15

I executed the above example code and added the screenshot below.

attributeerror module 'tensorflow' has no attribute 'get_default_graph'

This approach is useful for temporarily running older code, but I recommend gradually updating your codebase to use TensorFlow 2.x patterns for long-term maintenance.

Disabling eager execution can be a temporary solution while transitioning to newer TensorFlow versions.

Read ModuleNotFoundError: No Module Named ‘keras.utils.vis_utils’

Method 3: Downgrade to TensorFlow 1.x

If you’re working on a project that heavily relies on TensorFlow 1.x functionality and can’t be easily migrated, you might consider downgrading your TensorFlow installation:

pip uninstall tensorflow
pip install tensorflow==1.15.0

After downgrading, the original code should work:

import tensorflow as tf
graph = tf.get_default_graph()  # This will now work

However, I only recommend this approach for legacy projects that can’t be updated. TensorFlow 1.x is no longer receiving new features, and security updates will eventually cease.

Check out ModuleNotFoundError: No module named ‘tensorflow.python.keras’

Method 4: Update Your Code to TensorFlow 2.x Patterns

The best long-term solution is to update your code to follow TensorFlow 2.x patterns. In many cases, you don’t need get_default_graph() at all with eager execution.

Here’s an example of how you might refactor code that used get_default_graph():

# TensorFlow 1.x approach
import tensorflow as tf_old
graph = tf_old.get_default_graph()
with graph.as_default():
    # Define operations
    x = tf_old.placeholder(tf_old.float32, shape=[None, 784])
    W = tf_old.Variable(tf_old.zeros([784, 10]))
    b = tf_old.Variable(tf_old.zeros([10]))
    y = tf_old.matmul(x, W) + b

# TensorFlow 2.x approach
import tensorflow as tf
# No need for graphs or placeholders
x = tf.keras.Input(shape=(784,))
model = tf.keras.Sequential([
    tf.keras.layers.Dense(10)
])
y = model(x)

This modern approach is not only more concise but also more intuitive and aligns with current deep learning best practices.

Check out AttributeError: module ‘tensorflow’ has no attribute ‘count_nonzero’

Method 5: Check Version Compatibility

Sometimes, the error occurs due to incompatible versions of TensorFlow and its dependencies. You can check your installed version using:

import tensorflow as tf
print(tf.__version__)

I executed the above example code and added the screenshot below.

tensorflow has no attribute session

Make sure your code is compatible with the installed version. Version compatibility issues are common, especially when using multiple TensorFlow-related packages.

Read AttributeError: module ‘tensorflow’ has no attribute ‘reduce_sum’

Real-World Example: Image Classification for US Retail

Let me share how I solved this error in a real project for a US retail chain. We were building an image classification system to automatically categorize product images for their e-commerce platform.

The original code used TensorFlow 1.x with graph-based execution:

import tensorflow as tf

# This would cause the error in TensorFlow 2.x
graph = tf.get_default_graph()
with tf.Session() as sess:
    # Load pre-trained model
    saver = tf.train.import_meta_graph('retail_model.meta')
    saver.restore(sess, 'retail_model')

    # Get tensors from graph
    x = graph.get_tensor_by_name('input:0')
    y = graph.get_tensor_by_name('output:0')

    # Run inference
    predictions = sess.run(y, feed_dict={x: product_images})

I updated it to use TensorFlow 2.x compatibility features:

import tensorflow as tf

# Use compatibility module
tf.compat.v1.disable_eager_execution()
graph = tf.compat.v1.get_default_graph()
with tf.compat.v1.Session() as sess:
    # Load pre-trained model
    saver = tf.compat.v1.train.import_meta_graph('retail_model.meta')
    saver.restore(sess, 'retail_model')

    # Get tensors from graph
    x = graph.get_tensor_by_name('input:0')
    y = graph.get_tensor_by_name('output:0')

    # Run inference
    predictions = sess.run(y, feed_dict={x: product_images})

This intermediate solution allowed us to get the system running quickly while we worked on a full migration to TensorFlow 2.x with Keras.

Check out Solve AttributeError: module ‘tensorflow’ has no attribute ‘py_function’

Common Issues to Avoid

When dealing with this error, be aware of these common pitfalls:

  1. Mixing different TensorFlow versions: Make sure all your TensorFlow-related packages are compatible.
  2. Incomplete migration: Partially updating code can lead to confusing errors. Be thorough when adding compatibility imports.
  3. Overlooking other API changes: The get_default_graph() function isn’t the only change in TensorFlow 2.x. Other functions like placeholder() and Session() have also been moved to the compatibility module.
  4. Using outdated tutorials: Many online tutorials still use TensorFlow 1.x syntax. Always check the TensorFlow version mentioned in tutorials.

I hope you found this article helpful. The TensorFlow API changes can be frustrating to deal with, but understanding the differences between versions will save you a lot of time debugging these issues. Whether you choose to use the compatibility module, disable eager execution, or fully update your code to TensorFlow 2.x patterns, you now have the knowledge to fix the module 'tensorflow' has no attribute 'get_default_graph' error and move forward with your machine learning projects.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.