How can Keras be used to save model using hdf5 format in Python?

Keras provides an easy way to save and load machine learning models using the HDF5 format. HDF5 (Hierarchical Data Format version 5) is a binary format that efficiently stores the complete model including architecture, weights, and training configuration.

What is HDF5 Format?

HDF5 is a data model and file format designed to store and organize large amounts of data. When saving Keras models in HDF5 format, it preserves:

  • Model architecture − The structure and layers
  • Model weights − Trained parameters
  • Training configuration − Loss function, optimizer settings
  • Optimizer state − Current state for resuming training

Complete Example: Training and Saving a Model

Let's create a simple neural network, train it, and save it in HDF5 format −

import tensorflow as tf
from tensorflow import keras
import numpy as np

# Create sample data
x_train = np.random.random((1000, 20))
y_train = np.random.randint(2, size=(1000, 1))

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

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

# Train the model briefly
model.fit(x_train, y_train, epochs=5, verbose=1)

print("The model is saved to HDF5 format")
model.save('my_model.h5')
Epoch 1/5
32/32 [==============================] - 1s 2ms/step - loss: 0.7125 - accuracy: 0.4990
Epoch 2/5
32/32 [==============================] - 0s 2ms/step - loss: 0.6889 - accuracy: 0.5380
Epoch 3/5
32/32 [==============================] - 0s 2ms/step - loss: 0.6764 - accuracy: 0.5680
Epoch 4/5
32/32 [==============================] - 0s 2ms/step - loss: 0.6661 - accuracy: 0.5950
Epoch 5/5
32/32 [==============================] - 0s 2ms/step - loss: 0.6571 - accuracy: 0.6160
The model is saved to HDF5 format

Loading the Saved Model

Now let's load the saved model and verify it works correctly −

print("The same model is recreated with same weights and optimizer")
new_model = tf.keras.models.load_model('my_model.h5')

print("The architecture of the model is observed")
new_model.summary()

# Test that the loaded model works
test_input = np.random.random((1, 20))
prediction = new_model.predict(test_input, verbose=0)
print(f"Sample prediction: {prediction[0][0]:.4f}")
The same model is recreated with same weights and optimizer
The architecture of the model is observed
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 dense (Dense)               (None, 64)                1344      
                                                                 
 dense_1 (Dense)             (None, 32)                2080      
                                                                 
 dense_2 (Dense)             (None, 1)                 33        
                                                                 
=================================================================
Total params: 3,457
Trainable params: 3,457
Non-trainable params: 0
_________________________________________________________________
Sample prediction: 0.3847

Alternative: Saving Only Weights

If you only need to save the model weights without the architecture −

# Save only weights in HDF5 format
model.save_weights('model_weights.h5')

# Load weights back (requires same architecture)
model.load_weights('model_weights.h5')
print("Weights loaded successfully")
Weights loaded successfully

Key Points

  • Use model.save('filename.h5') to save the complete model
  • Use tf.keras.models.load_model('filename.h5') to load the model
  • The .h5 extension automatically uses HDF5 format
  • Saved models preserve architecture, weights, and training configuration
  • Use save_weights() and load_weights() for weights only

Conclusion

Keras makes it simple to save models in HDF5 format using model.save() with a .h5 extension. This preserves the complete model state, making it easy to resume training or deploy models later. The loaded model maintains all original properties including architecture, weights, and optimizer configuration.

Updated on: 2026-03-25T15:43:13+05:30

469 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements