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

pip install pyyaml h5py  # Required to save models in HDF5 format.
import os

import tensorflow as tf
from tensorflow import keras

print(tf.version.VERSION)
2025-12-03 05:22:40.216427: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:467] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered
WARNING: All log messages before absl::InitializeLog() is called are written to STDERR
E0000 00:00:1764739360.238836  521372 cuda_dnn.cc:8579] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered
E0000 00:00:1764739360.246316  521372 cuda_blas.cc:1407] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered
W0000 00:00:1764739360.264225  521372 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.
W0000 00:00:1764739360.264245  521372 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.
W0000 00:00:1764739360.264247  521372 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.
W0000 00:00:1764739360.264249  521372 computation_placer.cc:177] computation placer already registered. Please check linkage and avoid linking the same target more than once.
2.19.1

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.Sequential([
    keras.layers.Dense(512, activation='relu', input_shape=(784,)),
    keras.layers.Dropout(0.2),
    keras.layers.Dense(10)
  ])

  model.compile(optimizer='adam',
                loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
                metrics=[tf.keras.metrics.SparseCategoricalAccuracy()])

  return model

# Create a basic model instance
model = create_model()

# Display the model's architecture
model.summary()
/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/keras/src/layers/core/dense.py:93: UserWarning: Do not pass an `input_shape`/`input_dim` argument to a layer. When using Sequential models, prefer using an `Input(shape)` object as the first layer in the model instead.
  super().__init__(activity_regularizer=activity_regularizer, **kwargs)
I0000 00:00:1764739365.058683  521372 gpu_device.cc:2019] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 13638 MB memory:  -> device: 0, name: Tesla T4, pci bus id: 0000:00:05.0, compute capability: 7.5
I0000 00:00:1764739365.061077  521372 gpu_device.cc:2019] Created device /job:localhost/replica:0/task:0/device:GPU:1 with 13756 MB memory:  -> device: 1, name: Tesla T4, pci bus id: 0000:00:06.0, compute capability: 7.5
I0000 00:00:1764739365.063291  521372 gpu_device.cc:2019] Created device /job:localhost/replica:0/task:0/device:GPU:2 with 13756 MB memory:  -> device: 2, name: Tesla T4, pci bus id: 0000:00:07.0, compute capability: 7.5
I0000 00:00:1764739365.065558  521372 gpu_device.cc:2019] Created device /job:localhost/replica:0/task:0/device:GPU:3 with 13756 MB memory:  -> device: 3, name: Tesla T4, pci bus id: 0000:00:08.0, compute capability: 7.5

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:

checkpoint_path = "training_1/cp.weights.h5" # Since you're only saving weights, you should use the .weights.h5 extension. If you're saving the whole model, you would use the .keras extension instead
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.
Epoch 1/10
WARNING: All log messages before absl::InitializeLog() is called are written to STDERR
I0000 00:00:1764739366.870224  521544 service.cc:152] XLA service 0x7f4894009dd0 initialized for platform CUDA (this does not guarantee that XLA will be used). Devices:
I0000 00:00:1764739366.870258  521544 service.cc:160]   StreamExecutor device (0): Tesla T4, Compute Capability 7.5
I0000 00:00:1764739366.870266  521544 service.cc:160]   StreamExecutor device (1): Tesla T4, Compute Capability 7.5
I0000 00:00:1764739366.870270  521544 service.cc:160]   StreamExecutor device (2): Tesla T4, Compute Capability 7.5
I0000 00:00:1764739366.870275  521544 service.cc:160]   StreamExecutor device (3): Tesla T4, Compute Capability 7.5
I0000 00:00:1764739366.994028  521544 cuda_dnn.cc:529] Loaded cuDNN version 91600
23/32 ━━━━━━━━━━━━━━━━━━━━ 0s 2ms/step - loss: 1.8264 - sparse_categorical_accuracy: 0.3937
I0000 00:00:1764739368.130209  521544 device_compiler.h:188] Compiled cluster using XLA!  This line is logged at most once for the lifetime of the process.
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 31ms/step - loss: 1.6672 - sparse_categorical_accuracy: 0.4600
Epoch 1: saving model to training_1/cp.weights.h5
32/32 ━━━━━━━━━━━━━━━━━━━━ 4s 62ms/step - loss: 1.6527 - sparse_categorical_accuracy: 0.4659 - val_loss: 0.7262 - val_sparse_categorical_accuracy: 0.7840
Epoch 2/10
25/32 ━━━━━━━━━━━━━━━━━━━━ 0s 2ms/step - loss: 0.4149 - sparse_categorical_accuracy: 0.8846
Epoch 2: saving model to training_1/cp.weights.h5
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 9ms/step - loss: 0.4216 - sparse_categorical_accuracy: 0.8818 - val_loss: 0.5371 - val_sparse_categorical_accuracy: 0.8300
Epoch 3/10
25/32 ━━━━━━━━━━━━━━━━━━━━ 0s 2ms/step - loss: 0.2876 - sparse_categorical_accuracy: 0.9349
Epoch 3: saving model to training_1/cp.weights.h5
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 9ms/step - loss: 0.2897 - sparse_categorical_accuracy: 0.9314 - val_loss: 0.4570 - val_sparse_categorical_accuracy: 0.8580
Epoch 4/10
27/32 ━━━━━━━━━━━━━━━━━━━━ 0s 2ms/step - loss: 0.2002 - sparse_categorical_accuracy: 0.9657
Epoch 4: saving model to training_1/cp.weights.h5
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 8ms/step - loss: 0.2061 - sparse_categorical_accuracy: 0.9630 - val_loss: 0.4543 - val_sparse_categorical_accuracy: 0.8480
Epoch 5/10
26/32 ━━━━━━━━━━━━━━━━━━━━ 0s 2ms/step - loss: 0.1851 - sparse_categorical_accuracy: 0.9564
Epoch 5: saving model to training_1/cp.weights.h5
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 9ms/step - loss: 0.1815 - sparse_categorical_accuracy: 0.9575 - val_loss: 0.4271 - val_sparse_categorical_accuracy: 0.8660
Epoch 6/10
25/32 ━━━━━━━━━━━━━━━━━━━━ 0s 2ms/step - loss: 0.1170 - sparse_categorical_accuracy: 0.9853
Epoch 6: saving model to training_1/cp.weights.h5
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 9ms/step - loss: 0.1173 - sparse_categorical_accuracy: 0.9840 - val_loss: 0.4564 - val_sparse_categorical_accuracy: 0.8480
Epoch 7/10
26/32 ━━━━━━━━━━━━━━━━━━━━ 0s 2ms/step - loss: 0.1011 - sparse_categorical_accuracy: 0.9850
Epoch 7: saving model to training_1/cp.weights.h5
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 9ms/step - loss: 0.1012 - sparse_categorical_accuracy: 0.9853 - val_loss: 0.4108 - val_sparse_categorical_accuracy: 0.8650
Epoch 8/10
26/32 ━━━━━━━━━━━━━━━━━━━━ 0s 2ms/step - loss: 0.0713 - sparse_categorical_accuracy: 0.9871
Epoch 8: saving model to training_1/cp.weights.h5
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 9ms/step - loss: 0.0709 - sparse_categorical_accuracy: 0.9881 - val_loss: 0.4158 - val_sparse_categorical_accuracy: 0.8650
Epoch 9/10
26/32 ━━━━━━━━━━━━━━━━━━━━ 0s 2ms/step - loss: 0.0507 - sparse_categorical_accuracy: 0.9985
Epoch 9: saving model to training_1/cp.weights.h5
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 9ms/step - loss: 0.0514 - sparse_categorical_accuracy: 0.9982 - val_loss: 0.4128 - val_sparse_categorical_accuracy: 0.8670
Epoch 10/10
27/32 ━━━━━━━━━━━━━━━━━━━━ 0s 2ms/step - loss: 0.0404 - sparse_categorical_accuracy: 0.9995
Epoch 10: saving model to training_1/cp.weights.h5
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 9ms/step - loss: 0.0410 - sparse_categorical_accuracy: 0.9992 - val_loss: 0.4389 - val_sparse_categorical_accuracy: 0.8620
<keras.src.callbacks.history.History at 0x7f4a9f28dfd0>

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

os.listdir(checkpoint_dir)
['cp.weights.h5']

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

# 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))
32/32 - 1s - 26ms/step - loss: 2.3316 - sparse_categorical_accuracy: 0.1200
Untrained model, accuracy: 12.00%

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))
32/32 - 0s - 4ms/step - loss: 0.4389 - sparse_categorical_accuracy: 0.8620
Restored model, accuracy: 86.20%
/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/keras/src/saving/saving_lib.py:802: UserWarning: Skipping variable loading for optimizer 'adam', because it has 2 variables whereas the saved optimizer has 10 variables. 
  saveable.load_own_variables(weights_store.get(inner_path))

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}.weights.h5"
checkpoint_dir = os.path.dirname(checkpoint_path)
os.mkdir(checkpoint_dir)

batch_size = 32

# Calculate the number of batches per epoch
import math
n_batches = len(train_images) / batch_size
n_batches = math.ceil(n_batches)    # round up the number of batches to the nearest whole integer

# 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,
    save_freq=5*n_batches)

# 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,
          batch_size=batch_size,
          callbacks=[cp_callback],
          validation_data=(test_images, test_labels),
          verbose=0)
Epoch 5: saving model to training_2/cp-0005.weights.h5
Epoch 10: saving model to training_2/cp-0010.weights.h5
Epoch 15: saving model to training_2/cp-0015.weights.h5
Epoch 20: saving model to training_2/cp-0020.weights.h5
Epoch 25: saving model to training_2/cp-0025.weights.h5
Epoch 30: saving model to training_2/cp-0030.weights.h5
Epoch 35: saving model to training_2/cp-0035.weights.h5
Epoch 40: saving model to training_2/cp-0040.weights.h5
Epoch 45: saving model to training_2/cp-0045.weights.h5
Epoch 50: saving model to training_2/cp-0050.weights.h5
<keras.src.callbacks.history.History at 0x7f4a04022cd0>

Now, review the resulting checkpoints and choose the latest one:

os.listdir(checkpoint_dir)
['cp-0020.weights.h5',
 'cp-0030.weights.h5',
 'cp-0010.weights.h5',
 'cp-0050.weights.h5',
 'cp-0040.weights.h5',
 'cp-0045.weights.h5',
 'cp-0000.weights.h5',
 'cp-0035.weights.h5',
 'cp-0005.weights.h5',
 'cp-0025.weights.h5',
 'cp-0015.weights.h5']
def load_latest_checkpoint(checkpoint_dir):
    latest = max(os.listdir(checkpoint_dir), key=lambda f: int(f.split('-')[1].split('.')[0]))
    return os.path.join(checkpoint_dir, latest)

latest = load_latest_checkpoint(checkpoint_dir)
latest
'training_2/cp-0050.weights.h5'

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))
32/32 - 1s - 26ms/step - loss: 0.4777 - sparse_categorical_accuracy: 0.8760
Restored model, accuracy: 87.60%

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. You have to use .weights.h5 extension to save the weights. You can refer to the Save and load models guide.

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

# Create a new model instance
model = create_model()

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

# Evaluate the model
loss, acc = model.evaluate(test_images, test_labels, verbose=2)
print("Restored model, accuracy: {:5.2f}%".format(100 * acc))
32/32 - 1s - 26ms/step - loss: 0.4777 - sparse_categorical_accuracy: 0.8760
Restored model, accuracy: 87.60%

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.

You can switch to the SavedModel format by:

  • Passing save_format='tf' to save()
  • Passing a filename without an extension

You can switch to the H5 format by:

  • Passing save_format='h5' to save()
  • 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.

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

# Save the entire model as a `.keras` zip archive.
model.save('my_model.keras')
Epoch 1/5
32/32 ━━━━━━━━━━━━━━━━━━━━ 2s 28ms/step - loss: 1.5471 - sparse_categorical_accuracy: 0.5323
Epoch 2/5
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 3ms/step - loss: 0.4804 - sparse_categorical_accuracy: 0.8675
Epoch 3/5
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 3ms/step - loss: 0.3042 - sparse_categorical_accuracy: 0.9212
Epoch 4/5
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 3ms/step - loss: 0.2119 - sparse_categorical_accuracy: 0.9509
Epoch 5/5
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 3ms/step - loss: 0.1464 - sparse_categorical_accuracy: 0.9704

Reload a fresh Keras model from the .keras zip archive:

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

# Show the model architecture
new_model.summary()

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)
32/32 - 1s - 26ms/step - loss: 0.4088 - sparse_categorical_accuracy: 0.8680
Restored model, accuracy: 86.80%
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 7ms/step
(1000, 10)

SavedModel format

The SavedModel format is another way to serialize models. Models saved in this format can directly be used with TFLite/TFServing/etc for inferencing. 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.

# 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
tf.saved_model.save(model, 'saved_model/my_model')
Epoch 1/5
32/32 ━━━━━━━━━━━━━━━━━━━━ 2s 28ms/step - loss: 1.6237 - sparse_categorical_accuracy: 0.4981
Epoch 2/5
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 3ms/step - loss: 0.5018 - sparse_categorical_accuracy: 0.8567
Epoch 3/5
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 3ms/step - loss: 0.2820 - sparse_categorical_accuracy: 0.9101
Epoch 4/5
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 3ms/step - loss: 0.1979 - sparse_categorical_accuracy: 0.9597
Epoch 5/5
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 3ms/step - loss: 0.1548 - sparse_categorical_accuracy: 0.9734
INFO:tensorflow:Assets written to: saved_model/my_model/assets
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  fingerprint.pb  saved_model.pb  variables

Reload the saved SavedModel file:

saved_model = tf.saved_model.load('saved_model/my_model')
saved_model
<tensorflow.python.saved_model.load.Loader._recreate_base_user_object.<locals>._UserObject at 0x7f4b90b22af0>

HDF5 format

Keras provides a basic legacy high-level 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 should be saved to HDF5.
model.save('my_model.h5')
Epoch 1/5
/tmpfs/src/tf_docs_env/lib/python3.9/site-packages/keras/src/layers/core/dense.py:93: UserWarning: Do not pass an `input_shape`/`input_dim` argument to a layer. When using Sequential models, prefer using an `Input(shape)` object as the first layer in the model instead.
  super().__init__(activity_regularizer=activity_regularizer, **kwargs)
32/32 ━━━━━━━━━━━━━━━━━━━━ 2s 28ms/step - loss: 1.5877 - sparse_categorical_accuracy: 0.5199
Epoch 2/5
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 3ms/step - loss: 0.4432 - sparse_categorical_accuracy: 0.8676
Epoch 3/5
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 3ms/step - loss: 0.2809 - sparse_categorical_accuracy: 0.9341
Epoch 4/5
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 3ms/step - loss: 0.1933 - sparse_categorical_accuracy: 0.9577
Epoch 5/5
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 3ms/step - loss: 0.1651 - sparse_categorical_accuracy: 0.9568
WARNING:absl:You are saving your model as an HDF5 file via `model.save()` or `keras.saving.save_model(model)`. This file format is considered legacy. We recommend using instead the native Keras format, e.g. `model.save('my_model.keras')` or `keras.saving.save_model(model, 'my_model.keras')`.

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()
WARNING:absl:Compiled the loaded model, but the compiled metrics have yet to be built. `model.compile_metrics` will be empty until you train or evaluate the model.

Check its accuracy:

loss, acc = new_model.evaluate(test_images, test_labels, verbose=2)
print('Restored model, accuracy: {:5.2f}%'.format(100 * acc))
32/32 - 1s - 27ms/step - loss: 0.4218 - sparse_categorical_accuracy: 0.8680
Restored model, accuracy: 86.80%

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 the recommended approach is using the high-level .keras format instead due to its name-based, Keras built-in nature.

To save custom objects to .keras and 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 custom objects to the model in one of three ways:

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

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