How to Fix Module ‘TensorFlow’ has no attribute ‘session’

Recently, I worked on a deep learning project for a client in New York who needed an image classification model. After setting up my environment and installing TensorFlow 2.x, I ran into an error that many Python developers face: AttributeError: Module ‘tensorflow’ has no attribute ‘session’.

This error can be very frustrating, especially when following tutorials or migrating code from TensorFlow 1.x to 2.x. The good news is that simple solutions exist for this problem.

In this article, I will walk you through why this error occurs and show you multiple ways to fix it. Let’s dive in!

Understand the Error

The error occurs primarily because of the significant API changes between TensorFlow 1.x and TensorFlow 2.x. In TensorFlow 1.x, sessions were a core concept used to execute operations, but in TensorFlow 2.x, eager execution became the default mode.

When you try to use tf.session() in TensorFlow 2.x, Python tells you that the module has no such attribute because the API has changed.

Method 1: Use tf.compat.v1.Session()

The quickest way to fix this error is to use the compatibility layer that TensorFlow 2.x provides. This allows you to use TensorFlow 1.x code in a TensorFlow 2.x environment.

Here’s how you can modify your code:

import tensorflow as tf

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

# Create a session using the compatibility API
session = tf.compat.v1.Session()

# Define a simple computation graph
a = tf.constant(10)
b = tf.constant(15)
c = tf.add(a, b)

# Run the computation using the session
result = session.run(c)

# Print the output
print("Sum of 10 and 15 is:", result) 

Output:

Sum of 10 and 15 is: 25

You can see the output in the screenshot below.

module 'tensorflow' has no attribute 'session'

This approach is especially useful when you’re working with legacy code or following older tutorials that use TensorFlow 1.x syntax. Disabling eager execution is a crucial step when using the compatibility layer.

Read AttributeError: Module ‘tensorflow’ has no attribute ‘global_variables_initializer’

Method 2: Update Your Code to TensorFlow 2.x Style

While the compatibility layer works, the recommended approach is to update your code to use TensorFlow 2.x’s eager execution style, which is more Pythonic and easier to debug.

Here’s how to rewrite session-based code in the TensorFlow 2.x style:

import tensorflow as tf

# In TensorFlow 2.x, operations execute immediately
# No need for sessions

# Example: Creating a tensor
tensor = tf.constant([[1, 2], [3, 4]])
print(tensor)

# Example: Matrix multiplication
a = tf.constant([[1, 2], [3, 4]])
b = tf.constant([[1, 1], [1, 1]])
c = tf.matmul(a, b)
print(c)

Output:

tf.Tensor(
[[1 2]
 [3 4]], shape=(2, 2), dtype=int32)
tf.Tensor(
[[3 3]
 [7 7]], shape=(2, 2), dtype=int32)

You can see the output in the screenshot below.

attributeerror module 'tensorflow' has no attribute 'session'. did you mean 'version'

With eager execution, TensorFlow operations behave like regular Python functions – they execute immediately and return values, eliminating the need for sessions.

Read AttributeError: Module ‘tensorflow’ has no attribute ‘truncated_normal_initializer’

Method 3: Install the Specific TensorFlow Version

If you’re following a tutorial or working with code that specifically requires TensorFlow 1.x, you might want to install that version instead of trying to adapt the code.

You can install TensorFlow 1.x using pip:

# Uninstall current TensorFlow
pip uninstall tensorflow

# Install TensorFlow 1.15 (last 1.x version)
pip install tensorflow==1.15

After installing TensorFlow 1.x, you can use tf.Session() directly without the compatibility layer:

import tensorflow as tf

# Create a session
session = tf.Session()

# Your TensorFlow 1.x code here

However, keep in mind that TensorFlow 1.x is no longer actively maintained, so this should be considered a temporary solution.

Method 4: Use Virtual Environments for Different Projects

If you’re working on multiple projects that require different TensorFlow versions, it’s best to use virtual environments.

Here’s how to set up and use a virtual environment for a TensorFlow 1.x project:

# Create a virtual environment
python -m venv tf1_env

# Activate the environment (Windows)
tf1_env\Scripts\activate

# Activate the environment (Mac/Linux)
source tf1_env/bin/activate

# Install TensorFlow 1.15
pip install tensorflow==1.15

For a TensorFlow 2.x project:

# Create a virtual environment
python -m venv tf2_env

# Activate the environment
# (use appropriate activation command for your OS)

# Install TensorFlow 2.x
pip install tensorflow

This approach allows you to switch between environments without conflicts.

Check out Module ‘tensorflow’ has no attribute ‘truncated_normal’

Real-World Example: Image Classification for a Fashion Retailer

Let me share a real-world example. I was working with a fashion retailer in Los Angeles who wanted to automatically categorize their product images. Their existing codebase used TensorFlow 1.x, but I needed to run it in a TensorFlow 2.x environment.

Here’s how I modified the core part of their code:

# Original TensorFlow 1.x code
import tensorflow as tf

# Create placeholders for input images
x = tf.placeholder(tf.float32, [None, 224, 224, 3])
y = tf.placeholder(tf.float32, [None, 10])

# Define model and training operations
# ...

# Run training in a session
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    # Training loop
    # ...

Modified for TensorFlow 2.x:

import tensorflow as tf

# Disable eager execution for this legacy code
tf.compat.v1.disable_eager_execution()

# Create placeholders using compatibility API
x = tf.compat.v1.placeholder(tf.float32, [None, 224, 224, 3])
y = tf.compat.v1.placeholder(tf.float32, [None, 10])

# Define model and training operations
# ...

# Run training in a session
with tf.compat.v1.Session() as sess:
    sess.run(tf.compat.v1.global_variables_initializer())
    # Training loop
    # ...

This approach allowed us to run their existing model without rewriting everything, while planning a gradual migration to native TensorFlow 2.x code.

Best Practices When Working with TensorFlow

Based on my experience with both versions of TensorFlow, here are some best practices:

  1. Check the TensorFlow version at the beginning of your code to ensure compatibility.
  2. Document which version your code is designed for.
  3. Consider using virtual environments for projects with different requirements.
  4. For new projects, use TensorFlow 2.x and eager execution.
  5. For existing projects, decide whether to use the compatibility layer or migrate the code.

I hope you found this article helpful. If you have any questions or suggestions, feel free to leave them in the comments below.

Other Python articles you may also like:

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.