Path: blob/master/site/en-snapshot/tutorials/keras/save_and_load.ipynb
25118 views
Copyright 2019 The TensorFlow Authors.
Save and load models
Model progress can be saved during and after training. This means a model can resume where it left off and avoid long training times. Saving also means you can share your model and others can recreate your work. When publishing research models and techniques, most machine learning practitioners share:
code to create the model, and
the trained weights, or parameters, for the model
Sharing this data helps others understand how the model works and try it themselves with new data.
Caution: TensorFlow models are code and it is important to be careful with untrusted code. See Using TensorFlow Securely for details.
Options
There are different ways to save TensorFlow models depending on the API you're using. This guide uses tf.keras—a high-level API to build and train models in TensorFlow. The new, high-level .keras
format used in this tutorial is recommended for saving Keras objects, as it provides robust, efficient name-based saving that is often easier to debug than low-level or legacy formats. For more advanced saving or serialization workflows, especially those involving custom objects, please refer to the Save and load Keras models guide. For other approaches, refer to the Using the SavedModel format guide.
Setup
Installs and imports
Install and import TensorFlow and dependencies:
Get an example dataset
To demonstrate how to save and load weights, you'll use the MNIST dataset. To speed up these runs, use the first 1000 examples:
Define a model
Start by building a simple sequential model:
Save checkpoints during training
You can use a trained model without having to retrain it, or pick-up training where you left off in case the training process was interrupted. The tf.keras.callbacks.ModelCheckpoint
callback allows you to continually save the model both during and at the end of training.
Checkpoint callback usage
Create a tf.keras.callbacks.ModelCheckpoint
callback that saves weights only during training:
This creates a single collection of TensorFlow checkpoint files that are updated at the end of each epoch:
As long as two models share the same architecture you can share weights between them. So, when restoring a model from weights-only, create a model with the same architecture as the original model and then set its weights.
Now rebuild a fresh, untrained model and evaluate it on the test set. An untrained model will perform at chance levels (~10% accuracy):
Then load the weights from the checkpoint and re-evaluate:
Checkpoint callback options
The callback provides several options to provide unique names for checkpoints and adjust the checkpointing frequency.
Train a new model, and save uniquely named checkpoints once every five epochs:
Now, review the resulting checkpoints and choose the latest one:
Note: The default TensorFlow format only saves the 5 most recent checkpoints.
To test, reset the model, and load the latest checkpoint:
What are these files?
The above code stores the weights to a collection of checkpoint-formatted files that contain only the trained weights in a binary format. Checkpoints contain:
One or more shards that contain your model's weights.
An index file that indicates which weights are stored in which shard.
If you are training a model on a single machine, you'll have one shard with the suffix: .data-00000-of-00001
Manually save weights
To save weights manually, use tf.keras.Model.save_weights
. By default, tf.keras
—and the Model.save_weights
method in particular—uses the TensorFlow Checkpoint format with a .ckpt
extension. To save in the HDF5 format with a .h5
extension, refer to the Save and load models guide.
Save the entire model
Call tf.keras.Model.save
to save a model's architecture, weights, and training configuration in a single model.keras
zip archive.
An entire model can be saved in three different file formats (the new .keras
format and two legacy formats: SavedModel
, and HDF5
). Saving a model as path/to/model.keras
automatically saves in the latest format.
Note: For Keras objects it's recommended to use the new high-level .keras
format for richer, name-based saving and reloading, which is easier to debug. The low-level SavedModel format and legacy H5 format continue to be supported for existing code.
You can switch to the SavedModel format by:
Passing
save_format='tf'
tosave()
Passing a filename without an extension
You can switch to the H5 format by:
Passing
save_format='h5'
tosave()
Passing a filename that ends in
.h5
Saving a fully-functional model is very useful—you can load them in TensorFlow.js (Saved Model, HDF5) and then train and run them in web browsers, or convert them to run on mobile devices using TensorFlow Lite (Saved Model, HDF5)
*Custom objects (for example, subclassed models or layers) require special attention when saving and loading. Refer to the Saving custom objects section below.
New high-level .keras
format
The new Keras v3 saving format, marked by the .keras
extension, is a more simple, efficient format that implements name-based saving, ensuring what you load is exactly what you saved, from Python's perspective. This makes debugging much easier, and it is the recommended format for Keras.
The section below illustrates how to save and restore the model in the .keras
format.
Reload a fresh Keras model from the .keras
zip archive:
Try running evaluate and predict with the loaded model:
SavedModel format
The SavedModel format is another way to serialize models. Models saved in this format can be restored using tf.keras.models.load_model
and are compatible with TensorFlow Serving. The SavedModel guide goes into detail about how to serve/inspect
the SavedModel. The section below illustrates the steps to save and restore the model.
The SavedModel format is a directory containing a protobuf binary and a TensorFlow checkpoint. Inspect the saved model directory:
Reload a fresh Keras model from the saved model:
The restored model is compiled with the same arguments as the original model. Try running evaluate and predict with the loaded model:
HDF5 format
Keras provides a basic legacy high-level save format using the HDF5 standard.
Now, recreate the model from that file:
Check its accuracy:
Keras saves models by inspecting their architectures. This technique saves everything:
The weight values
The model's architecture
The model's training configuration (what you pass to the
.compile()
method)The optimizer and its state, if any (this enables you to restart training where you left off)
Keras is not able to save the v1.x
optimizers (from tf.compat.v1.train
) since they aren't compatible with checkpoints. For v1.x optimizers, you need to re-compile the model after loading—losing the state of the optimizer.
Saving custom objects
If you are using the SavedModel format, you can skip this section. The key difference between high-level .keras
/HDF5 formats and the low-level SavedModel format is that the .keras
/HDF5 formats uses object configs to save the model architecture, while SavedModel saves the execution graph. Thus, SavedModels are able to save custom objects like subclassed models and custom layers without requiring the original code. However, debugging low-level SavedModels can be more difficult as a result, and we recommend using the high-level .keras
format instead due to its name-based, Keras-native nature.
To save custom objects to .keras
and HDF5, you must do the following:
Define a
get_config
method in your object, and optionally afrom_config
classmethod.
get_config(self)
returns a JSON-serializable dictionary of parameters needed to recreate the object.from_config(cls, config)
uses the returned config fromget_config
to create a new object. By default, this function will use the config as initialization kwargs (return cls(**config)
).
Pass the custom objects to the model in one of three ways:
Register the custom object with the
@tf.keras.utils.register_keras_serializable
decorator. (recommended)Directly pass the object to the
custom_objects
argument when loading the model. The argument must be a dictionary mapping the string class name to the Python class. E.g.tf.keras.models.load_model(path, custom_objects={'CustomLayer': CustomLayer})
Use a
tf.keras.utils.custom_object_scope
with the object included in thecustom_objects
dictionary argument, and place atf.keras.models.load_model(path)
call within the scope.
Refer to the Writing layers and models from scratch tutorial for examples of custom objects and get_config
.