python-kerasHow to load a model in Python Keras?
Loading a model in Python Keras is a simple process. The following example code block loads a model from a JSON file:
from keras.models import model_from_json
# load json and create model
json_file = open('model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
# load weights into new model
loaded_model.load_weights("model.h5")
print("Loaded model from disk")
The output of this code block will be: Loaded model from disk
Code explanation
-
from keras.models import model_from_json: This imports themodel_from_jsonfunction from the Keras library. -
json_file = open('model.json', 'r'): This opens themodel.jsonfile in read mode. -
loaded_model_json = json_file.read(): This reads the contents of themodel.jsonfile. -
json_file.close(): This closes themodel.jsonfile. -
loaded_model = model_from_json(loaded_model_json): This creates a model from themodel.jsonfile. -
loaded_model.load_weights("model.h5"): This loads the weights from themodel.h5file into the model. -
print("Loaded model from disk"): This prints the messageLoaded model from diskwhen the model is successfully loaded.
Helpful links
More of Python Keras
- How do I use zero padding in Python Keras?
- How do I set the input shape when using Keras with Python?
- How can I use Python and Keras to create a Variational Autoencoder (VAE)?
- How do I build a neural network using Python and Keras?
- How do I use the to_categorical function from TensorFlow in Python to convert data into a format suitable for a neural network?
- How can I use a GPU with Python and Keras to run an example?
- How do I use a GPU with Keras in Python?
- How can I use Python and Keras to perform image classification?
- How do I create a sequential model using Python and Keras?
- How do I use the Python Keras package to develop a deep learning model?
See more codes...