How can Keras be used to save and serialize the model using Python?

Keras is a high-level deep learning API that runs on top of TensorFlow. One of the key features of Keras is its ability to save and serialize trained models, allowing you to store your work and reuse models later without retraining.

The tensorflow package can be installed on Windows using the below line of code ?

pip install tensorflow

Keras is already present within the TensorFlow package. It can be accessed using the below code ?

import tensorflow as tf
from tensorflow import keras

Creating a Sample Model

Let's first create a simple model that we can save and serialize ?

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

# Create a simple sequential model
model = keras.Sequential([
    layers.Dense(64, activation='relu', input_shape=(32,)),
    layers.Dense(32, activation='relu'),
    layers.Dense(10, activation='softmax')
])

# Compile the model
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

print("Model created successfully")
print(f"Model has {model.count_params()} parameters")
Model created successfully
Model has 3466 parameters

Saving the Complete Model

The most straightforward way to save a Keras model is using the save() method, which saves the entire model ?

# Save the complete model
print("Saving the model to a file...")
model.save("my_keras_model")

print("Model saved successfully")
Saving the model to a file...
Model saved successfully

Loading the Saved Model

You can recreate the exact same model from the saved file using keras.models.load_model() ?

# Delete the original model
print("Deleting the original model...")
del model

# Load the model from file
print("Loading the model from file...")
loaded_model = keras.models.load_model("my_keras_model")

print("Model loaded successfully")
print(f"Loaded model has {loaded_model.count_params()} parameters")
Deleting the original model...
Loading the model from file...
Model loaded successfully
Loaded model has 3466 parameters

Alternative Serialization Methods

Saving Only Model Weights

You can save only the model weights using the save_weights() method ?

# Save only the weights
loaded_model.save_weights("model_weights.h5")
print("Model weights saved to model_weights.h5")

# Load weights into a new model with same architecture
new_model = keras.Sequential([
    layers.Dense(64, activation='relu', input_shape=(32,)),
    layers.Dense(32, activation='relu'),
    layers.Dense(10, activation='softmax')
])

new_model.load_weights("model_weights.h5")
print("Weights loaded into new model")
Model weights saved to model_weights.h5
Weights loaded into new model

Saving Model Architecture as JSON

You can save just the model architecture as JSON ?

# Save model architecture as JSON
model_json = loaded_model.to_json()
with open("model_architecture.json", "w") as json_file:
    json_file.write(model_json)

print("Model architecture saved as JSON")

# Load model from JSON
with open("model_architecture.json", "r") as json_file:
    loaded_json = json_file.read()

model_from_json = keras.models.model_from_json(loaded_json)
print("Model architecture loaded from JSON")
Model architecture saved as JSON
Model architecture loaded from JSON

Comparison of Methods

Method Saves Architecture Saves Weights Saves Training Config
model.save() Yes Yes Yes
save_weights() No Yes No
to_json() Yes No No

Key Points

  • Use model.save() for complete model serialization including architecture, weights, and training configuration

  • Use save_weights() when you only need to save the trained parameters

  • Use to_json() when you only need to save the model architecture

  • Saved models can be loaded in different sessions or shared with others

Conclusion

Keras provides multiple methods for saving and serializing models. The model.save() method is the most comprehensive approach, saving everything needed to recreate the model. Use save_weights() for parameter-only storage or to_json() for architecture-only serialization based on your specific needs.

Updated on: 2026-03-25T14:47:26+05:30

274 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements