ModuleNotFoundError: No module named ‘tensorflow.keras’ [Fixed]

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 messageCauseFix
No module named ‘tensorflow’TensorFlow is not installed in this Pythonpython -m pip install tensorflow with the same python you run
No module named ‘tensorflow.keras’; ‘tensorflow’ is not a packageA file named tensorflow.py in your folderRename the file and delete __pycache__
No module named ‘tensorflow.keras.layers.experimental’Removed in Keras 3from keras import layers then layers.Rescaling, layers.Normalization…
No module named ‘keras.layers.convolutional’ / ‘merge’ / ‘core’Keras 2 internal modules, removed in Keras 3from keras.layers import Conv2D, concatenate, Dense
Import “tensorflow.keras” could not be resolvedVS Code / Pylance warning, not a Python errorUse 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
Command Prompt output of a Python script printing the Python version, the interpreter path and the installed TensorFlow, Keras and tf_keras versions
The interpreter path and the installed TensorFlow and Keras versions.

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'
Command Prompt traceback ModuleNotFoundError No module named 'tensorflow' when TensorFlow is not installed in the active virtual environment
Running in an environment without 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
Command Prompt traceback No module named 'tensorflow.keras'; 'tensorflow' is not a package caused by a local tensorflow.py file
The exact error caused by a local 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'
Command Prompt output showing ModuleNotFoundError for tensorflow.keras.layers.experimental, wrappers.scikit_learn, keras.layers.convolutional, merge, core, vis_utils and keras.engine in Keras 3
Old Keras 2 import paths failing on TensorFlow 2.21 / Keras 3.15.

Replace them with the public Keras 3 imports:

Old import (fails)Keras 3 replacement
from tensorflow.keras.layers.experimental import preprocessingfrom keras import layers, then layers.Rescaling, layers.Normalization, layers.RandomFlip…
from keras.layers.convolutional import Conv2Dfrom keras.layers import Conv2D
from keras.layers.merge import concatenatefrom keras.layers import concatenate (or Concatenate)
from keras.layers.core import Densefrom keras.layers import Dense
from keras.utils.vis_utils import plot_modelfrom keras.utils import plot_model
from keras.utils import np_utilsfrom keras.utils import to_categorical
from tensorflow.keras.wrappers.scikit_learn import KerasClassifierpip install scikeras, then from scikeras.wrappers import KerasClassifier
from keras.engine import ... / tensorflow.python.kerasInternal 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)
Command Prompt showing a Keras 3 Sequential model with Rescaling and Dense layers training and predicting after fixing the imports
The fixed imports running on Keras 3.

tensorflow.keras vs import keras