I was working on a deep learning project where I needed to build a neural network model in Python using TensorFlow Keras. But when I tried to import the library, I ran into the dreaded error, “ModuleNotFoundError: No module named ‘tensorflow.keras’.”
If you’ve ever faced this issue, don’t worry. I’ve been developing in Python for many years, and I’ve seen this problem countless times. The good news is that importing TensorFlow Keras in Python is simple once you understand how TensorFlow organizes its modules.
In this tutorial, I’ll show you how to import TensorFlow Keras in Python step by step. I’ll also include code examples, installation methods, and a few pro tips I’ve learned through real-world projects here in the U.S.
What is TensorFlow Keras?
Before we get into the code, let’s quickly understand what TensorFlow Keras is.
Keras is a high-level API built on top of TensorFlow that makes it easier to build and train deep learning models in Python. It allows you to focus on your model architecture rather than worrying about low-level mathematical operations.
In short, Keras = User-Friendly Deep Learning in Python.
Use TensorFlow Keras Instead of Standalone Keras
In the early days, Keras was a standalone library that could run on multiple backends (like TensorFlow, Theano, or CNTK).
However, since TensorFlow 2.0, Keras has been fully integrated into TensorFlow. This means you no longer need to install Keras separately; it’s part of TensorFlow by default.
So instead of writing:
import kerasYou should now use:
from tensorflow import kerasThis ensures compatibility with TensorFlow’s ecosystem, making your Python code more stable and future-proof.
Method 1 – Install TensorFlow and Import Keras in Python
Let’s start with the most common method, installing TensorFlow and importing Keras from it.
Step 1: Install TensorFlow
First, open your terminal or command prompt and run:
pip install tensorflowThis command installs TensorFlow, which includes the Keras API.
If you want GPU support (for faster training), you can install the GPU version:
pip install tensorflow[and-cuda]Once it’s installed, you can verify the installation by checking the version.
Step 2: Verify TensorFlow Installation
Now open your Python environment (like Jupyter Notebook, VS Code, or PyCharm) and run:
import tensorflow as tf
print(tf.__version__)You can refer to the screenshot below to see the output.

If you see a version number printed (like 2.16.1), TensorFlow is successfully installed.
Step 3: Import Keras from TensorFlow
Now, let’s import Keras from TensorFlow:
from tensorflow import kerasThat’s it! You’ve successfully imported TensorFlow Keras in Python. Let’s go one step further and build a simple neural network to confirm everything works perfectly.
Example: Build a Simple Neural Network with TensorFlow Keras
Here’s a complete example that shows how to use TensorFlow Keras to create and train a simple neural network model.
This example uses a dataset that’s familiar in the U.S., predicting housing prices based on features like square footage, number of bedrooms, and location.
# Import TensorFlow and Keras
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
# Generate synthetic housing data (square feet, bedrooms, price)
np.random.seed(42)
square_feet = np.random.randint(800, 4000, 1000)
bedrooms = np.random.randint(1, 5, 1000)
price = square_feet * 200 + bedrooms * 15000 + np.random.randint(-20000, 20000, 1000)
# Combine features
X = np.column_stack((square_feet, bedrooms))
y = price
# Normalize data
X = X / np.max(X, axis=0)
# Split data
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Build a Sequential model
model = keras.Sequential([
layers.Dense(16, activation='relu', input_shape=(2,)),
layers.Dense(8, activation='relu'),
layers.Dense(1)
])
# Compile the model
model.compile(optimizer='adam', loss='mse', metrics=['mae'])
# Train the model
model.fit(X_train, y_train, epochs=50, batch_size=32, verbose=1)
# Evaluate the model
loss, mae = model.evaluate(X_test, y_test)
print("Mean Absolute Error on Test Data:", mae)You can refer to the screenshot below to see the output.

This example demonstrates a real-world scenario, predicting housing prices. You can easily adapt it to your own dataset.
I often use a similar structure when building quick prototypes for clients in the U.S. real estate market.
Method 2 – Handle the “No Module Named ‘tensorflow.keras’” Error
Sometimes, even after installing TensorFlow, you might get this error when importing Keras in Python:
ModuleNotFoundError: No module named 'tensorflow.keras'This usually happens for one of three reasons:
- TensorFlow isn’t installed in your current Python environment.
- You’re using an outdated version of TensorFlow.
- You have multiple Python environments (e.g., Anaconda, venv) and the wrong one is active.
Here’s how to fix it step by step.
Step 1: Check Your Python Environment
Run this command in your terminal:
where python(on Windows) or
which python(on macOS/Linux).
This tells you which Python environment is currently active. Make sure it’s the same one where TensorFlow is installed.
Step 2: Reinstall TensorFlow
If TensorFlow isn’t detected, reinstall it using:
pip install --upgrade tensorflowThen try importing again:
from tensorflow import kerasIf this works, you’re good to go!
Method 3 – Import Specific Keras Modules in Python
In many projects, I prefer importing specific Keras submodules instead of importing everything at once.
This makes the code cleaner and avoids unnecessary memory usage.
Here are some common imports I use:
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.optimizers import AdamThis way, you can directly access the classes you need without typing long module paths later.
For example, you can build a classification model like this:
model = Sequential([
Dense(64, activation='relu', input_shape=(10,)),
Dropout(0.3),
Dense(32, activation='relu'),
Dense(1, activation='sigmoid')
])
model.compile(optimizer=Adam(learning_rate=0.001),
loss='binary_crossentropy',
metrics=['accuracy'])This modular approach is what I use in most of my production-level Python projects.
Method 4 – Use Virtual Environments for TensorFlow Keras in Python
When working on multiple machine learning projects, it’s best practice to use virtual environments in Python. Each project can have its own dependencies, preventing version conflicts.
Here’s how you can create and activate a virtual environment:
python -m venv keras_envThen activate it:
- Windows:
keras_env\Scripts\activate- macOS/Linux:
source keras_env/bin/activateNow install TensorFlow inside this environment:
pip install tensorflowOnce done, you can safely import Keras:
from tensorflow import kerasThis method ensures your Python environment remains clean and isolated.
Method 5 – Verify TensorFlow Keras Installation in Python
If you want to double-check that TensorFlow Keras is working correctly, run the following script:
import tensorflow as tf
print("TensorFlow version:", tf.__version__)
print("Keras version:", tf.keras.__version__)
# Test a simple model
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
print("Keras model created successfully!")If this script runs without errors, your TensorFlow Keras setup in Python is perfect.
Pro Tips for Working with TensorFlow Keras in Python
Based on my experience, here are a few quick tips:
- Always use the latest stable version of TensorFlow for better performance.
- Use GPU acceleration for training large models.
- Save your models using model.save(‘model.keras’) to reuse them easily.
- Keep your Python environment lightweight — avoid mixing TensorFlow versions.
- Regularly update your dependencies using pip list –outdated.
These practices have saved me countless hours in real-world projects.
Conclusion
So that’s how you can import TensorFlow Keras in Python, from installation to fixing common errors and building models.
We started by understanding what TensorFlow Keras is, then learned multiple ways to import it, and finally looked at practical examples and troubleshooting steps.
Whether you’re building a deep learning model for predicting housing prices or analyzing customer churn, this setup will give you a solid foundation.
You may also like to read:
- How to Save a Keras Model in Python
- Import Keras from TensorFlow in Python
- Save a Keras Model with a Custom Layer in Python
- How to Load a Keras Model in Python

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.