Path: blob/master/guides/ipynb/serialization_and_saving.ipynb
3283 views
Save, serialize, and export models
Authors: Neel Kovelamudi, Francois Chollet
Date created: 2023/06/14
Last modified: 2023/06/30
Description: Complete guide to saving, serializing, and exporting models.
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:
Loading the model back:
Now, let's look at the details.
Setup
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 only supported format in Keras 3 is the "Keras v3" format, which uses the .keras
extension.
Example:
Custom objects
This section covers the basic workflows for handling custom layers, functions, and models in Keras saving and reloading.
When saving a model that includes custom objects, such as a subclassed Layer, you must define a get_config()
method on the object class. If the arguments passed to the constructor (__init__()
method) of the custom object aren't Python objects (anything other than base types like ints, strings, etc.), then you must also explicitly deserialize these arguments in the from_config()
class method.
Like this:
Please see the Defining the config methods section for more details and examples.
The saved .keras
file is lightweight and does not store the Python code for custom objects. Therefore, to reload the model, load_model
requires access to the definition of any custom objects used through one of the following methods:
Registering custom objects (preferred),
Passing custom objects directly when loading, or
Using a custom object scope
Below are examples of each workflow:
Registering custom objects (preferred)
This is the preferred method, as custom object registration greatly simplifies saving and loading code. Adding the @keras.saving.register_keras_serializable
decorator to the class definition of a custom object registers the object globally in a master list, allowing Keras to recognize the object when loading the model.
Let's create a custom model involving both a custom layer and a custom activation function to demonstrate this.
Example:
Passing custom objects to load_model()
Using a custom object scope
Any code within the custom object scope will be able to recognize the custom objects passed to the scope argument. Therefore, loading the model within the scope will allow the loading of our custom objects.
Example:
Model serialization
This section is about saving only the model's configuration, without its state. The model's configuration (or architecture) specifies what layers the model contains, and how these layers are connected. If you have the configuration of a model, then the model can be created with a freshly initialized state (no weights or compilation information).
APIs
The following serialization APIs are available:
keras.models.clone_model(model)
: make a (randomly initialized) copy of a model.get_config()
andcls.from_config()
: retrieve the configuration of a layer or model, and recreate a model instance from its config, respectively.keras.models.model_to_json()
andkeras.models.model_from_json()
: similar, but as JSON strings.keras.saving.serialize_keras_object()
: retrieve the configuration any arbitrary Keras object.keras.saving.deserialize_keras_object()
: recreate an object instance from its configuration.
In-memory model cloning
You can do in-memory cloning of a model via keras.models.clone_model()
. This is equivalent to getting the config then recreating the model from its config (so it does not preserve compilation information or layer weights values).
Example:
get_config()
and from_config()
Calling model.get_config()
or layer.get_config()
will return a Python dict containing the configuration of the model or layer, respectively. You should define get_config()
to contain arguments needed for the __init__()
method of the model or layer. At loading time, the from_config(config)
method will then call __init__()
with these arguments to reconstruct the model or layer.
Layer example:
Now let's reconstruct the layer using the from_config()
method:
Sequential model example:
Functional model example:
to_json()
and keras.models.model_from_json()
This is similar to get_config
/ from_config
, except it turns the model into a JSON string, which can then be loaded without the original model class. It is also specific to models, it isn't meant for layers.
Example:
Arbitrary object serialization and deserialization
The keras.saving.serialize_keras_object()
and keras.saving.deserialize_keras_object()
APIs are general-purpose APIs that can be used to serialize or deserialize any Keras object and any custom object. It is at the foundation of saving model architecture and is behind all serialize()
/deserialize()
calls in keras.
Example:
Note the serialization format containing all the necessary information for proper reconstruction:
module
containing the name of the Keras module or other identifying module the object comes fromclass_name
containing the name of the object's class.config
with all the information needed to reconstruct the objectregistered_name
for custom objects. See here.
Now we can reconstruct the regularizer.
Model weights saving
You can choose to only save & load a model's weights. This can be useful if:
You only need the model for inference: in this case you won't need to restart training, so you don't need the compilation information or optimizer state.
You are doing transfer learning: in this case you will be training a new model reusing the state of a prior model, so you don't need the compilation information of the prior model.
APIs for in-memory weight transfer
Weights can be copied between different objects by using get_weights()
and set_weights()
:
keras.layers.Layer.get_weights()
: Returns a list of NumPy arrays of weight values.keras.layers.Layer.set_weights(weights)
: Sets the model weights to the values provided (as NumPy arrays).
Examples:
Transfering weights from one layer to another, in memory
Transfering weights from one model to another model with a compatible architecture, in memory
The case of stateless layers
Because stateless layers do not change the order or number of weights, models can have compatible architectures even if there are extra/missing stateless layers.
APIs for saving weights to disk & loading them back
Weights can be saved to disk by calling model.save_weights(filepath)
. The filename should end in .weights.h5
.
Example:
Note that changing layer.trainable
may result in a different layer.weights
ordering when the model contains nested layers.
Transfer learning example
When loading pretrained weights from a weights file, it is recommended to load the weights into the original checkpointed model, and then extract the desired weights/layers into a new model.
Example:
Appendix: Handling custom objects
Defining the config methods
Specifications:
get_config()
should return a JSON-serializable dictionary in order to be compatible with the Keras architecture- and model-saving APIs.from_config(config)
(aclassmethod
) should return a new layer or model object that is created from the config. The default implementation returnscls(**config)
.
NOTE: If all your constructor arguments are already serializable, e.g. strings and ints, or non-custom Keras objects, overriding from_config
is not necessary. However, for more complex objects such as layers or models passed to __init__
, deserialization must be handled explicitly either in __init__
itself or overriding the from_config()
method.
Example:
Note that overriding from_config
is unnecessary above for MyDense
because hidden_units
, kernel_initializer
, and kernel_regularizer
are ints, strings, and a built-in Keras object, respectively. This means that the default from_config
implementation of cls(**config)
will work as intended.
For more complex objects, such as layers and models passed to __init__
, for example, you must explicitly deserialize these objects. Let's take a look at an example of a model where a from_config
override is necessary.
How custom objects are serialized
The serialization format has a special key for custom objects registered via @keras.saving.register_keras_serializable
. This registered_name
key allows for easy retrieval at loading/deserialization time while also allowing users to add custom naming.
Let's take a look at the config from serializing the custom layer MyDense
we defined above.
Example:
As shown, the registered_name
key contains the lookup information for the Keras master list, including the package MyLayers
and the custom name KernelMult
that we gave in the @keras.saving.register_keras_serializable
decorator. Take a look again at the custom class definition/registration here.
Note that the class_name
key contains the original name of the class, allowing for proper re-initialization in from_config
.
Additionally, note that the module
key is None
since this is a custom object.