View source on GitHub |
Saves a model as a TensorFlow SavedModel or HDF5 file.
tf.keras.models.save_model( model, filepath, overwrite=True, include_optimizer=True, save_format=None, signatures=None, options=None )
model = tf.keras.Sequential([ tf.keras.layers.Dense(5, input_shape=(3,)), tf.keras.layers.Softmax()]) model.save('/tmp/model') loaded_model = tf.keras.models.load_model('/tmp/model') x = tf.random.uniform((10, 3)) assert np.allclose(model.predict(x), loaded_model.predict(x))
The saved model contains:
- the model's configuration (topology) - the model's weights - the model's optimizer's state (if any)
Thus the saved model can be reinstantiated in the exact same state, without any of the code used for model definition or training.
Note that the model weights may have different scoped names after being loaded. Scoped names include the model/layer names, such as "dense_1/kernel:0"
. It is recommended that you use the layer properties to access specific variables, e.g. model.get_layer("dense_1").kernel
.
SavedModel serialization
The SavedModel serialization path uses tf.saved_model.save
to save the model and all trackable objects attached to the model (e.g. layers and variables). @tf.function
-decorated methods are also saved. Additional trackable objects and functions are added to the SavedModel to allow the model to be loaded back as a Keras Model object.
Arguments | |
---|---|
model | Keras model instance to be saved. |
filepath | One of the following:
|
overwrite | Whether we should overwrite any existing model at the target location, or instead ask the user with a manual prompt. |
include_optimizer | If True, save optimizer's state together. |
save_format | Either 'tf' or 'h5', indicating whether to save the model to Tensorflow SavedModel or HDF5. Defaults to 'tf' in TF 2.X, and 'h5' in TF 1.X. |
signatures | Signatures to save with the SavedModel. Applicable to the 'tf' format only. Please see the signatures argument in tf.saved_model.save for details. |
options | Optional tf.saved_model.SaveOptions object that specifies options for saving to SavedModel. |
Raises | |
---|---|
ImportError | If save format is hdf5, and h5py is not available. |
© 2020 The TensorFlow Authors. All rights reserved.
Licensed under the Creative Commons Attribution License 3.0.
Code samples licensed under the Apache 2.0 License.
https://www.tensorflow.org/versions/r2.3/api_docs/python/tf/keras/models/save_model