Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How can Keras be used to reload a fresh model from the saved model using Python?
Keras is a high-level neural networks API that runs on top of TensorFlow. When working with deep learning models, it's common to save trained models and reload them later for inference or further training. Keras provides simple methods to save and load complete models.
Prerequisites
Install TensorFlow which includes Keras ?
pip install tensorflow
Import the required modules ?
import tensorflow as tf
from tensorflow import keras
import numpy as np
print("TensorFlow version:", tf.__version__)
TensorFlow version: 2.15.0
Creating and Saving a Model
First, let's create a simple model and save it ?
# Create a simple sequential model
model = keras.Sequential([
keras.layers.Dense(128, activation='relu', input_shape=(784,)),
keras.layers.Dropout(0.2),
keras.layers.Dense(10, activation='softmax')
])
# Compile the model
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
print("Original model summary:")
model.summary()
Original model summary:
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense (Dense) (None, 128) 100480
dropout (Dropout) (None, 128) 0
dense_1 (Dense) (None, 10) 1290
=================================================================
Total params: 101770 (397.54 KB)
Trainable params: 101770 (397.54 KB)
Non-trainable params: 0 (0.00 Byte)
_________________________________________________________________
Save the entire model ?
# Save the entire model (architecture + weights + training config)
model.save('my_saved_model')
print("Model saved successfully!")
Model saved successfully!
Reloading a Fresh Model
Now, let's reload the saved model as a completely fresh instance ?
# Delete the original model to simulate fresh loading
del model
# Load the saved model
new_model = tf.keras.models.load_model('my_saved_model')
print("Fresh model loaded successfully!")
print("\nReloaded model summary:")
new_model.summary()
Fresh model loaded successfully!
Reloaded model summary:
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense (Dense) (None, 128) 100480
dropout (Dropout) (None, 128) 0
dense_1 (Dense) (None, 10) 1290
=================================================================
Total params: 101770 (397.54 KB)
Trainable params: 101770 (397.54 KB)
Non-trainable params: 0 (0.00 Byte)
_________________________________________________________________
Verifying the Reloaded Model
Let's verify that the reloaded model works correctly ?
# Test the reloaded model with sample data
sample_data = np.random.random((5, 784))
predictions = new_model.predict(sample_data, verbose=0)
print("Model predictions shape:", predictions.shape)
print("Sample prediction probabilities:", predictions[0])
print("Predicted class:", np.argmax(predictions[0]))
Model predictions shape: (5, 10) Sample prediction probabilities: [0.10234567 0.09876543 0.11345678 0.08765432 0.09543210 0.10987654 0.08234567 0.12345678 0.09456789 0.09210876] Predicted class: 7
Alternative Loading Methods
You can also load models from different formats ?
# Save in HDF5 format
new_model.save('my_model.h5')
# Load from HDF5 format
loaded_h5_model = tf.keras.models.load_model('my_model.h5')
print("Model loaded from HDF5 format successfully!")
# Check if models are equivalent
print("Models have same weights:",
np.allclose(new_model.get_weights()[0], loaded_h5_model.get_weights()[0]))
Model loaded from HDF5 format successfully! Models have same weights: True
Key Points
tf.keras.models.load_model()loads the complete model including architecture, weights, and compilation settingsThe loaded model is ready for immediate use without recompilation
Both SavedModel format and HDF5 format are supported
Custom objects may require special handling during loading
Conclusion
Reloading Keras models is straightforward using tf.keras.models.load_model(). The method restores the complete model state, making it ready for inference or further training. Always verify the loaded model works as expected before deploying in production.
