There's more...

Training a deep learning model is a time-consuming task. If training stops unexpectedly, we can lose a lot of our work. The keras library in R provides us with the functionality to save a model's progress during and after training. A saved model contains the weight values, the model's configuration, and the optimizer's configuration. If the training process is interrupted somehow, we can pick up training from there.

The following code block shows how we can save the model after training:

# Save model
model_sequential %>% save_model_hdf5("my_model.h5")

If we want to save the model after each iteration while training, we need to create a checkpoint object. To perform this task, we use the callback_model_checkpoint() function. The value of the filepath argument defines the name of the model that we want to save at the end of each iteration. For example, if filepath is {epoch:02d}-{val_loss:.2f}.hdf5, the model will be saved with the epoch number and the validation loss in the filename.

The following code block demonstrates how to save a model after each epoch:

checkpoint_dir <- "checkpoints"
dir.create(checkpoint_dir, showWarnings = FALSE)
filepath <- file.path(checkpoint_dir, "{epoch:02d}.hdf5")

# Create checkpoint callback
cp_callback <- callback_model_checkpoint(
filepath = filepath,
verbose = 1
)

# Fit model and save model after each check point
model_sequential %>% fit(
x_data,
y_data,
epochs = 30,
batch_size = 128,
validation_split = 0.2,
callbacks = list(cp_callback)
)

By doing this, you've learned how to save models with the appropriate checkpoints and callbacks.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset