Save and load models

View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook

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.

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. For other approaches, see the TensorFlow Save and Restore guide or Saving in eager.

Setup

Installs and imports

Install and import TensorFlow and dependencies:


!pip install -q pyyaml h5py  # Required to save models in HDF5 format
from __future__ import absolute_import, division, print_function, unicode_literals

import os

import tensorflow as tf
from tensorflow import keras

print(tf.version.VERSION)
2.0.0

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:

(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()

train_labels = train_labels[:1000]
test_labels = test_labels[:1000]

train_images = train_images[:1000].reshape(-1, 28 * 28) / 255.0
test_images = test_images[:1000].reshape(-1, 28 * 28) / 255.0
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz
11493376/11490434 [==============================] - 0s 0us/step

Define a model

Start by building a simple sequential model:

# Define a simple sequential model
def create_model():
  model = tf.keras.models.Sequential([
    keras.layers.Dense(512, activation='relu', input_shape=(784,)),
    keras.layers.Dropout(0.2),
    keras.layers.Dense(10, activation='softmax')
  ])

  model.compile(optimizer='adam',
                loss='sparse_categorical_crossentropy',
                metrics=['accuracy'])

  return model

# Create a basic model instance
model = create_model()

# Display the model's architecture
model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense (Dense)                (None, 512)               401920    
_________________________________________________________________
dropout (Dropout)            (None, 512)               0         
_________________________________________________________________
dense_1 (Dense)              (None, 10)                5130      
=================================================================
Total params: 407,050
Trainable params: 407,050
Non-trainable params: 0
_________________________________________________________________

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 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:

checkpoint_path = "training_1/cp.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)

# Create a callback that saves the model's weights
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path,
                                                 save_weights_only=True,
                                                 verbose=1)

# Train the model with the new callback
model.fit(train_images, 
          train_labels,  
          epochs=10,
          validation_data=(test_images,test_labels),
          callbacks=[cp_callback])  # Pass callback to training

# This may generate warnings related to saving the state of the optimizer.
# These warnings (and similar warnings throughout this notebook)
# are in place to discourage outdated usage, and can be ignored.
Train on 1000 samples, validate on 1000 samples
Epoch 1/10
 736/1000 [=====================>........] - ETA: 0s - loss: 1.2481 - accuracy: 0.6495 
Epoch 00001: saving model to training_1/cp.ckpt
1000/1000 [==============================] - 1s 987us/sample - loss: 1.1037 - accuracy: 0.6980 - val_loss: 0.7099 - val_accuracy: 0.7900
Epoch 2/10
 768/1000 [======================>.......] - ETA: 0s - loss: 0.4389 - accuracy: 0.8763
Epoch 00002: saving model to training_1/cp.ckpt
1000/1000 [==============================] - 0s 156us/sample - loss: 0.4158 - accuracy: 0.8870 - val_loss: 0.5068 - val_accuracy: 0.8450
Epoch 3/10
 736/1000 [=====================>........] - ETA: 0s - loss: 0.2625 - accuracy: 0.9321
Epoch 00003: saving model to training_1/cp.ckpt
1000/1000 [==============================] - 0s 164us/sample - loss: 0.2715 - accuracy: 0.9350 - val_loss: 0.4682 - val_accuracy: 0.8510
Epoch 4/10
 768/1000 [======================>.......] - ETA: 0s - loss: 0.2047 - accuracy: 0.9505
Epoch 00004: saving model to training_1/cp.ckpt
1000/1000 [==============================] - 0s 158us/sample - loss: 0.2052 - accuracy: 0.9510 - val_loss: 0.4303 - val_accuracy: 0.8620
Epoch 5/10
 768/1000 [======================>.......] - ETA: 0s - loss: 0.1525 - accuracy: 0.9714
Epoch 00005: saving model to training_1/cp.ckpt
1000/1000 [==============================] - 0s 160us/sample - loss: 0.1444 - accuracy: 0.9720 - val_loss: 0.4277 - val_accuracy: 0.8570
Epoch 6/10
 768/1000 [======================>.......] - ETA: 0s - loss: 0.1181 - accuracy: 0.9831
Epoch 00006: saving model to training_1/cp.ckpt
1000/1000 [==============================] - 0s 164us/sample - loss: 0.1148 - accuracy: 0.9840 - val_loss: 0.4238 - val_accuracy: 0.8620
Epoch 7/10
 736/1000 [=====================>........] - ETA: 0s - loss: 0.0769 - accuracy: 0.9891
Epoch 00007: saving model to training_1/cp.ckpt
1000/1000 [==============================] - 0s 160us/sample - loss: 0.0872 - accuracy: 0.9850 - val_loss: 0.3968 - val_accuracy: 0.8690
Epoch 8/10
 768/1000 [======================>.......] - ETA: 0s - loss: 0.0633 - accuracy: 0.9935
Epoch 00008: saving model to training_1/cp.ckpt
1000/1000 [==============================] - 0s 160us/sample - loss: 0.0639 - accuracy: 0.9940 - val_loss: 0.4035 - val_accuracy: 0.8700
Epoch 9/10
 768/1000 [======================>.......] - ETA: 0s - loss: 0.0460 - accuracy: 0.9974
Epoch 00009: saving model to training_1/cp.ckpt
1000/1000 [==============================] - 0s 161us/sample - loss: 0.0459 - accuracy: 0.9980 - val_loss: 0.4052 - val_accuracy: 0.8670
Epoch 10/10
 800/1000 [=======================>......] - ETA: 0s - loss: 0.0366 - accuracy: 0.9975
Epoch 00010: saving model to training_1/cp.ckpt
1000/1000 [==============================] - 0s 158us/sample - loss: 0.0390 - accuracy: 0.9960 - val_loss: 0.4007 - val_accuracy: 0.8650

<tensorflow.python.keras.callbacks.History at 0x7fb5ceaca710>

This creates a single collection of TensorFlow checkpoint files that are updated at the end of each epoch:

!ls {checkpoint_dir}
checkpoint           cp.ckpt.data-00001-of-00002
cp.ckpt.data-00000-of-00002  cp.ckpt.index

Create a new, untrained model. When restoring a model from weights-only, you must have a model with the same architecture as the original model. Since it's the same model architecture, you can share weights despite that it's a different instance of the model.

Now rebuild a fresh, untrained model, and evaluate it on the test set. An untrained model will perform at chance levels (~10% accuracy):

# Create a basic model instance
model = create_model()

# Evaluate the model
loss, acc = model.evaluate(test_images,  test_labels, verbose=2)
print("Untrained model, accuracy: {:5.2f}%".format(100*acc))
1000/1 - 0s - loss: 2.3598 - accuracy: 0.1360
Untrained model, accuracy: 13.60%

Then load the weights from the checkpoint and re-evaluate:

# Loads the weights
model.load_weights(checkpoint_path)

# Re-evaluate the model
loss,acc = model.evaluate(test_images,  test_labels, verbose=2)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))
1000/1 - 0s - loss: 0.3937 - accuracy: 0.8650
Restored model, accuracy: 86.50%

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:

# Include the epoch in the file name (uses `str.format`)
checkpoint_path = "training_2/cp-{epoch:04d}.ckpt"
checkpoint_dir = os.path.dirname(checkpoint_path)

# Create a callback that saves the model's weights every 5 epochs
cp_callback = tf.keras.callbacks.ModelCheckpoint(
    filepath=checkpoint_path, 
    verbose=1, 
    save_weights_only=True,
    period=5)

# Create a new model instance
model = create_model()

# Save the weights using the `checkpoint_path` format
model.save_weights(checkpoint_path.format(epoch=0))

# Train the model with the new callback
model.fit(train_images, 
              train_labels,
              epochs=50, 
              callbacks=[cp_callback],
              validation_data=(test_images,test_labels),
              verbose=0)
WARNING:tensorflow:`period` argument is deprecated. Please use `save_freq` to specify the frequency in number of samples seen.

Epoch 00005: saving model to training_2/cp-0005.ckpt

Epoch 00010: saving model to training_2/cp-0010.ckpt

Epoch 00015: saving model to training_2/cp-0015.ckpt

Epoch 00020: saving model to training_2/cp-0020.ckpt

Epoch 00025: saving model to training_2/cp-0025.ckpt

Epoch 00030: saving model to training_2/cp-0030.ckpt

Epoch 00035: saving model to training_2/cp-0035.ckpt

Epoch 00040: saving model to training_2/cp-0040.ckpt

Epoch 00045: saving model to training_2/cp-0045.ckpt

Epoch 00050: saving model to training_2/cp-0050.ckpt

<tensorflow.python.keras.callbacks.History at 0x7fb642df5780>

Now, look at the resulting checkpoints and choose the latest one:

!ls {checkpoint_dir}
checkpoint            cp-0025.ckpt.data-00001-of-00002
cp-0000.ckpt.data-00000-of-00002  cp-0025.ckpt.index
cp-0000.ckpt.data-00001-of-00002  cp-0030.ckpt.data-00000-of-00002
cp-0000.ckpt.index        cp-0030.ckpt.data-00001-of-00002
cp-0005.ckpt.data-00000-of-00002  cp-0030.ckpt.index
cp-0005.ckpt.data-00001-of-00002  cp-0035.ckpt.data-00000-of-00002
cp-0005.ckpt.index        cp-0035.ckpt.data-00001-of-00002
cp-0010.ckpt.data-00000-of-00002  cp-0035.ckpt.index
cp-0010.ckpt.data-00001-of-00002  cp-0040.ckpt.data-00000-of-00002
cp-0010.ckpt.index        cp-0040.ckpt.data-00001-of-00002
cp-0015.ckpt.data-00000-of-00002  cp-0040.ckpt.index
cp-0015.ckpt.data-00001-of-00002  cp-0045.ckpt.data-00000-of-00002
cp-0015.ckpt.index        cp-0045.ckpt.data-00001-of-00002
cp-0020.ckpt.data-00000-of-00002  cp-0045.ckpt.index
cp-0020.ckpt.data-00001-of-00002  cp-0050.ckpt.data-00000-of-00002
cp-0020.ckpt.index        cp-0050.ckpt.data-00001-of-00002
cp-0025.ckpt.data-00000-of-00002  cp-0050.ckpt.index
latest = tf.train.latest_checkpoint(checkpoint_dir)
latest
'training_2/cp-0050.ckpt'

To test, reset the model and load the latest checkpoint:

# Create a new model instance
model = create_model()

# Load the previously saved weights
model.load_weights(latest)

# Re-evaluate the model
loss, acc = model.evaluate(test_images,  test_labels, verbose=2)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))
1000/1 - 0s - loss: 0.5208 - accuracy: 0.8750
Restored model, accuracy: 87.50%

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 a which shard.

If you are only training a model on a single machine, you'll have one shard with the suffix: .data-00000-of-00001

Manually save weights

You saw how to load the weights into a model. Manually saving them is just as simple with the Model.save_weights method. By default, tf.keras—and save_weights in particular—uses the TensorFlow checkpoints format with a .ckpt extension (saving in HDF5 with a .h5 extension is covered in the Save and serialize models guide):

# Save the weights
model.save_weights('./checkpoints/my_checkpoint')

# Create a new model instance
model = create_model()

# Restore the weights
model.load_weights('./checkpoints/my_checkpoint')

# Evaluate the model
loss,acc = model.evaluate(test_images,  test_labels, verbose=2)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))
WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.iter
WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.beta_1
WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.beta_2
WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.decay
WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.learning_rate
WARNING:tensorflow:A checkpoint was restored (e.g. tf.train.Checkpoint.restore or tf.keras.Model.load_weights) but not all checkpointed values were used. See above for specific issues. Use expect_partial() on the load status object, e.g. tf.train.Checkpoint.restore(...).expect_partial(), to silence these warnings, or use assert_consumed() to make the check explicit. See https://www.tensorflow.org/alpha/guide/checkpoints#loading_mechanics for details.
WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.iter
WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.beta_1
WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.beta_2
WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.decay
WARNING:tensorflow:Unresolved object in checkpoint: (root).optimizer.learning_rate
WARNING:tensorflow:A checkpoint was restored (e.g. tf.train.Checkpoint.restore or tf.keras.Model.load_weights) but not all checkpointed values were used. See above for specific issues. Use expect_partial() on the load status object, e.g. tf.train.Checkpoint.restore(...).expect_partial(), to silence these warnings, or use assert_consumed() to make the check explicit. See https://www.tensorflow.org/alpha/guide/checkpoints#loading_mechanics for details.
1000/1 - 0s - loss: 0.5208 - accuracy: 0.8750
Restored model, accuracy: 87.50%

Save the entire model

Call model.save to save the a model's architecture, weights, and training configuration in a single file/folder. This allows you to export a model so it can be used without access to the original Python code*. Since the optimizer-state is recovered, you can resume training from exactly where you left off.

Saving a fully-functional model is very useful—you can load them in TensorFlow.js (HDF5, Saved Model) and then train and run them in web browsers, or convert them to run on mobile devices using TensorFlow Lite (HDF5, Saved Model)

*Custom objects (e.g. subclassed models or layers) require special attention when saving and loading. See the Saving custom objects section below

HDF5 format

Keras provides a basic save format using the HDF5 standard.

# Create and train a new model instance.
model = create_model()
model.fit(train_images, train_labels, epochs=5)

# Save the entire model to a HDF5 file.
# The '.h5' extension indicates that the model shuold be saved to HDF5.
model.save('my_model.h5') 
Train on 1000 samples
Epoch 1/5
1000/1000 [==============================] - 0s 372us/sample - loss: 1.1794 - accuracy: 0.6460
Epoch 2/5
1000/1000 [==============================] - 0s 69us/sample - loss: 0.4345 - accuracy: 0.8630
Epoch 3/5
1000/1000 [==============================] - 0s 74us/sample - loss: 0.2957 - accuracy: 0.9160
Epoch 4/5
1000/1000 [==============================] - 0s 72us/sample - loss: 0.2053 - accuracy: 0.9520
Epoch 5/5
1000/1000 [==============================] - 0s 72us/sample - loss: 0.1553 - accuracy: 0.9660

Now, recreate the model from that file:

# Recreate the exact same model, including its weights and the optimizer
new_model = tf.keras.models.load_model('my_model.h5')

# Show the model architecture
new_model.summary()
Model: "sequential_5"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_10 (Dense)             (None, 512)               401920    
_________________________________________________________________
dropout_5 (Dropout)          (None, 512)               0         
_________________________________________________________________
dense_11 (Dense)             (None, 10)                5130      
=================================================================
Total params: 407,050
Trainable params: 407,050
Non-trainable params: 0
_________________________________________________________________

Check its accuracy:

loss, acc = new_model.evaluate(test_images,  test_labels, verbose=2)
print('Restored model, accuracy: {:5.2f}%'.format(100*acc))
1000/1 - 0s - loss: 0.5667 - accuracy: 0.8630
Restored model, accuracy: 86.30%

This technique saves everything:

  • The weight values
  • The model's configuration(architecture)
  • The optimizer configuration

Keras saves models by inspecting the architecture. Currently, it is not able to save TensorFlow optimizers (from tf.train). When using those you will need to re-compile the model after loading, and you will lose the state of the optimizer.

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 saving and restoring the model.

# Create and train a new model instance.
model = create_model()
model.fit(train_images, train_labels, epochs=5)

# Save the entire model as a SavedModel.
!mkdir -p saved_model
model.save('saved_model/my_model') 
Train on 1000 samples
Epoch 1/5
1000/1000 [==============================] - 0s 492us/sample - loss: 1.1973 - accuracy: 0.6570
Epoch 2/5
1000/1000 [==============================] - 0s 72us/sample - loss: 0.4279 - accuracy: 0.8820
Epoch 3/5
1000/1000 [==============================] - 0s 73us/sample - loss: 0.2931 - accuracy: 0.9210
Epoch 4/5
1000/1000 [==============================] - 0s 72us/sample - loss: 0.2096 - accuracy: 0.9510
Epoch 5/5
1000/1000 [==============================] - 0s 75us/sample - loss: 0.1501 - accuracy: 0.9660
WARNING:tensorflow:From /tmpfs/src/tf_docs_env/lib/python3.6/site-packages/tensorflow_core/python/ops/resource_variable_ops.py:1781: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.
Instructions for updating:
If using Keras pass *_constraint arguments to layers.
INFO:tensorflow:Assets written to: saved_model/my_model/assets

The SavedModel format is a directory containing a protobuf binary and a Tensorflow checkpoint. Inspect the saved model directory:

# my_model directory
!ls saved_model

# Contains an assets folder, saved_model.pb, and variables folder.
!ls saved_model/my_model
my_model
assets  saved_model.pb  variables

Reload a fresh Keras model from the saved model:

new_model = tf.keras.models.load_model('saved_model/my_model')

# Check its architecture
new_model.summary()
Model: "sequential_6"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_12 (Dense)             (None, 512)               401920    
_________________________________________________________________
dropout_6 (Dropout)          (None, 512)               0         
_________________________________________________________________
dense_13 (Dense)             (None, 10)                5130      
=================================================================
Total params: 407,050
Trainable params: 407,050
Non-trainable params: 0
_________________________________________________________________

The restored model is compiled with the same arguments as the original model. Try running evaluate and predict with the loaded model:

# Evaluate the restored model
loss, acc = new_model.evaluate(test_images,  test_labels, verbose=2)
print('Restored model, accuracy: {:5.2f}%'.format(100*acc))

print(new_model.predict(test_images).shape)
1000/1 - 0s - loss: 0.5041 - accuracy: 0.8550
Restored model, accuracy: 85.50%
(1000, 10)

Saving custom objects

If you are using the SavedModel format, you can skip this section. The key difference between HDF5 and SavedModel is that HDF5 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 orginal code.

To save custom objects to HDF5, you must do the following:

  1. Define a get_config method in your object, and optionally a from_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 from get_config to create a new object. By default, this function will use the config as initialization kwargs (return cls(**config)).
  2. 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})

See the Writing layers and models from scratch tutorial for examples of custom objects and get_config.

#@title MIT License
#
# Copyright (c) 2017 François Chollet
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.