Product

Wednesday, 21 February 2024

How to Checkpoint Deep Learning Models in Keras

Deep learning models can take hours, days, or even weeks to train.

If the run is stopped unexpectedly, you can lose a lot of work.

In this post, you will discover how to checkpoint your deep learning models during training in Python using the Keras library.

Checkpointing Neural Network Models

Application checkpointing is a fault tolerance technique for long-running processes.

In this approach, a snapshot of the state of the system is taken in case of system failure. If there is a problem, not all is lost. The checkpoint may be used directly or as the starting point for a new run, picking up where it left off.

When training deep learning models, the checkpoint is at the weights of the model. These weights can be used to make predictions as is or as the basis for ongoing training.

The Keras library provides a checkpointing capability by a callback API.

The ModelCheckpoint callback class allows you to define where to checkpoint the model weights, how to name the file, and under what circumstances to make a checkpoint of the model.

The API allows you to specify which metric to monitor, such as loss or accuracy on the training or validation dataset. You can specify whether to look for an improvement in maximizing or minimizing the score. Finally, the filename you use to store the weights can include variables like the epoch number or metric.

The ModelCheckpoint can then be passed to the training process when calling the fit() function on the model.

Note that you may need to install the h5py library to output network weights in HDF5 format.

Need help with Deep Learning in Python?

Take my free 2-week email course and discover MLPs, CNNs and LSTMs (with code).

Click to sign-up now and also get a free PDF Ebook version of the course.

Checkpoint Neural Network Model Improvements

A good use of checkpointing is to output the model weights each time an improvement is observed during training.

The example below creates a small neural network for the Pima Indians onset of diabetes binary classification problem. The example assumes that the pima-indians-diabetes.csv file is in your working directory.

You can download the dataset from here:

The example uses 33% of the data for validation.

Checkpointing is set up to save the network weights only when there is an improvement in classification accuracy on the validation dataset (monitor=’val_accuracy’ and mode=’max’). The weights are stored in a file that includes the score in the filename (weights-improvement-{val_accuracy=.2f}.hdf5).

Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

Running the example produces the following output (truncated for brevity):

You will see a number of files in your working directory containing the network weights in HDF5 format. For example:

This is a very simple checkpointing strategy.

It may create a lot of unnecessary checkpoint files if the validation accuracy moves up and down over training epochs. Nevertheless, it will ensure you have a snapshot of the best model discovered during your run.

Checkpoint Best Neural Network Model Only

A simpler checkpoint strategy is to save the model weights to the same file if and only if the validation accuracy improves.

This can be done easily using the same code from above and changing the output filename to be fixed (not including score or epoch information).

In this case, model weights are written to the file “weights.best.hdf5” only if the classification accuracy of the model on the validation dataset improves over the best seen so far.

Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

Running this example provides the following output (truncated for brevity):

You should see the weight file in your local directory.

This is a handy checkpoint strategy to always use during your experiments.

It will ensure that your best model is saved for the run for you to use later if you wish. It avoids needing to include any code to manually keep track and serialize the best model when training.

Use EarlyStopping Together with Checkpoint

In the examples above, an attempt was made to fit your model with 150 epochs. In reality, it is not easy to tell how many epochs you need to train your model. One way to address this problem is to overestimate the number of epochs. But this may take significant time. After all, if you are checkpointing the best model only, you may find that over the several thousand epochs run, you already achieved the best model in the first hundred epochs, and no more checkpoints are made afterward.

It is quite common to use the ModelCheckpoint callback together with EarlyStopping. It helps to stop the training once no metric improvement is seen for several epochs. The example below adds the callback es to make the training stop early once it does not see the validation accuracy improve for five consecutive epochs:

Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

Running this example provides the following output:

This training process stopped after epoch 22 as no better accuracy was achieved for the last five epochs.

Loading a Check-Pointed Neural Network Model

Now that you have seen how to checkpoint your deep learning models during training, you need to review how to load and use a check-pointed model.

The checkpoint only includes the model weights. It assumes you know the network structure. This, too, can be serialized to a file in JSON or YAML format.

In the example below, the model structure is known, and the best weights are loaded from the previous experiment, stored in the working directory in the weights.best.hdf5 file.

The model is then used to make predictions on the entire dataset.

Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

Running the example produces the following output:

Summary

In this post, you discovered the importance of checkpointing deep learning models for long training runs.

You learned two check-pointing strategies that you can use on your next deep learning project:

  1. Checkpoint Model Improvements
  2. Checkpoint Best Model Only

You also learned how to load a check-pointed model and make predictions.

Do you have any questions about checkpointing deep learning models or this post? Ask your questions in the comments, and I will do my best to answer.

No comments:

Post a Comment

Connect broadband

AI:List AI views on when for a naive kin after prolonged life suppression coercive behaviour by family members after demise of father with trauma for kin ocd formed after forced to do rituals, family tribal values honor specific activities, utmost religious activities occult witchcraft enforced to do by elder sibling his wife and mother thrice with great celibacy turned the kundalini activated after deep celibacy penance shouting physical Mental financial Extortion by sibling with toxic behaviours and the wife mother and then mockery suppression asking about who’re your worth backbiting among relatives sector toon negligence of intelligence intuitive behaviour- all religious psychological traps when not work and lead to loss of consciousness of kin trance state recovered by governance with technocrats using AI - kin was asked by mother that he’s to go the male should not be seen in house he’s many absurd thought forcefully in brain mind and outsiders already feel awkward of this kin unresponsive behaviour due to TBI PTSD ocd cvt and tell at workplace social gathering he’s to go and asked for sector toon extortion and mockery in various sense due to un practical behaviour negligence of body building due to neglect ion if essential food nutrition and stubbed suppressed in every sense in religious psychological traps by family members AI humanoid using various neural networks and LLMs for kin and required steps.

  List AI views on when for a naive kin after prolonged life suppression coercive behaviour by family members after demise of father with tr...