Google News
logo
Keras - Interview Questions
How do you save and load models in Keras?
Keras provides straightforward methods to save and load trained models.

Save and Load Model with Keras :

You can save or load two types of Keras models :

* Architecture-Only Models : Saved as JSON or YAML files. These files contain the model's architecture but not its weights or training configuration.
* Stateful Models : Saved as Hierarchical Data Format (HDF5) files. They store the model's architecture, weights, and training configuration. This is the preferred way for saving trained models.

Here is the Keras code that demonstrates how to do that:

Code: Save and Load Models in Keras :

Here is the Python code :
from keras.models import model_from_json

# Save model in JSON format (architecture-only)
model_json = model.to_json()
with open("model.json", "w") as json_file:
    json_file.write(model_json)

# Load model from JSON
json_file = open('model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)

# Save model in HDF5 format (stateful model)
model.save("model.h5")

# Load model from HDF5
loaded_model_h5 = load_model('model.h5')?

Additional Considerations :

* Historical Data :
The HDF5 format does not save the training metrics. This means that the loaded model will not include the training and validation histories. If you need those, you'll have to save them separately.

* Custom Objects : If your model uses custom layers or other custom objects, you need to pass them to the loading mechanism using the custom_objects parameter. This is particularly crucial when loading pre-trained models.
Advertisement