Save, serialize, and export models

Authors: Neel Kovelamudi, Francois Chollet

View on TensorFlow.org Run in Google Colab View source on GitHub View on keras.io

Introduction

A Keras model consists of multiple components:

  • The architecture, or configuration, which specifies what layers the model contain, and how they're connected.
  • A set of weights values (the "state of the model").
  • An optimizer (defined by compiling the model).
  • A set of losses and metrics (defined by compiling the model).

The Keras API saves all of these pieces together in a unified format, marked by the .keras extension. This is a zip archive consisting of the following:

  • A JSON-based configuration file (config.json): Records of model, layer, and other trackables' configuration.
  • A H5-based state file, such as model.weights.h5 (for the whole model), with directory keys for layers and their weights.
  • A metadata file in JSON, storing things such as the current Keras version.

Let's take a look at how this works.

How to save and load a model

If you only have 10 seconds to read this guide, here's what you need to know.

Saving a Keras model:

model = ...  # Get model (Sequential, Functional Model, or Model subclass)
model.save('path/to/location.keras')  # The file needs to end with the .keras extension

Loading the model back:

model = keras.models.load_model('path/to/location.keras')

Now, let's look at the details.

Setup

import numpy as np
import tensorflow as tf
import keras

Saving

This section is about saving an entire model to a single file. The file will include:

  • The model's architecture/config
  • The model's weight values (which were learned during training)
  • The model's compilation information (if compile() was called)
  • The optimizer and its state, if any (this enables you to restart training where you left)

APIs

You can save a model with model.save() or keras.models.save_model() (which is equivalent). You can load it back with keras.models.load_model().

The recommended format is the "Keras v3" format, which uses the .keras extension. There are, however, two legacy formats that are available: the TensorFlow SavedModel format and the older Keras H5 format.

You can switch to the SavedModel format by:

  • Passing save_format='tf' to save()
  • Passing a filename without an extension

You can switch to the H5 format by:

  • Passing save_format='h5' to save()
  • Passing a filename that ends in .h5

Example:

def get_model():
    # Create a simple model.
    inputs = keras.Input(shape=(32,))
    outputs = keras.layers.Dense(1)(inputs)
    model = keras.Model(inputs, outputs)
    model.compile(optimizer=keras.optimizers.Adam(), loss="mean_squared_error")
    return model


model = get_model()

# Train the model.
test_input = np.random