Import Keras from TensorFlow in Python

While working on a deep learning project for a U.S.-based retail analytics company, I needed to quickly build and test a neural network model using Keras in Python. Even though I’ve been using Keras for over four years, I realized that many beginners still struggle with one basic step: how to import Keras from TensorFlow properly.

The good news is that importing Keras from TensorFlow is quite simple once you understand how TensorFlow integrates the Keras API.

In this tutorial, I’ll walk you through multiple ways to import Keras in Python, share complete working code, and explain each step in a clear and beginner-friendly way.

What is Keras in TensorFlow?

Before we start coding, let me briefly explain what Keras is.

Keras is a high-level deep learning API written in Python that runs on top of TensorFlow. It provides a clean and intuitive interface for building, training, and deploying neural networks.

TensorFlow integrated Keras natively from version 2.0 onward, which means you no longer need to install Keras separately. You can simply import it directly from TensorFlow, and that’s what we’ll do in this tutorial.

Why Import Keras from TensorFlow Instead of Installing It Separately?

In the early days of deep learning, Keras was a standalone library that could run on multiple backends like TensorFlow, Theano, or CNTK. But as TensorFlow matured, Google decided to integrate Keras directly into it.

Now, importing Keras from TensorFlow ensures:

  • Better compatibility with TensorFlow features.
  • Simpler installation (no need to manage multiple packages).
  • Improved performance through TensorFlow’s optimized backend.

In short, it’s the recommended and most stable way to use Keras in modern Python projects.

Method 1 – Import Keras from TensorFlow (Recommended Way)

This is the most common and recommended method to import Keras in Python. You can access all Keras modules directly from the tensorflow.keras package.

Here’s the basic syntax:

from tensorflow import keras

This single line gives you access to everything in Keras, including models, layers, optimizers, and callbacks.

Now, let’s see a full working example to make things clear.

Example 1: Build a Simple Neural Network in Python with TensorFlow Keras

Let’s say I want to build a simple neural network to predict housing prices in the U.S. using TensorFlow and Keras.

Below is the complete Python code:

# Importing TensorFlow and Keras
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

# Sample dataset (using random data for demonstration)
import numpy as np

# Let's assume we have 100 samples with 5 features each
X = np.random.rand(100, 5)
y = np.random.rand(100, 1)

# Building a simple Sequential model
model = keras.Sequential([
    layers.Dense(64, activation='relu', input_shape=(5,)),
    layers.Dense(32, activation='relu'),
    layers.Dense(1)
])

# Compiling the model
model.compile(optimizer='adam', loss='mean_squared_error')

# Training the model
model.fit(X, y, epochs=10, batch_size=8, verbose=1)

# Evaluating the model
loss = model.evaluate(X, y)
print(f"Model Loss: {loss:.4f}")

# Making predictions
predictions = model.predict(X[:5])
print("Sample Predictions:\n", predictions)

You can see the output in the screenshot below.

Import Keras from TensorFlow Python

This example shows how seamlessly you can import and use Keras from TensorFlow in Python.

The code creates a simple neural network with two hidden layers and trains it on randomly generated data. You can replace the dataset with your own U.S.-based data (like housing, sales, or weather data).

Method 2 – Import Specific Keras Modules from TensorFlow

Sometimes, you might not need the entire Keras library. You can import only specific modules, like layers or models, to keep your code clean and readable.

Here’s how you can do that:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

This approach is helpful when you’re building multiple models or working in large Python projects where importing unnecessary modules can increase memory usage.

Example 2: Import Specific Keras Components in Python

In this example, I’ll show how to build a similar model by importing only the required components.

# Importing only what we need
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import numpy as np

# Random input and output data
X = np.random.rand(200, 10)
y = np.random.rand(200, 1)

# Defining the model
model = Sequential([
    Dense(128, activation='relu', input_shape=(10,)),
    Dense(64, activation='relu'),
    Dense(1)
])

# Compiling the model
model.compile(optimizer='adam', loss='mse')

# Training the model
model.fit(X, y, epochs=5, batch_size=16)

# Evaluating
loss = model.evaluate(X, y)
print(f"Loss: {loss:.3f}")

You can see the output in the screenshot below.

Import Keras from Python TensorFlow

This method is clean and efficient, especially when you’re working with multiple Python files or modules in a production environment.

Method 3 – Import Keras from TensorFlow Using Aliases

If you prefer shorter syntax, you can use an alias while importing Keras.

For example:

import tensorflow.keras as keras

This allows you to access Keras modules using the shorter alias keras.

Let’s see a quick working example.

Example 3: Use Aliases for Cleaner Python Code

Here’s how you can use an alias when importing Keras from TensorFlow.

# Importing keras with an alias
import tensorflow.keras as keras
from tensorflow.keras import layers
import numpy as np

# Generating dummy data
X = np.random.rand(150, 4)
y = np.random.rand(150, 1)

# Defining the model
model = keras.Sequential([
    layers.Dense(32, activation='relu', input_shape=(4,)),
    layers.Dense(16, activation='relu'),
    layers.Dense(1)
])

# Compiling and training
model.compile(optimizer='adam', loss='mae')
model.fit(X, y, epochs=8, batch_size=10)

# Evaluating
print("Model evaluation:", model.evaluate(X, y))

You can see the output in the screenshot below.

Import Keras from TensorFlow

Using aliases like this can make your Python code more concise and easier to read, especially when you’re working in Jupyter notebooks or collaborative projects.

Method 4 – Check TensorFlow and Keras Versions in Python

Before importing Keras, it’s a good practice to check your TensorFlow version. Keras is fully integrated starting from TensorFlow 2.0, so if you’re using an older version, you may face import errors.

Here’s a quick way to check:

import tensorflow as tf
print("TensorFlow version:", tf.__version__)
print("Keras version:", tf.keras.__version__)

If your TensorFlow version is below 2.0, you can upgrade it using:

pip install --upgrade tensorflow

Keeping your TensorFlow and Keras versions updated ensures compatibility and access to the latest features.

Common Errors When Importing Keras from TensorFlow

Even though importing Keras is straightforward, you might still encounter a few common issues.

Here are some of the most frequent ones and how to fix them:

  1. Error: ModuleNotFoundError: No module named ‘tensorflow’
  • Fix: Install TensorFlow using pip install tensorflow.
  1. Error: AttributeError: module ‘tensorflow’ has no attribute ‘keras’
  • Fix: Upgrade TensorFlow to version 2.0 or higher.
  1. Error: ImportError: cannot import name ‘keras’ from ‘tensorflow’
  1. Error: DLL load failed (on Windows)
  • Fix: Update your Python and TensorFlow versions, and ensure your system has the latest Visual C++ redistributables.

These small checks can save hours of debugging, especially when setting up a new deep learning environment.

Bonus Tip – Using Keras with GPU in Python

If you have a GPU-enabled machine, you can use TensorFlow’s GPU version to speed up your Keras models.

To install TensorFlow with GPU support, run:

pip install tensorflow-gpu

Then, verify that TensorFlow detects your GPU:

import tensorflow as tf
print("GPUs Available:", len(tf.config.list_physical_devices('GPU')))

If the output shows one or more GPUs, your Keras models will automatically use them for training, no extra configuration needed!

When Should You Import Keras Separately?

Although importing Keras from TensorFlow is the preferred method, there are rare cases where you might still want to install standalone Keras.

For example, if you’re maintaining an older project built on Keras 1.x or 2.x (before TensorFlow integration), you can install it using:

pip install keras

Then, import it as:

import keras

However, for all modern Python projects, especially those using TensorFlow 2.x and above, always import Keras from TensorFlow.

So that’s how you can import Keras from TensorFlow in Python, the right way.

We covered multiple methods, from importing the entire Keras module to specific components and even using aliases for cleaner code. We also looked at common errors, version checks, and GPU support.

In my experience, once you get comfortable with importing and setting up Keras, you’ll find building deep learning models in Python much more intuitive and enjoyable.

You may also like to read:

Leave a Comment

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.