How to Fix: Module ‘keras.backend’ Has No Attribute ‘set_session’

Recently, I was working on a deep learning project that involved training a neural network to predict stock prices for a Fortune 500 company. When I tried to run my code, I encountered an error that many TensorFlow and Keras users face: AttributeError: module ‘keras.backend’ has no attribute ‘set_session’.

This error can be frustrating, especially during an important project. It usually arises from a version mismatch or changes in the TensorFlow/Keras API between versions.

In this article, I’ll walk you through several methods to fix this error based on my experience. Let’s get in!

What Causes ‘set_session’ Error?

The set_session error typically occurs due to:

  1. Using TensorFlow 2.x with code written for TensorFlow 1.x
  2. Import conflicts between standalone Keras and TensorFlow’s integrated Keras
  3. Incorrect import statements in your code

This is a common issue many developers face when migrating projects or following older tutorials online.

Method 1: Use TensorFlow’s Compatibility Module

TensorFlow 2.x provides a compatibility layer that allows you to run TensorFlow 1.x code. This is the simplest solution if you don’t want to rewrite your code.

import tensorflow.compat.v1 as tf
tf.disable_eager_execution()  # simulate TF1.x graph mode

# Create a session manually (like TF1.x)
sess = tf.Session()

a = tf.constant(10)
b = tf.constant(20)
c = a + b

# Explicit graph execution
result = sess.run(c)
print("Result:", result)

Output:

Result: 30

You can see the output in the screenshot below.

attributeerror module 'keras._tf_keras.keras.backend' has no attribute 'set_session'

This approach uses the compatibility layer in TensorFlow 2.x to access TensorFlow 1.x functionality, which includes the set_session function.

Read ModuleNotFoundError: No module named ‘tensorflow.python.keras’

Method 2: Update Your Code for TensorFlow 2.x

If you’re starting a new project or willing to update your code, it’s better to adapt to the TensorFlow 2.x API. In TensorFlow 2.x, sessions are managed automatically, so set_session is no longer needed.

import tensorflow as tf
import numpy as np

# Simple model: input -> Dense(1)
model = tf.keras.Sequential([
    tf.keras.Input(shape=(1,)),  # Recommended way instead of input_shape in layer
    tf.keras.layers.Dense(1)
])

# Compile the model
model.compile(optimizer='sgd', loss='mse')

# Dummy training data (y = 2x)
x = np.array([[1], [2], [3], [4]], dtype=float)
y = np.array([[2], [4], [6], [8]], dtype=float)

# Train the model
model.fit(x, y, epochs=10, verbose=0)

# Make a prediction
input_data = np.array([[5]], dtype=float)
pred = model.predict(input_data, verbose=0)

print("Prediction for input 5:", pred[0][0])

Output:

Prediction for input 5: 7.356321

You can see the output in the screenshot below.

module 'keras.api.backend' has no attribute 'sum'

This approach embraces the newer, cleaner API of TensorFlow 2.x, which uses eager execution by default.

Method 3: Downgrade to TensorFlow 1.x

If you’re working with legacy code that heavily relies on TensorFlow 1.x functionality, downgrading might be a practical solution.

# Uninstall current TensorFlow version
pip uninstall tensorflow tensorflow-gpu

# Install TensorFlow 1.x
pip install tensorflow==1.15.0

After downgrading, you can use the original code with set_session:

import tensorflow as tf
from keras import backend as K

# Create a session
session = tf.Session()

# Set the session
K.set_session(session)

# Your model code here

While this works, I recommend this approach only for legacy projects that cannot be easily migrated.

Method 4: Use the Correct Import Path

Sometimes the error occurs because of confusion between standalone Keras and TensorFlow’s integrated Keras. Make sure you’re using consistent imports:

# For standalone Keras with TensorFlow backend
from keras import backend as K

# For TensorFlow's integrated Keras
from tensorflow.keras import backend as K

If you’re using standalone Keras with TensorFlow 1.x, you should be able to use set_session. If you’re using TensorFlow’s integrated Keras with TensorFlow 2.x, you’ll need to use the compatibility module as shown in Method 1.

Method 5: Use a Virtual Environment for Version Control

One best practice I always follow is using virtual environments to manage package versions for different projects:

# Create a virtual environment
python -m venv tf1_env

# Activate the environment
# On Windows
tf1_env\Scripts\activate
# On macOS/Linux
source tf1_env/bin/activate

# Install specific versions
pip install tensorflow==1.15.0 keras==2.3.1

This approach allows you to maintain different TensorFlow/Keras versions for different projects without conflicts.

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

Real-World Example: Train a Stock Price Predictor

Let’s put this into a practical context with a simplified example of a stock price prediction model:

import numpy as np
import tensorflow as tf
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt

# For TensorFlow 2.x
print(f"Using TensorFlow version: {tf.__version__}")

# Load stock data (example using Apple stock)
# In a real scenario, you might use APIs like yfinance
df = pd.read_csv('AAPL_stock_data.csv')
data = df['Close'].values.reshape(-1, 1)

# Normalize the data
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data)

# Prepare training data
def create_dataset(dataset, time_step=60):
    X, y = [], []
    for i in range(len(dataset) - time_step - 1):
        X.append(dataset[i:(i + time_step), 0])
        y.append(dataset[i + time_step, 0])
    return np.array(X), np.array(y)

time_step = 60
X, y = create_dataset(scaled_data, time_step)

# Reshape input for LSTM [samples, time steps, features]
X = X.reshape(X.shape[0], X.shape[1], 1)

# Create the LSTM model
model = tf.keras.Sequential([
    tf.keras.layers.LSTM(50, return_sequences=True, input_shape=(time_step, 1)),
    tf.keras.layers.LSTM(50, return_sequences=False),
    tf.keras.layers.Dense(25),
    tf.keras.layers.Dense(1)
])

# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')

# Train the model
model.fit(X, y, batch_size=32, epochs=20)

# No need for explicit session management in TensorFlow 2.x

This example works with TensorFlow 2.x without needing to call set_session. If you needed to run this with TensorFlow 1.x code that uses set_session you’d apply Method 1 from above.

Avoid Future API Compatibility Issues

To avoid similar issues in the future:

  1. Always specify library versions in your requirements.txt or environment.yml files
  2. Check the TensorFlow and Keras documentation for API changes when upgrading
  3. Consider using TensorFlow’s SavedModel format instead of Keras’ model saving to ensure better compatibility

What About My Existing Models?

If you have models saved with older versions of Keras/TensorFlow, you might need to:

  1. Load them using the same version they were saved with
  2. Convert them to the newer format (possible in some cases)
  3. Rebuild them from scratch if necessary

When you encounter the module 'keras.backend' has no attribute 'set_session' error, it’s usually a sign that you’re mixing TensorFlow/Keras versions or using outdated code patterns. The best approach depends on your specific situation:

  • For new projects, embrace TensorFlow 2.x’s eager execution and simpler API.
  • For existing projects, consider using the compatibility layer.
  • For legacy projects that cannot be migrated, maintain a separate environment with TensorFlow 1.x.

I hope this article helps you resolve the set_session error in your projects! If you have any questions or suggestions, please 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.