Product

Wednesday, 21 February 2024

How to Save and Load Your Keras Deep Learning Model

 


Keras is a simple and powerful Python library for deep learning.

Since deep learning models can take hours, days, and even weeks to train, it is important to know how to save and load them from a disk.

In this post, you will discover how to save your Keras models to files and load them up again to make predictions.

After reading this tutorial, you will know:

  • How to save model weights and model architecture in separate files
  • How to save model architecture in both YAML and JSON format
  • How to save model weights and architecture into a single file for later use

Tutorial Overview

If you are new to Keras or deep learning, see this step-by-step Keras tutorial.

Keras separates the concerns of saving your model architecture and saving your model weights.

Model weights are saved to an HDF5 format. This grid format is ideal for storing multi-dimensional arrays of numbers.

The model structure can be described and saved using two different formats: JSON and YAML.

In this post, you will look at three examples of saving and loading your model to a file:

  • Save Model to JSON
  • Save Model to YAML
  • Save Model to HDF5

The first two examples save the model architecture and weights separately. The model weights are saved into an HDF5 format file in all cases.

The examples will use the same simple network trained on the Pima Indians onset of diabetes binary classification dataset. This is a small dataset that contains all numerical data and is easy to work with. You can download this dataset and place it in your working directory with the filename “pima-indians-diabetes.csv” (update: download from here).

Confirm that you have TensorFlow v2.x installed (e.g., v2.9 as of June 2022).

Note: Saving models requires that you have the h5py library installed. It is usually installed as a dependency with TensorFlow. You can also install it easily as follows:

Save Your Neural Network Model to JSON

JSON is a simple file format for describing data hierarchically.

Keras provides the ability to describe any model using JSON format with a to_json() function. This can be saved to a file and later loaded via the model_from_json() function that will create a new model from the JSON specification.

The weights are saved directly from the model using the save_weights() function and later loaded using the symmetrical load_weights() function.

The example below trains and evaluates a simple model on the Pima Indians dataset. The model is then converted to JSON format and written to model.json in the local directory. The network weights are written to model.h5 in the local directory.

The model and weight data is loaded from the saved files, and a new model is created. It is important to compile the loaded model before it is used. This is so that predictions made using the model can use the appropriate efficient computation from the Keras backend.

The model is evaluated in the same way, printing the same evaluation score.

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 output below.

The JSON format of the model looks like the following:

Save Your Neural Network Model to YAML

Note: This method only applies to TensorFlow 2.5 or earlier. If you run it in later versions of TensorFlow, you will see a RuntimeError with the message “Method model.to_yaml() has been removed due to security risk of arbitrary code execution. Please use model.to_json() instead.”

This example is much the same as the above JSON example, except the YAML format is used for the model specification.

Note, this example assumes that you have PyYAML 5 installed:

In this example, the model is described using YAML, saved to file model.yaml, and later loaded into a new model via the model_from_yaml() function.

Weights are handled the same way as above in the HDF5 format as model.h5.

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 displays the following output.

The model described in YAML format looks like the following:

Save Model Weights and Architecture Together

Keras also supports a simpler interface to save both the model weights and model architecture together into a single H5 file.

Saving the model in this way includes everything you need to know about the model, including:

  • Model weights
  • Model architecture
  • Model compilation details (loss and metrics)
  • Model optimizer state

This means that you can load and use the model directly without having to re-compile it as you had to in the examples above.

Note: This is the preferred way for saving and loading your Keras model.

How to Save a Keras Model

You can save your model by calling the save() function on the model and specifying the filename.

The example below demonstrates this by first fitting a model, evaluating it, and saving it to the file model.h5.

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 fits the model, summarizes the model’s performance on the training dataset, and saves the model to file.

You can later load this model from the file and use it.

Note that in the Keras library, there is another function doing the same, as follows:

How to Load a Keras Model

Your saved model can then be loaded later by calling the load_model() function and passing the filename. The function returns the model with the same architecture and weights.

In this case, you load the model, summarize the architecture, and evaluate it on the same dataset to confirm the weights and architecture are the same.

Running the example first loads the model, prints a summary of the model architecture, and then evaluates the loaded model on the same 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.

The model achieves the same accuracy score, which in this case is 77%.

Protocol Buffer Format

While saving and loading a Keras model using HDF5 format is the recommended way, TensorFlow supports yet another format, the protocol buffer. It is considered faster to save and load a protocol buffer format, but doing so will produce multiple files. The syntax is the same, except that you do not need to provide the .h5 extension to the filename:

These will create a directory “model” with the following files:

This is also the format used to save a model in TensorFlow v1.x. You may encounter this when you download a pre-trained model from TensorFlow Hub.

Further Reading

Summary

In this post, you discovered how to serialize your Keras deep learning models.

You learned how to save your trained models to files, later load them up, and use them to make predictions.

You also learned that model weights are easily stored using  HDF5 format and that the network structure can be saved in either JSON or YAML format.

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

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