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_json
function from the Keras library. -
json_file = open('model.json', 'r')
: This opens themodel.json
file in read mode. -
loaded_model_json = json_file.read()
: This reads the contents of themodel.json
file. -
json_file.close()
: This closes themodel.json
file. -
loaded_model = model_from_json(loaded_model_json)
: This creates a model from themodel.json
file. -
loaded_model.load_weights("model.h5")
: This loads the weights from themodel.h5
file into the model. -
print("Loaded model from disk")
: This prints the messageLoaded model from disk
when the model is successfully loaded.
Helpful links
More of Python Keras
- How can I improve the validation accuracy of my Keras model using Python?
- How do I use validation_data when creating a Keras model in Python?
- How do I check which version of Keras I am using in Python?
- How can I visualize a Keras model using Python?
- How do Python Keras and TensorFlow compare in developing machine learning models?
- How do I use Python's tf.keras.utils.get_file to retrieve a file?
- 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 Python Keras to develop a reinforcement learning model?
- How do I use Python Keras to zip a file?
- How do I save a Keras model in Python?
See more codes...