0
0
TensorFlowml~5 mins

HDF5 format in TensorFlow

Choose your learning style9 modes available
Introduction

HDF5 format helps save and load machine learning models easily. It keeps all model parts in one file.

You want to save a trained model to use later without retraining.
You need to share your model with others in a simple file.
You want to pause training and continue later from the saved model.
You want to load a pre-trained model to make predictions quickly.
You want to keep model architecture and weights together in one file.
Syntax
TensorFlow
model.save('model_name.h5')

model = keras.models.load_model('model_name.h5')

The .h5 extension tells TensorFlow to use HDF5 format.

This format saves model architecture, weights, and optimizer state.

Examples
Saves the entire model to a file named my_model.h5.
TensorFlow
model.save('my_model.h5')
Loads the saved model from my_model.h5 for use.
TensorFlow
loaded_model = keras.models.load_model('my_model.h5')
Save and load model in different program runs.
TensorFlow
model.save('model_v1.h5')
# Later
model = keras.models.load_model('model_v1.h5')
Sample Model

This code trains a simple model, saves it in HDF5 format, loads it back, and checks accuracy.

TensorFlow
import tensorflow as tf
from tensorflow import keras

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

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

# Dummy data
import numpy as np
x_train = np.random.random((100, 5))
y_train = np.random.randint(2, size=(100, 1))

# Train model
model.fit(x_train, y_train, epochs=2, verbose=0)

# Save model in HDF5 format
model.save('example_model.h5')

# Load model back
loaded_model = keras.models.load_model('example_model.h5')

# Check loaded model accuracy on training data
loss, accuracy = loaded_model.evaluate(x_train, y_train, verbose=0)
print(f'Loaded model accuracy: {accuracy:.2f}')
OutputSuccess
Important Notes

HDF5 files can be large if the model is big.

Use .h5 extension to ensure compatibility.

HDF5 format is widely supported and easy to share.

Summary

HDF5 format saves the whole model in one file.

It is useful for saving, sharing, and loading models easily.

Use model.save('file.h5') and keras.models.load_model('file.h5').