Recently, I was working on a deep learning project where I needed to build a CNN model for image classification. When I tried to import the layers module from TensorFlow Keras, I encountered this error: ModuleNotFoundError: no module named ‘tensorflow.keras.layers’.
This is a common error that many Python developers face when working with TensorFlow and Keras. The good news is that it’s relatively easy to fix once you understand what’s causing it.
In this article, I’ll walk you through several methods to resolve this error based on my experience. Let’s get in!
What Causes This Error?
Before we jump into the solutions, let’s understand why this error occurs:
- TensorFlow is not installed in your environment
- You have an outdated version of TensorFlow
- You’re using standalone Keras instead of the integrated TensorFlow Keras
- Your Python environment is corrupted
- Incorrect import statements
Read ModuleNotFoundError: No module named ‘tensorflow.keras.layers’
Method 1: Install or Upgrade TensorFlow
The most common cause of this error is that TensorFlow isn’t installed or you’re using an outdated version.
Here’s how to fix it:
# Install TensorFlow
pip install tensorflow
# Or upgrade to the latest version
pip install --upgrade tensorflowAfter installation, verify that TensorFlow is properly installed:
import tensorflow as tf
print(tf.__version__)I executed the above example code and added the screenshot below.

If you’re using a Jupyter notebook, restart the kernel after installation.
Check out the TensorFlow Convolution Neural Network
Method 2: Use the Correct Import Statement
Since TensorFlow 2.0, Keras has been fully integrated into TensorFlow. You should use the following import statement:
# Correct import statement
from tensorflow.keras import layers
# Example usage
model = tf.keras.Sequential([
layers.Dense(128, activation='relu'),
layers.Dense(10, activation='softmax')
])Don’t use the standalone Keras import unless you specifically need it:
# Avoid using this for TensorFlow 2.x
import keras # This is standalone KerasMethod 3: Create a Fresh Virtual Environment
Sometimes, package conflicts can cause this error. Creating a fresh virtual environment can help:
# Create a new virtual environment
python -m venv tf_env
# Activate the environment (Windows)
tf_env\Scripts\activate
# Activate the environment (macOS/Linux)
source tf_env/bin/activate
# Install TensorFlow
pip install tensorflowThis ensures you have a clean environment with compatible packages.
Read AttributeError: Module ‘tensorflow’ has no attribute ‘placeholder’
Method 4: Install TensorFlow with GPU Support (Optional)
If you’re working with large models and have an NVIDIA GPU, you might want to install the GPU version:
pip install tensorflow-gpuNote: For TensorFlow 2.x, the tensorflow package includes GPU support by default if CUDA is properly set up on your system.
Method 5: Check for Conda Environment Issues
If you’re using Anaconda, you might need to install TensorFlow through conda:
conda install tensorflowOr create a new conda environment specifically for TensorFlow:
conda create -n tf_env python=3.8
conda activate tf_env
conda install tensorflowMethod 6: Troubleshooting Import Issues
If you’re still facing issues, try this debugging approach:
# Check if tensorflow is installed
import sys
print([pkg for pkg in sys.modules if 'tensorflow' in pkg])
# Check the installation path
import tensorflow as tf
print(tf.__file__)I executed the above example code and added the screenshot below.

This will help you identify if TensorFlow is properly installed and where it’s located.
Read AttributeError: Module ‘tensorflow’ has no attribute ‘sparse_tensor_to_dense’
Real-World Example: Building an Image Classifier
Let’s put this into practice with a real example. Imagine we’re building a model to classify images of famous American landmarks:
import tensorflow as tf
from tensorflow.keras import layers, models
import numpy as np
# Create a simple CNN model
model = models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 3)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(128, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dense(5, activation='softmax') # 5 classes: Statue of Liberty, Golden Gate Bridge, etc.
])
# Compile the model
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# Print model summary
model.summary()This code should run without any ModuleNotFoundError if TensorFlow is properly installed.
Common Pitfalls to Avoid
- Mixing TensorFlow versions: Avoid having multiple versions of TensorFlow installed simultaneously.
- Using standalone Keras with TensorFlow 2.x: Stick to
tensorflow.kerasinstead of standalone Keras. - Incompatible Python versions: TensorFlow has specific Python version requirements. Check the official compatibility matrix.
- Skipping environment activation: Always make sure your virtual environment is activated before installing packages or running code.
I hope this article has helped you resolve the ModuleNotFoundError: no module named 'tensorflow.keras.layers' error. Remember that maintaining a clean Python environment and using the correct import statements are key to avoiding these types of errors.
If you’re still facing issues, check the official TensorFlow documentation for the most up-to-date installation instructions, or let me know in the comments below!
Other Python articles you may also like:
- Module ‘tensorflow’ has no attribute ‘sparse_placeholder’
- Module ‘tensorflow’ has no attribute ‘optimizers’
- Module ‘tensorflow’ has no attribute ‘log’

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.