Path: blob/master/site/en-snapshot/guide/keras/save_and_serialize.ipynb
25118 views
Copyright 2020 The TensorFlow Authors.
Save and load Keras 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 or calling
add_loss()
oradd_metric()
).
The Keras API makes it possible to save all of these pieces to disk at once, or to only selectively save some of them:
Saving everything into a single archive in the TensorFlow SavedModel format (or in the older Keras H5 format). This is the standard practice.
Saving the architecture / configuration only, typically as a JSON file.
Saving the weights values only. This is generally used when training the model.
Let's take a look at each of these options. When would you use one or the other, and how do they work?
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
Whole-model saving & loading
You can save an entire model to a single artifact. It 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
model.save()
ortf.keras.models.save_model()
tf.keras.models.load_model()
There are two formats you can use to save an entire model to disk: the TensorFlow SavedModel format, and the older Keras H5 format. The recommended format is SavedModel. It is the default when you use model.save()
.
You can switch to the H5 format by:
Passing
save_format='h5'
tosave()
.Passing a filename that ends in
.h5
or.keras
tosave()
.
SavedModel format
SavedModel is the more comprehensive save format that saves the model architecture, weights, and the traced Tensorflow subgraphs of the call functions. This enables Keras to restore both built-in layers as well as custom objects.
Example:
What the SavedModel contains
Calling model.save('my_model')
creates a folder named my_model
, containing the following:
The model architecture, and training configuration (including the optimizer, losses, and metrics) are stored in saved_model.pb
. The weights are saved in the variables/
directory.
For detailed information on the SavedModel format, see the SavedModel guide (The SavedModel format on disk).
How SavedModel handles custom objects
When saving the model and its layers, the SavedModel format stores the class name, call function, losses, and weights (and the config, if implemented). The call function defines the computation graph of the model/layer.
In the absence of the model/layer config, the call function is used to create a model that exists like the original model which can be trained, evaluated, and used for inference.
Nevertheless, it is always a good practice to define the get_config
and from_config
methods when writing a custom model or layer class. This allows you to easily update the computation later if needed. See the section about Custom objects for more information.
Example:
The first loaded model is loaded using the config and CustomModel
class. The second model is loaded by dynamically creating the model class that acts like the original model.
Configuring the SavedModel
New in TensoFlow 2.4 The argument save_traces
has been added to model.save
, which allows you to toggle SavedModel function tracing. Functions are saved to allow the Keras to re-load custom objects without the original class definitons, so when save_traces=False
, all custom objects must have defined get_config
/from_config
methods. When loading, the custom objects must be passed to the custom_objects
argument. save_traces=False
reduces the disk space used by the SavedModel and saving time.
Keras H5 format
Keras also supports saving a single HDF5 file containing the model's architecture, weights values, and compile()
information. It is a light-weight alternative to SavedModel.
Example:
Limitations
Compared to the SavedModel format, there are two things that don't get included in the H5 file:
External losses & metrics added via
model.add_loss()
&model.add_metric()
are not saved (unlike SavedModel). If you have such losses & metrics on your model and you want to resume training, you need to add these losses back yourself after loading the model. Note that this does not apply to losses/metrics created inside layers viaself.add_loss()
&self.add_metric()
. As long as the layer gets loaded, these losses & metrics are kept, since they are part of thecall
method of the layer.The computation graph of custom objects such as custom layers is not included in the saved file. At loading time, Keras will need access to the Python classes/functions of these objects in order to reconstruct the model. See Custom objects.
Saving the architecture
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 for the weights and no compilation information.
*Note this only applies to models defined using the functional or Sequential apis not subclassed models.
Configuration of a Sequential model or Functional API model
These types of models are explicit graphs of layers: their configuration is always available in a structured form.
APIs
get_config()
andfrom_config()
tf.keras.models.model_to_json()
andtf.keras.models.model_from_json()
get_config()
and from_config()
Calling config = model.get_config()
will return a Python dict containing the configuration of the model. The same model can then be reconstructed via Sequential.from_config(config)
(for a Sequential
model) or Model.from_config(config)
(for a Functional API model).
The same workflow also works for any serializable layer.
Layer example:
Sequential model example:
Functional model example:
to_json()
and tf.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:
Custom objects
Models and layers
The architecture of subclassed models and layers are defined in the methods __init__
and call
. They are considered Python bytecode, which cannot be serialized into a JSON-compatible config -- you could try serializing the bytecode (e.g. via pickle
), but it's completely unsafe and means your model cannot be loaded on a different system.
In order to save/load a model with custom-defined layers, or a subclassed model, you should overwrite the get_config
and optionally from_config
methods. Additionally, you should use register the custom object so that Keras is aware of it.
Custom functions
Custom-defined functions (e.g. activation loss or initialization) do not need a get_config
method. The function name is sufficient for loading as long as it is registered as a custom object.
Loading the TensorFlow graph only
It's possible to load the TensorFlow graph generated by the Keras. If you do so, you won't need to provide any custom_objects
. You can do so like this:
Note that this method has several drawbacks:
For traceability reasons, you should always have access to the custom objects that were used. You wouldn't want to put in production a model that you cannot re-create.
The object returned by
tf.saved_model.load
isn't a Keras model. So it's not as easy to use. For example, you won't have access to.predict()
or.fit()
Even if its use is discouraged, it can help you if you're in a tight spot, for example, if you lost the code of your custom objects or have issues loading the model with tf.keras.models.load_model()
.
You can find out more in the page about tf.saved_model.load
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)
(classmethod
) should return a new layer or model object that is created from the config. The default implementation returnscls(**config)
.
Example:
Registering the custom object
Keras keeps a note of which class generated the config. From the example above, tf.keras.layers.serialize
generates a serialized form of the custom layer:
Keras keeps a master list of all built-in layer, model, optimizer, and metric classes, which is used to find the correct class to call from_config
. If the class can't be found, then an error is raised (Value Error: Unknown layer
). There are a few ways to register custom classes to this list:
Setting
custom_objects
argument in the loading function. (see the example in section above "Defining the config methods")tf.keras.utils.custom_object_scope
ortf.keras.utils.CustomObjectScope
tf.keras.utils.register_keras_serializable
Custom layer and function example
In-memory model cloning
You can also do in-memory cloning of a model via tf.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:
Saving & loading only the model's weights values
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
:
tf.keras.layers.Layer.get_weights()
: Returns a list of numpy arrays.tf.keras.layers.Layer.set_weights()
: Sets the model weights to the values in theweights
argument.
Examples below.
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
in the following formats:
TensorFlow Checkpoint
HDF5
The default format for model.save_weights
is TensorFlow checkpoint. There are two ways to specify the save format:
save_format
argument: Set the value tosave_format="tf"
orsave_format="h5"
.path
argument: If the path ends with.h5
or.hdf5
, then the HDF5 format is used. Other suffixes will result in a TensorFlow checkpoint unlesssave_format
is set.
There is also an option of retrieving weights as in-memory numpy arrays. Each API has its pros and cons which are detailed below.
TF Checkpoint format
Example:
Format details
The TensorFlow Checkpoint format saves and restores the weights using object attribute names. For instance, consider the tf.keras.layers.Dense
layer. The layer contains two weights: dense.kernel
and dense.bias
. When the layer is saved to the tf
format, the resulting checkpoint contains the keys "kernel"
and "bias"
and their corresponding weight values. For more information see "Loading mechanics" in the TF Checkpoint guide.
Note that attribute/graph edge is named after the name used in parent object, not the name of the variable. Consider the CustomLayer
in the example below. The variable CustomLayer.var
is saved with "var"
as part of key, not "var_a"
.
Transfer learning example
Essentially, as long as two models have the same architecture, they are able to share the same checkpoint.
Example:
It is generally recommended to stick to the same API for building models. If you switch between Sequential and Functional, or Functional and subclassed, etc., then always rebuild the pre-trained model and load the pre-trained weights to that model.
The next question is, how can weights be saved and loaded to different models if the model architectures are quite different? The solution is to use tf.train.Checkpoint
to save and restore the exact layers/variables.
Example:
HDF5 format
The HDF5 format contains weights grouped by layer names. The weights are lists ordered by concatenating the list of trainable weights to the list of non-trainable weights (same as layer.weights
). Thus, a model can use a hdf5 checkpoint if it has the same layers and trainable statuses as saved in the checkpoint.
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 HDF5, it is recommended to load the weights into the original checkpointed model, and then extract the desired weights/layers into a new model.
Example: