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:
- Using TensorFlow 2.x with code written for TensorFlow 1.x
- Import conflicts between standalone Keras and TensorFlow’s integrated Keras
- 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: 30You can see the output in the screenshot below.

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.356321You can see the output in the screenshot below.

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.0After 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 hereWhile 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 KIf 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.1This 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.xThis 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:
- Always specify library versions in your requirements.txt or environment.yml files
- Check the TensorFlow and Keras documentation for API changes when upgrading
- 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:
- Load them using the same version they were saved with
- Convert them to the newer format (possible in some cases)
- 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:
- AttributeError: module ‘tensorflow’ has no attribute ‘reduce_sum’
- Solve AttributeError: module ‘tensorflow’ has no attribute ‘py_function’
- ModuleNotFoundError: No module named ‘tensorflow.keras.layers’

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.