Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Saving and Loading Models in Keras

Introduction

In machine learning, saving and loading models is essential for reusing trained models without retraining them. Keras provides built-in functionalities to save and load models efficiently. This tutorial will guide you through the process of saving and loading models in Keras, covering different formats and methods.

Saving a Model

Keras allows you to save your models in two formats: the TensorFlow SavedModel format and the HDF5 format. The most common method for saving a model is using the model.save() function.

Saving in HDF5 Format

HDF5 is a popular format for storing large amounts of data. To save a model in HDF5 format, you can specify the filename with a .h5 extension.

Example Code:

from keras.models import Sequential
from keras.layers import Dense

# Define a simple model
model = Sequential()
model.add(Dense(64, activation='relu', input_shape=(32,)))
model.add(Dense(10, activation='softmax'))

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

# Save the model
model.save('my_model.h5')
                

Saving in TensorFlow SavedModel Format

To save a model in TensorFlow's SavedModel format, simply call the model.save() function without specifying a file extension.

Example Code:

# Save the model in TensorFlow SavedModel format
model.save('my_model')
                

Loading a Model

Loading a model is just as easy as saving one. You can use the keras.models.load_model() function to load a model from either HDF5 or TensorFlow SavedModel formats.

Loading from HDF5 Format

Example Code:

from keras.models import load_model

# Load the model from HDF5 file
loaded_model = load_model('my_model.h5')
                

Loading from TensorFlow SavedModel Format

Example Code:

# Load the model from TensorFlow SavedModel directory
loaded_model = load_model('my_model')
                

Conclusion

In this tutorial, we covered how to save and load models in Keras using both HDF5 and TensorFlow SavedModel formats. By saving models, you can easily share your trained models or resume training later without starting from scratch. Make sure to choose the format that best fits your needs when saving your models.