Join us at TensorFlow World, Oct 28-31. Use code TF20 for 20% off select passes. Register now

Save and restore 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:

try:
  # %tensorflow_version only exists in Colab.
  %tensorflow_version 2.x
except Exception:
  pass

!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-rc1

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

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.
WARNING: Logging before flag parsing goes to stderr.
W0813 05:56:52.663807 140260485625600 deprecation.py:323] From /tmpfs/src/tf_docs_env/lib/python3.5/site-packages/tensorflow/python/ops/math_grad.py:1250: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.where in 2.0, which has the same broadcast rule as np.where

Train on 1000 samples, validate on 1000 samples
Epoch 1/10
 544/1000 [===============>..............] - ETA: 0s - loss: 1.5945 - accuracy: 0.5165 
Epoch 00001: saving model to training_1/cp.ckpt
1000/1000 [==============================] - 1s 770us/sample - loss: 1.1882 - accuracy: 0.6570 - val_loss: 0.6953 - val_accuracy: 0.8060
Epoch 2/10
 544/1000 [===============>..............] - ETA: 0s - loss: 0.4965 - accuracy: 0.8529
Epoch 00002: saving model to training_1/cp.ckpt
1000/1000 [==============================] - 0s 190us/sample - loss: 0.4455 - accuracy: 0.8720 - val_loss: 0.5438 - val_accuracy: 0.8220
Epoch 3/10
 576/1000 [================>.............] - ETA: 0s - loss: 0.3156 - accuracy: 0.9149
Epoch 00003: saving model to training_1/cp.ckpt
1000/1000 [==============================] - 0s 190us/sample - loss: 0.3014 - accuracy: 0.9200 - val_loss: 0.4729 - val_accuracy: 0.8460
Epoch 4/10
 544/1000 [===============>..............] - ETA: 0s - loss: 0.2103 - accuracy: 0.9614
Epoch 00004: saving model to training_1/cp.ckpt
1000/1000 [==============================] - 0s 179us/sample - loss: 0.2113 - accuracy: 0.9580 - val_loss: 0.4346 - val_accuracy: 0.8580
Epoch 5/10
 576/1000 [================>.............] - ETA: 0s - loss: 0.1463 - accuracy: 0.9757
Epoch 00005: saving model to training_1/cp.ckpt
1000/1000 [==============================] - 0s 176us/sample - loss: 0.1533 - accuracy: 0.9680 - val_loss: 0.4460 - val_accuracy: 0.8520
Epoch 6/10
 576/1000 [================>.............] - ETA: 0s - loss: 0.1258 - accuracy: 0.9774
Epoch 00006: saving model to training_1/cp.ckpt
1000/1000 [==============================] - 0s 183us/sample - loss: 0.1254 - accuracy: 0.9750 - val_loss: 0.4095 - val_accuracy: 0.8610
Epoch 7/10
 576/1000 [================>.............] - ETA: 0s - loss: 0.0878 - accuracy: 0.9878
Epoch 00007: saving model to training_1/cp.ckpt
1000/1000 [==============================] - 0s 180us/sample - loss: 0.0886 - accuracy: 0.9850 - val_loss: 0.4128 - val_accuracy: 0.8640
Epoch 8/10
 576/1000 [================>.............] - ETA: 0s - loss: 0.0682 - accuracy: 0.9931
Epoch 00008: saving model to training_1/cp.ckpt
1000/1000 [==============================] - 0s 183us/sample - loss: 0.0631 - accuracy: 0.9950 - val_loss: 0.4017 - val_accuracy: 0.8710
Epoch 9/10
 544/1000 [===============>..............] - ETA: 0s - loss: 0.0446 - accuracy: 0.9982
Epoch 00009: saving model to training_1/cp.ckpt
1000/1000 [==============================] - 0s 187us/sample - loss: 0.0520 - accuracy: 0.9960 - val_loss: 0.3958 - val_accuracy: 0.8720
Epoch 10/10
 576/1000 [================>.............] - ETA: 0s - loss: 0.0431 - accuracy: 0.9983
Epoch 00010: saving model to training_1/cp.ckpt
1000/1000 [==============================] - 0s 176us/sample - loss: 0.0458 - accuracy: 0.9960 - val_loss: 0.4169 - val_accuracy: 0.8610

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

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)
print("Untrained model, accuracy: {:5.2f}%".format(100*acc))
1000/1000 [==============================] - 0s 117us/sample - loss: 2.4200 - accuracy: 0.0720
Untrained model, accuracy:  7.20%

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)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))
1000/1000 [==============================] - 0s 62us/sample - loss: 0.4169 - accuracy: 0.8610
Restored model, accuracy: 86.10%

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)
W0813 05:56:56.139839 140260485625600 callbacks.py:859] `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 0x7f90cdb86320>

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)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))
1000/1000 [==============================] - 0s 128us/sample - loss: 0.4938 - accuracy: 0.8770
Restored model, accuracy: 87.70%

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)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))
1000/1000 [==============================] - 0s 124us/sample - loss: 0.4938 - accuracy: 0.8770
Restored model, accuracy: 87.70%

Save the entire model

The model and optimizer can be saved to a file that contains both their state (weights and variables) and the model configuration. 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)

Save model as an HDF5 file

Keras also provides a basic save format using the HDF5 standard. For our purposes, the saved model can be treated as a single binary blob:

# Create a new model instance
model = create_model()

# Train the model
model.fit(train_images, train_labels, epochs=5)

# Save the entire model to a HDF5 file
model.save('my_model.h5')
W0813 05:57:07.036314 140260485625600 util.py:244] Unresolved object in checkpoint: (root).optimizer.iter
W0813 05:57:07.037730 140260485625600 util.py:244] Unresolved object in checkpoint: (root).optimizer.beta_1
W0813 05:57:07.038418 140260485625600 util.py:244] Unresolved object in checkpoint: (root).optimizer.beta_2
W0813 05:57:07.039014 140260485625600 util.py:244] Unresolved object in checkpoint: (root).optimizer.decay
W0813 05:57:07.040382 140260485625600 util.py:244] Unresolved object in checkpoint: (root).optimizer.learning_rate
W0813 05:57:07.041442 140260485625600 util.py:252] 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.
W0813 05:57:07.043382 140260485625600 util.py:244] Unresolved object in checkpoint: (root).optimizer.iter
W0813 05:57:07.044302 140260485625600 util.py:244] Unresolved object in checkpoint: (root).optimizer.beta_1
W0813 05:57:07.045785 140260485625600 util.py:244] Unresolved object in checkpoint: (root).optimizer.beta_2
W0813 05:57:07.046592 140260485625600 util.py:244] Unresolved object in checkpoint: (root).optimizer.decay
W0813 05:57:07.047197 140260485625600 util.py:244] Unresolved object in checkpoint: (root).optimizer.learning_rate
W0813 05:57:07.047771 140260485625600 util.py:252] 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.

Train on 1000 samples
Epoch 1/5
1000/1000 [==============================] - 0s 279us/sample - loss: 1.1772 - accuracy: 0.6680
Epoch 2/5
1000/1000 [==============================] - 0s 104us/sample - loss: 0.4321 - accuracy: 0.8790
Epoch 3/5
1000/1000 [==============================] - 0s 102us/sample - loss: 0.2801 - accuracy: 0.9260
Epoch 4/5
1000/1000 [==============================] - 0s 103us/sample - loss: 0.2170 - accuracy: 0.9520
Epoch 5/5
1000/1000 [==============================] - 0s 103us/sample - loss: 0.1646 - accuracy: 0.9640

Now, recreate the model from that file:

# Recreate the exact same model, including its weights and the optimizer
new_model = 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)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))
1000/1000 [==============================] - 0s 119us/sample - loss: 0.4165 - accuracy: 0.8640
Restored model, accuracy: 86.40%

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.

As a saved_model

Build a new model, then train it:

model = create_model()

model.fit(train_images, train_labels, epochs=5)
Train on 1000 samples
Epoch 1/5
1000/1000 [==============================] - 0s 278us/sample - loss: 1.1439 - accuracy: 0.6650
Epoch 2/5
1000/1000 [==============================] - 0s 107us/sample - loss: 0.4219 - accuracy: 0.8740
Epoch 3/5
1000/1000 [==============================] - 0s 106us/sample - loss: 0.2878 - accuracy: 0.9210
Epoch 4/5
1000/1000 [==============================] - 0s 107us/sample - loss: 0.2007 - accuracy: 0.9560
Epoch 5/5
1000/1000 [==============================] - 0s 108us/sample - loss: 0.1549 - accuracy: 0.9650

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

Create a saved_model, and place it in a time-stamped directory with tf.keras.experimental.export_saved_model:

import time
saved_model_path = "./saved_models/{}".format(int(time.time()))

tf.keras.experimental.export_saved_model(model, saved_model_path)
saved_model_path
W0813 05:57:10.658085 140260485625600 deprecation.py:323] From /tmpfs/src/tf_docs_env/lib/python3.5/site-packages/tensorflow/python/saved_model/signature_def_utils_impl.py:253: build_tensor_info (from tensorflow.python.saved_model.utils_impl) is deprecated and will be removed in a future version.
Instructions for updating:
This function will only be available through the v1 compatibility library as tf.compat.v1.saved_model.utils.build_tensor_info or tf.compat.v1.saved_model.build_tensor_info.
W0813 05:57:10.660027 140260485625600 export_utils.py:182] Export includes no default signature!
W0813 05:57:10.906395 140260485625600 export_utils.py:182] Export includes no default signature!

'./saved_models/1565675829'

List your saved models:

!ls saved_models/
1565675829

Reload a fresh Keras model from the saved model:

new_model = tf.keras.experimental.load_from_saved_model(saved_model_path)

# 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
_________________________________________________________________

Run a prediction with the restored model:

model.predict(test_images).shape
(1000, 10)
# The model has to be compiled before evaluating.
# This step is not required if the saved model is only being deployed.

new_model.compile(optimizer=model.optimizer,  # Keep the optimizer that was loaded
                  loss='sparse_categorical_crossentropy', 
                  metrics=['accuracy'])

# Evaluate the restored model
loss, acc = new_model.evaluate(test_images, test_labels)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))
1000/1000 [==============================] - 0s 132us/sample - loss: 0.4738 - accuracy: 0.8500
Restored model, accuracy: 85.00%
#@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.