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 can I improve the validation accuracy of my Keras model using Python?
- How do I use zero padding in Python Keras?
- How can I use word2vec and Keras to develop a machine learning model in Python?
- How do I check which version of Keras I am using in Python?
- How do I use Python Keras to zip a file?
- How do I use validation_data when creating a Keras model in Python?
- How can I use XGBoost, Python and Keras together to build a machine learning model?
- How can I install the python module tensorflow.keras in R?
- How do I use Python and Keras to create a VGG16 model?
- How can I use the to_categorical attribute in the tensorflow.python.keras.utils module?
See more codes...