ModuleNotFoundError: No module named 'tensorflow.keras' means Python cannot import Keras through TensorFlow. There are four usual causes: TensorFlow is not installed in the Python environment that runs your script, a file or folder named tensorflow in your project hides the real package, your code uses an import path that was removed in Keras 3 (for example tensorflow.keras.layers.experimental or keras.layers.convolutional), or your editor is checking a different interpreter. This guide reproduces each error, shows the exact fix, and lists the old imports with their Keras 3 replacements.
Every error and fix below was run for real with Python 3.12.5, TensorFlow 2.21.0 and Keras 3.15.1 in the Windows Command Prompt. Official references: install TensorFlow with pip and the Keras getting started guide, which explains Keras 3 in TensorFlow 2.16 and later.
Quick fix
| Error message | Cause | Fix |
|---|---|---|
| No module named ‘tensorflow’ | TensorFlow is not installed in this Python | python -m pip install tensorflow with the same python you run |
| No module named ‘tensorflow.keras’; ‘tensorflow’ is not a package | A file named tensorflow.py in your folder | Rename the file and delete __pycache__ |
| No module named ‘tensorflow.keras.layers.experimental’ | Removed in Keras 3 | from keras import layers then layers.Rescaling, layers.Normalization… |
| No module named ‘keras.layers.convolutional’ / ‘merge’ / ‘core’ | Keras 2 internal modules, removed in Keras 3 | from keras.layers import Conv2D, concatenate, Dense |
| Import “tensorflow.keras” could not be resolved | VS Code / Pylance warning, not a Python error | Use from tensorflow import keras or import keras, and select the right interpreter |
Step 1: check which Python and TensorFlow you are running
Most cases come down to installing TensorFlow in one environment and running the script in another (global Python vs a virtual environment, Anaconda vs python.org, Jupyter kernel vs terminal). Run this in the same way you run your failing script:
import sys
import importlib.metadata as md
print("Python:", sys.version.split()[0])
print("Running:", sys.executable) # the interpreter that runs this script
for package in ("tensorflow", "keras", "tf_keras"):
try:
print(f"{package:<11}", md.version(package))
except md.PackageNotFoundError:
print(f"{package:<11}", "NOT INSTALLED in this environment")
Output:
Python: 3.12.5
Running: C:\pyguides\tfvenv\Scripts\python.exe
tensorflow 2.21.0
keras 3.15.1
tf_keras 2.21.0
If TensorFlow shows as not installed, install it with that exact interpreter. Using python -m pip instead of plain pip guarantees that:
python -m pip install --upgrade pip
python -m pip install tensorflow
In Jupyter, run %pip install tensorflow in a cell so it installs into the notebook’s kernel, then restart the kernel. With Anaconda, activate the environment first (conda activate myenv). Also check that your Python version is supported on the TensorFlow install page: pip finds no TensorFlow wheel for unsupported versions.
Cause 1: TensorFlow is not installed in this environment
Here the same script runs in a virtual environment that only has NumPy. Python stops at the first line with the parent module name:
import tensorflow as tf
from tensorflow.keras.models import Sequential
Result:
Traceback (most recent call last):
File "C:\pyguides\train_model.py", line 1, in <module>
import tensorflow as tf
ModuleNotFoundError: No module named 'tensorflow'
See ImportError: No module named tensorflow for installation problems in more detail.
Cause 2: a file named tensorflow.py in your project
If your folder contains tensorflow.py (or a folder called tensorflow, or keras.py), Python imports that instead of the real package. Since your file is a single module, not a package, tensorflow.keras cannot exist:
from tensorflow.keras.models import Sequential
Result:
this is my own tensorflow.py
Traceback (most recent call last):
File "C:\pyguides\train_model.py", line 1, in <module>
from tensorflow.keras.models import Sequential
ModuleNotFoundError: No module named 'tensorflow.keras'; 'tensorflow' is not a package
tensorflow.py.Rename the file (for example to tf_model.py), delete the __pycache__ folder next to it, and run again.
Cause 3: import paths removed in Keras 3 (TensorFlow 2.16+)
Since TensorFlow 2.16, pip install tensorflow installs Keras 3. tensorflow.keras still works as an alias, but many Keras 2 module paths that tutorials and older projects use were removed. Running the old imports shows exactly which ones fail:
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" # hide TensorFlow info messages
os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0" # and the oneDNN start-up notice
old_imports = [
"from tensorflow.keras.layers.experimental import preprocessing",
"from tensorflow.keras.wrappers.scikit_learn import KerasClassifier",
"from keras.layers.convolutional import Conv2D",
"from keras.layers.merge import concatenate",
"from keras.layers.core import Dense",
"from keras.utils.vis_utils import plot_model",
"from keras.engine import topology",
]
for line in old_imports:
try:
exec(line)
print("works:", line)
except ImportError as e: # ModuleNotFoundError is a subclass of ImportError
print(f"{type(e).__name__}: {e}")
Output:
ModuleNotFoundError: No module named 'tensorflow.keras.layers.experimental'
ModuleNotFoundError: No module named 'tensorflow.keras.wrappers.scikit_learn'
ModuleNotFoundError: No module named 'keras.layers.convolutional'
ModuleNotFoundError: No module named 'keras.layers.merge'
ModuleNotFoundError: No module named 'keras.layers.core'
ModuleNotFoundError: No module named 'keras.utils.vis_utils'
ModuleNotFoundError: No module named 'keras.engine'
Replace them with the public Keras 3 imports:
| Old import (fails) | Keras 3 replacement |
|---|---|
from tensorflow.keras.layers.experimental import preprocessing | from keras import layers, then layers.Rescaling, layers.Normalization, layers.RandomFlip… |
from keras.layers.convolutional import Conv2D | from keras.layers import Conv2D |
from keras.layers.merge import concatenate | from keras.layers import concatenate (or Concatenate) |
from keras.layers.core import Dense | from keras.layers import Dense |
from keras.utils.vis_utils import plot_model | from keras.utils import plot_model |
from keras.utils import np_utils | from keras.utils import to_categorical |
from tensorflow.keras.wrappers.scikit_learn import KerasClassifier | pip install scikeras, then from scikeras.wrappers import KerasClassifier |
from keras.engine import ... / tensorflow.python.keras | Internal modules: use the public keras API instead |
The same model code with the new imports trains and predicts without errors (the two os.environ lines only hide TensorFlow’s start-up notices so the output is readable):
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" # hide TensorFlow info messages
os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0" # and the oneDNN start-up notice
import numpy as np
import keras # Keras 3 (installed with TensorFlow 2.16+)
from keras import layers
model = keras.Sequential([
keras.Input(shape=(4,)),
layers.Rescaling(1 / 10), # was layers.experimental.preprocessing.Rescaling
layers.Dense(8, activation="relu"),
layers.Dense(3, activation="softmax"),
])
model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])
X = np.random.default_rng(0).uniform(0, 10, size=(60, 4))
y = (X[:, 0] > 5).astype(int) + (X[:, 1] > 5).astype(int)
model.fit(X, y, epochs=3, verbose=0)
print("Keras", keras.__version__, "on backend", keras.backend.backend())
print("prediction shape:", model.predict(X[:2], verbose=0).shape)
Output:
WARNING:tensorflow:TensorFlow GPU support is not available on native Windows for TensorFlow >= 2.11. Even if CUDA/cuDNN are installed, GPU will not be used. Please use WSL2 or the TensorFlow-DirectML plugin.
Keras 3.15.1 on backend tensorflow
prediction shape: (2, 3)
tensorflow.keras vs import keras
Both give you the same Keras 3 package in TensorFlow 2.16+, so existing from tensorflow import keras code keeps working. For new code, import keras is the recommended style:
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" # hide TensorFlow info messages
os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0" # and the oneDNN start-up notice
import tensorflow as tf
from tensorflow import keras # tf.keras still works in TensorFlow 2.16+ ...
import keras as standalone_keras
print("tf.keras is Keras", keras.__version__)
print("same package as 'import keras':", keras.__version__ == standalone_keras.__version__)
Output:
tf.keras is Keras 3.15.1
same package as 'import keras': True
Keep old Keras 2 code running with tf_keras
If you cannot update a large project (or a library such as older optuna_integration.tfkeras versions) right away, install the Keras 2 package tf_keras and tell TensorFlow to use it. The environment variable must be set before TensorFlow is imported:
python -m pip install tf_keras
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" # hide TensorFlow info messages
os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0" # and the oneDNN start-up notice
os.environ["TF_USE_LEGACY_KERAS"] = "1" # must be set before TensorFlow is imported
import tensorflow as tf
from tensorflow.keras.layers.experimental import preprocessing # Keras 2 path works again
print("Dense comes from:", tf.keras.layers.Dense.__module__) # tf_keras = Keras 2
import tf_keras
print("tf_keras version:", tf_keras.__version__)
Output:
WARNING:tensorflow:From C:\pyguides\tfvenv\Lib\site-packages\tf_keras\src\losses.py:2976: The name tf.losses.sparse_softmax_cross_entropy is deprecated. Please use tf.compat.v1.losses.sparse_softmax_cross_entropy instead.
Dense comes from: tf_keras.src.layers.core.dense
tf_keras version: 2.21.0
Treat this as a bridge: tf_keras is kept for compatibility, and new features go into Keras 3. If you see No module named 'tf_keras', it means TF_USE_LEGACY_KERAS is set but the package is not installed.
Import “tensorflow.keras” could not be resolved (VS Code)
This yellow squiggle comes from Pylance, VS Code’s code checker, not from Python. tensorflow.keras is created lazily when TensorFlow is imported, so static checkers cannot always see it, and the code may still run fine. To fix it:
- Select the interpreter that has TensorFlow: Ctrl+Shift+P → Python: Select Interpreter.
- Write
from tensorflow import kerasorimport kerasinstead ofimport tensorflow.keras. - If the script really fails when you run it, go back to Step 1.
Checklist
- Run the version check with the same interpreter as your script.
- Install with
python -m pip install tensorflow(or%pipin Jupyter). - Remove any
tensorflow.py,keras.pyortensorflow/folder from your project. - Replace Keras 2 internal import paths with the public
kerasAPI. - Use
tf_keras+TF_USE_LEGACY_KERAS=1only as a temporary bridge.
Fix other common Python import errors:
- ImportError: No module named tensorflow
- No module named ‘tensorflow.keras.utils.np_utils’
- Install TensorFlow on Windows, macOS and Linux
- Upgrade TensorFlow to the latest version
Frequently asked questions
How do I fix ModuleNotFoundError: No module named ‘tensorflow.keras’?
Install TensorFlow in the environment that runs the script with python -m pip install tensorflow, remove any local tensorflow.py file, and replace Keras 2 import paths (such as layers.experimental) with the Keras 3 ones.
Is tensorflow.keras removed in TensorFlow 2.16?
No. from tensorflow import keras still works and gives you Keras 3. What was removed are old submodules like tensorflow.keras.layers.experimental and tensorflow.keras.wrappers.scikit_learn.
How do I fix No module named ‘tensorflow.keras.layers.experimental’?
The preprocessing layers moved to the main layers module: use from keras import layers and layers.Rescaling, layers.Normalization or layers.RandomFlip.
How do I fix No module named ‘keras.layers.convolutional’?
Import the layer directly from keras.layers: from keras.layers import Conv2D. The same applies to keras.layers.merge and keras.layers.core.
Why do I get ‘tensorflow’ is not a package?
A file named tensorflow.py in your project is imported instead of the real TensorFlow. Rename it and delete __pycache__.
How can I use Keras 2 with TensorFlow 2.16 or later?
Install tf_keras and set the environment variable TF_USE_LEGACY_KERAS=1 before importing TensorFlow.
Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and TSinfo Technologies. He started out building .NET and SharePoint solutions at HP, TCS and KPIT before moving into Python, machine learning and AI, and he also builds web apps with TypeScript and React. He writes the tutorials here himself, and every example is run before publishing so you see the real output. More about Bijay · Microsoft MVP profile · LinkedIn