How to Load a Keras Model in Python

When I first started working with deep learning in Python, one of the biggest challenges I faced was figuring out how to properly save and reload my Keras models.

After spending hours training a neural network, the last thing you want is to lose your progress or have to retrain your model from scratch.

Over the years, I’ve worked on several production-level Python projects using Keras and TensorFlow, from image classification to text sentiment analysis, and I’ve learned the best ways to load a Keras model in Python safely and efficiently.

In this article, I’ll walk you through everything you need to know about loading a Keras model in Python. We’ll cover multiple methods, including how to handle models with custom layers or loss functions.

What Does It Mean to Load a Keras Model in Python?

When we talk about loading a Keras model, we mean restoring a previously saved model so that we can use it again, either for inference (making predictions) or for further training.

Keras provides a simple and powerful function called load_model() that lets us bring back a model saved in the HDF5 (.h5) or TensorFlow SavedModel format.

This is extremely useful in real-world Python applications where training might take hours or even days. Instead of retraining, you can simply load the model and start predicting immediately.

Method 1 – Load a Keras Model Using load_model() in Python

This is the most common and easiest method to load a Keras model in Python. Let’s assume you have already trained and saved your model using the model.save(‘model.h5’) command.

Here’s how you can load it back:

# Import necessary libraries
from tensorflow.keras.models import load_model
import numpy as np

# Load the saved Keras model
model = load_model('model.h5')

# Print model summary
model.summary()

# Example: Make a prediction using dummy data
# Let's assume our model takes input of shape (1, 10)
sample_input = np.random.rand(1, 10)
prediction = model.predict(sample_input)

print("Prediction result:", prediction)

You can see the output in the screenshot below.

Load a Keras Model in Python

In the code above, I used the built-in load_model() function from Keras to restore the model.

Once loaded, the model behaves exactly like it did before saving. You can evaluate it, continue training, or make predictions.

Method 2 – Load a Keras Model Saved in TensorFlow SavedModel Format

Keras models can also be saved in the TensorFlow SavedModel format, which is the default format when you call model.save(‘my_model’) without specifying an extension.

Here’s how you can load such a model in Python:

from tensorflow.keras.models import load_model
import numpy as np

# Load the model from a directory (SavedModel format)
model = load_model('saved_model_directory')

# Check model structure
model.summary()

# Example: Make a prediction
sample_input = np.random.rand(1, 10)
result = model.predict(sample_input)

print("Predicted output:", result)

You can see the output in the screenshot below.

Load Keras Model in Python

This method is particularly useful for TensorFlow Serving or deployment on cloud services like Google Cloud AI Platform or AWS SageMaker.

In my experience, the SavedModel format is more robust when sharing models across environments or Python versions.

Method 3 – Load a Keras Model with Custom Layers or Functions in Python

Sometimes, your model may include custom layers, activation functions, or loss functions that are not part of the standard Keras library.

If you try to load such a model directly, Python will throw an error because it doesn’t recognize those custom components.

Here’s how I usually handle it:

from tensorflow.keras.models import load_model
from tensorflow.keras.layers import Layer
import tensorflow as tf
import numpy as np

# Define a custom layer (for example)
class MyCustomLayer(Layer):
    def __init__(self, units=32, **kwargs):
        super(MyCustomLayer, self).__init__(**kwargs)
        self.units = units

    def build(self, input_shape):
        self.w = self.add_weight(shape=(input_shape[-1], self.units),
                                 initializer='random_normal',
                                 trainable=True)
        self.b = self.add_weight(shape=(self.units,),
                                 initializer='zeros',
                                 trainable=True)

    def call(self, inputs):
        return tf.nn.relu(tf.matmul(inputs, self.w) + self.b)

# Load the model with custom layer
model = load_model('custom_model.h5', custom_objects={'MyCustomLayer': MyCustomLayer})

# Print model summary
model.summary()

# Example prediction
sample_input = np.random.rand(1, 16)
prediction = model.predict(sample_input)

print("Prediction with custom layer:", prediction)

You can see the output in the screenshot below.

Load a Python Keras Model

This approach ensures that Keras knows how to interpret your custom components when reloading the model.

It’s especially useful when working on advanced Python deep learning projects where you define your own layers or metrics.

Method 4 – Load Keras Model Weights Only in Python

Sometimes, you might only want to load the weights of a model, not the entire architecture. This is common when you’ve already defined the model structure in Python code and just want to restore its trained parameters.

Here’s how you can do it:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import numpy as np

# Recreate the same model architecture
model = Sequential([
    Dense(64, activation='relu', input_shape=(10,)),
    Dense(32, activation='relu'),
    Dense(1, activation='sigmoid')
])

# Load pre-trained weights
model.load_weights('model_weights.h5')

# Verify model functionality
sample_input = np.random.rand(1, 10)
prediction = model.predict(sample_input)

print("Prediction using loaded weights:", prediction)

This method is faster and often used in transfer learning workflows in Python, where you want to reuse weights from previously trained models.

Method 5 – Verify the Loaded Model in Python

After loading the model, it’s always a good idea to confirm that it works as expected. You can verify it by checking the model summary, evaluating it on test data, or comparing predictions with the original model.

Here’s a quick example:

# Evaluate the model on test data
test_data = np.random.rand(10, 10)
test_labels = np.random.randint(2, size=(10, 1))

loss, accuracy = model.evaluate(test_data, test_labels, verbose=0)

print(f"Model Evaluation -> Loss: {loss:.4f}, Accuracy: {accuracy:.4f}")

This simple test ensures that your model is loaded correctly and ready to perform inference or further training.

Common Errors When Loading a Keras Model in Python

Over the years, I’ve noticed a few common mistakes developers make when loading models in Python:

  • File path errors: Make sure your .h5 or SavedModel directory path is correct.
  • Version mismatch: Models saved with older TensorFlow/Keras versions may not load properly in newer versions.
  • Missing custom objects: Always include custom layers, metrics, or loss functions in the custom_objects parameter.
  • Corrupted model files: If your training was interrupted while saving, the file might be incomplete.

Whenever I encounter such issues, I first check the TensorFlow and Keras versions and ensure that the saving and loading environments match.

Real-World Example: Load a Customer Churn Prediction Model in Python

Let’s say you built a deep learning model to predict customer churn for a telecom company in the U.S.

You trained it, saved it as churn_model.h5, and now you want to load it in Python to make predictions for new customers.

Here’s how you can do that:

from tensorflow.keras.models import load_model
import numpy as np
import pandas as pd

# Load the trained model
model = load_model('churn_model.h5')

# Example: New customer data (dummy values)
new_customer = np.array([[35, 1, 0, 70, 2, 0, 1, 45.6, 0]])

# Predict churn probability
churn_probability = model.predict(new_customer)

print(f"Customer churn probability: {churn_probability[0][0]*100:.2f}%")

This is a typical use case in Python data science projects, loading a pre-trained Keras model and using it to make real-world predictions without retraining.

Conclusion

Loading a Keras model in Python is one of the most essential skills for any deep learning developer.

Whether you’re restoring an image classifier, a sentiment analysis model, or a customer churn predictor, the process is simple once you understand the available methods.

To summarize:

  • Use load_model() for .h5 or SavedModel formats.
  • Include custom_objects for custom layers or functions.
  • Use load_weights() if you only need the weights.

With these methods, you can confidently manage your trained models and deploy them efficiently in any Python environment.

You may also like to read the Keras-related tutorials:

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.