```
library(tensorflow)
library(keras)
```

# Save and load

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

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

```
c(c(train_images, train_labels), c(test_images, test_labels)) %<-% dataset_mnist()
<- train_labels[1:1000]
train_labels <- test_labels[1:1000]
test_labels
<- train_images[1:1000,,] %>% array_reshape(dim = c(1000, 784))/255
train_images <- test_images[1:1000,,] %>% array_reshape(dim = c(1000, 784))/255 test_images
```

### Define a model

Start by building a simple sequential model:

```
# Define a simple sequential model
<- function() {
create_model <- keras_model_sequential() %>%
model layer_dense(512, activation = 'relu', input_shape = shape(784)) %>%
layer_dropout(0.2) %>%
layer_dense(10)
%>% compile(
model optimizer = 'adam',
loss = loss_sparse_categorical_crossentropy(from_logits = TRUE),
metrics = list(metric_sparse_categorical_accuracy())
)
model
}
# Create a basic model instance
<- create_model()
model
# Display the model's architecture
summary(model)
```

```
Model: "sequential"
____________________________________________________________________________
Layer (type) Output Shape Param #
============================================================================
dense_1 (Dense) (None, 512) 401920
dropout (Dropout) (None, 512) 0
dense (Dense) (None, 10) 5130
============================================================================
Total params: 407050 (1.55 MB)
Trainable params: 407050 (1.55 MB)
Non-trainable params: 0 (0.00 Byte)
____________________________________________________________________________
```

## 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 `callback_model_checkpoint()`

callback allows you to continually save the model both *during* and at *the end* of training.

### Checkpoint callback usage

Create a `callback_model_checkpoint()`

callback that saves weights only during training:

```
<- "training_1/cp.ckpt"
checkpoint_path <- fs::path_dir(checkpoint_path)
checkpoint_dir
# Create a callback that saves the model's weights
<- callback_model_checkpoint(
cp_callback filepath = checkpoint_path,
save_weights_only = TRUE,
verbose = 1
)
# Train the model with the new callback
%>% fit(
model
train_images,
train_labels,epochs = 10,
validation_data = list(test_images, test_labels),
callbacks = list(cp_callback) # Pass callback to training
)
```

```
Epoch 1/10
Epoch 1: saving model to training_1/cp.ckpt
32/32 - 1s - loss: 1.1534 - sparse_categorical_accuracy: 0.6730 - val_loss: 0.7187 - val_sparse_categorical_accuracy: 0.7840 - 940ms/epoch - 29ms/step
Epoch 2/10
Epoch 2: saving model to training_1/cp.ckpt
32/32 - 0s - loss: 0.4104 - sparse_categorical_accuracy: 0.8810 - val_loss: 0.5314 - val_sparse_categorical_accuracy: 0.8410 - 129ms/epoch - 4ms/step
Epoch 3/10
Epoch 3: saving model to training_1/cp.ckpt
32/32 - 0s - loss: 0.2863 - sparse_categorical_accuracy: 0.9230 - val_loss: 0.5097 - val_sparse_categorical_accuracy: 0.8270 - 125ms/epoch - 4ms/step
Epoch 4/10
Epoch 4: saving model to training_1/cp.ckpt
32/32 - 0s - loss: 0.2128 - sparse_categorical_accuracy: 0.9370 - val_loss: 0.4331 - val_sparse_categorical_accuracy: 0.8560 - 118ms/epoch - 4ms/step
Epoch 5/10
Epoch 5: saving model to training_1/cp.ckpt
32/32 - 0s - loss: 0.1484 - sparse_categorical_accuracy: 0.9710 - val_loss: 0.4299 - val_sparse_categorical_accuracy: 0.8640 - 124ms/epoch - 4ms/step
Epoch 6/10
Epoch 6: saving model to training_1/cp.ckpt
32/32 - 0s - loss: 0.1146 - sparse_categorical_accuracy: 0.9720 - val_loss: 0.4172 - val_sparse_categorical_accuracy: 0.8600 - 123ms/epoch - 4ms/step
Epoch 7/10
Epoch 7: saving model to training_1/cp.ckpt
32/32 - 0s - loss: 0.0776 - sparse_categorical_accuracy: 0.9920 - val_loss: 0.4153 - val_sparse_categorical_accuracy: 0.8700 - 120ms/epoch - 4ms/step
Epoch 8/10
Epoch 8: saving model to training_1/cp.ckpt
32/32 - 0s - loss: 0.0582 - sparse_categorical_accuracy: 0.9940 - val_loss: 0.3971 - val_sparse_categorical_accuracy: 0.8730 - 119ms/epoch - 4ms/step
Epoch 9/10
Epoch 9: saving model to training_1/cp.ckpt
32/32 - 0s - loss: 0.0452 - sparse_categorical_accuracy: 0.9970 - val_loss: 0.4223 - val_sparse_categorical_accuracy: 0.8600 - 133ms/epoch - 4ms/step
Epoch 10/10
Epoch 10: saving model to training_1/cp.ckpt
32/32 - 0s - loss: 0.0348 - sparse_categorical_accuracy: 1.0000 - val_loss: 0.3950 - val_sparse_categorical_accuracy: 0.8740 - 115ms/epoch - 4ms/step
```

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

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

`::dir_tree(checkpoint_dir) fs`

```
training_1
├── checkpoint
├── cp.ckpt.data-00000-of-00001
└── cp.ckpt.index
```

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
<- create_model()
model
# Evaluate the model
<- model %>% evaluate(test_images, test_labels, verbose = 2) untrained_results
```

`32/32 - 0s - loss: 2.3928 - sparse_categorical_accuracy: 0.0840 - 101ms/epoch - 3ms/step`

`cat("Untrained model results: \n")`

`Untrained model results: `

` untrained_results`

```
loss sparse_categorical_accuracy
2.392836 0.084000
```

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

```
# Loads the weights
load_model_weights_tf(model, checkpoint_path)
# Re-evaluate the model
<- model %>% evaluate(test_images, test_labels, verbose = 2) restored_model
```

`32/32 - 0s - loss: 0.3950 - sparse_categorical_accuracy: 0.8740 - 44ms/epoch - 1ms/step`

`cat("Restored model results: \n")`

`Restored model results: `

` restored_model`

```
loss sparse_categorical_accuracy
0.3950371 0.8740000
```

### 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
<- "training_2/cp-list{epoch:04d}.ckpt"
checkpoint_path <- fs::path_dir(checkpoint_path)
checkpoint_dir
<- 32
batch_size
# Create a callback that saves the model's weights every 5 epochs
<- callback_model_checkpoint(
cp_callback filepath = checkpoint_path,
verbose = 1,
save_weights_only = TRUE,
save_freq = 5*batch_size
)
# Create a new model instance
<- create_model()
model
# Train the model with the new callback
%>% fit(
model
train_images,
train_labels,epochs = 50,
batch_size = batch_size,
callbacks = list(cp_callback),
validation_data = list(test_images, test_labels),
verbose = 0
)
```

```
Epoch 5: saving model to training_2/cp-list0005.ckpt
Epoch 10: saving model to training_2/cp-list0010.ckpt
Epoch 15: saving model to training_2/cp-list0015.ckpt
Epoch 20: saving model to training_2/cp-list0020.ckpt
Epoch 25: saving model to training_2/cp-list0025.ckpt
Epoch 30: saving model to training_2/cp-list0030.ckpt
Epoch 35: saving model to training_2/cp-list0035.ckpt
Epoch 40: saving model to training_2/cp-list0040.ckpt
Epoch 45: saving model to training_2/cp-list0045.ckpt
Epoch 50: saving model to training_2/cp-list0050.ckpt
```

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

`::dir_tree(checkpoint_dir) fs`

```
training_2
├── checkpoint
├── cp-list0005.ckpt.data-00000-of-00001
├── cp-list0005.ckpt.index
├── cp-list0010.ckpt.data-00000-of-00001
├── cp-list0010.ckpt.index
├── cp-list0015.ckpt.data-00000-of-00001
├── cp-list0015.ckpt.index
├── cp-list0020.ckpt.data-00000-of-00001
├── cp-list0020.ckpt.index
├── cp-list0025.ckpt.data-00000-of-00001
├── cp-list0025.ckpt.index
├── cp-list0030.ckpt.data-00000-of-00001
├── cp-list0030.ckpt.index
├── cp-list0035.ckpt.data-00000-of-00001
├── cp-list0035.ckpt.index
├── cp-list0040.ckpt.data-00000-of-00001
├── cp-list0040.ckpt.index
├── cp-list0045.ckpt.data-00000-of-00001
├── cp-list0045.ckpt.index
├── cp-list0050.ckpt.data-00000-of-00001
└── cp-list0050.ckpt.index
```

```
<- tf$train$latest_checkpoint(checkpoint_dir)
latest latest
```

`[1] "training_2/cp-list0050.ckpt"`

Note: the default TensorFlow format only saves the 5 most recent checkpoints. To test, reset the model and load the latest checkpoint:

```
# Create a new model instance
<- create_model()
model
# Load the previously saved weights
load_model_weights_tf(model, latest)
# Re-evaluate the model
%>% evaluate(test_images, test_labels, verbose = 0) model
```

```
loss sparse_categorical_accuracy
0.4798704 0.8770000
```

## 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 `save_model_weights_tf()`

. By default, Keras —and the `save_model_weights_tf()`

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 weights
save_model_weights_tf(model, './checkpoints/my_checkpoint')
# Create a new model instance
<- create_model()
model
# Restore the weights
load_model_weights_tf(model, './checkpoints/my_checkpoint')
# Evaluate the model
<- model %>% evaluate(test_images, test_labels, verbose = 2) restored_model
```

`32/32 - 0s - loss: 0.4799 - sparse_categorical_accuracy: 0.8770 - 101ms/epoch - 3ms/step`

`cat("Restored model results: \n")`

`Restored model results: `

` restored_model`

```
loss sparse_categorical_accuracy
0.4798704 0.8770000
```

## Save the entire model

Call `save_model_tf()`

to save 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.

An entire model can be saved in two different file formats (`SavedModel`

and `HDF5`

). The TensorFlow `SavedModel`

format is the default file format in TF2$x. However, models can be saved in `HDF5`

format. More details on saving entire models in the two file formats is described below.

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 (e.g. subclassed models or layers) require special attention when saving and loading. See the **Saving custom objects** section below

### SavedModel format

The SavedModel format is another way to serialize models. Models saved in this format can be restored using `load_model_tf()`

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.

```
# Create and train a new model instance.
<- create_model()
model %>% fit(train_images, train_labels, epochs = 5) model
```

```
Epoch 1/5
32/32 - 1s - loss: 1.1850 - sparse_categorical_accuracy: 0.6650 - 548ms/epoch - 17ms/step
Epoch 2/5
32/32 - 0s - loss: 0.4377 - sparse_categorical_accuracy: 0.8740 - 50ms/epoch - 2ms/step
Epoch 3/5
32/32 - 0s - loss: 0.2893 - sparse_categorical_accuracy: 0.9290 - 49ms/epoch - 2ms/step
Epoch 4/5
32/32 - 0s - loss: 0.2108 - sparse_categorical_accuracy: 0.9470 - 47ms/epoch - 1ms/step
Epoch 5/5
32/32 - 0s - loss: 0.1558 - sparse_categorical_accuracy: 0.9650 - 45ms/epoch - 1ms/step
```

```
# Save the entire model as a SavedModel.
save_model_tf(model, "saved_model/my_model")
```

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

```
# my_model directory
# Contains an assets folder, saved_model.pb, and variables folder.
::dir_tree("saved_model/") fs
```

```
saved_model/
└── my_model
├── assets
├── fingerprint.pb
├── keras_metadata.pb
├── saved_model.pb
└── variables
├── variables.data-00000-of-00001
└── variables.index
```

Reload a fresh Keras model from the saved model:

```
<- load_model_tf('saved_model/my_model')
new_model
# Check its architecture
summary(new_model)
```

```
Model: "sequential_5"
____________________________________________________________________________
Layer (type) Output Shape Param #
============================================================================
dense_11 (Dense) (None, 512) 401920
dropout_5 (Dropout) (None, 512) 0
dense_10 (Dense) (None, 10) 5130
============================================================================
Total params: 407050 (1.55 MB)
Trainable params: 407050 (1.55 MB)
Non-trainable params: 0 (0.00 Byte)
____________________________________________________________________________
```

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
<- new_model %>% evaluate(test_images, test_labels, verbose = 2) restored_model
```

`32/32 - 0s - loss: 0.4517 - sparse_categorical_accuracy: 0.8480 - 103ms/epoch - 3ms/step`

` restored_model`

```
loss sparse_categorical_accuracy
0.4517023 0.8480000
```

`dim(predict(new_model, test_images))`

`32/32 - 0s - 66ms/epoch - 2ms/step`

`[1] 1000 10`

### HDF5 format

Keras provides a basic save format using the HDF5 standard.

```
# Create and train a new model instance.
<- create_model()
model %>% fit(train_images, train_labels, epochs = 5) model
```

```
Epoch 1/5
32/32 - 1s - loss: 1.1538 - sparse_categorical_accuracy: 0.6690 - 554ms/epoch - 17ms/step
Epoch 2/5
32/32 - 0s - loss: 0.4328 - sparse_categorical_accuracy: 0.8790 - 51ms/epoch - 2ms/step
Epoch 3/5
32/32 - 0s - loss: 0.2858 - sparse_categorical_accuracy: 0.9250 - 52ms/epoch - 2ms/step
Epoch 4/5
32/32 - 0s - loss: 0.2079 - sparse_categorical_accuracy: 0.9490 - 50ms/epoch - 2ms/step
Epoch 5/5
32/32 - 0s - loss: 0.1482 - sparse_categorical_accuracy: 0.9730 - 48ms/epoch - 2ms/step
```

```
# Save the entire model to a HDF5 file.
# The '.h5' extension indicates that the model should be saved to HDF5.
save_model_hdf5(model, 'my_model.h5')
```

Now, recreate the model from that file:

```
# Recreate the exact same model, including its weights and the optimizer
<- load_model_hdf5('my_model.h5')
new_model
# Show the model architecture
summary(new_model)
```

```
Model: "sequential_6"
____________________________________________________________________________
Layer (type) Output Shape Param #
============================================================================
dense_13 (Dense) (None, 512) 401920
dropout_6 (Dropout) (None, 512) 0
dense_12 (Dense) (None, 10) 5130
============================================================================
Total params: 407050 (1.55 MB)
Trainable params: 407050 (1.55 MB)
Non-trainable params: 0 (0.00 Byte)
____________________________________________________________________________
```

Check its accuracy:

`%>% evaluate(test_images, test_labels, verbose = 0) new_model `

```
loss sparse_categorical_accuracy
0.4328409 0.8590000
```

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 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 original code.

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

- 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 do.call(cls, config)`

).

- 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. Eg.`load_model_tf(path, custom_objects = list('CustomLayer'= CustomLayer))`

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

.