Keras is a simple and powerful Python library for deep learning and machine learning algorithms.
A Keras model consists of multiple components:
Many deep learning models are complex and may take days to train and test the data. Therefore, it is important to understand how to save and load data for later use.
There are three ways in which the model can be saved:
Saving everything into a single file, usually it is in the
Saving the architecture as only a JSON or YAML file.
Saving the weight values only. This is generally used when training the model so that they may be used again. These weights can be used in a similar representation of a different model.
In order to save the model, a user can use the save()
function specified in the Keras library. A user will specify the name and location of the file with .h5
extension. If you do not specify the path it will, by default, save it in the folder where the model is executed. Look at the syntax below:
model.save("myModel.h5")
The function save()
saves the following features:
In order to load the model, a user can use the load_model()
function specified in the keras.models
library. The user will first have to import this function from the relevant library in order to use it. The user will specify the name and location of the file with an .h5
extension. Take a look at the syntax below:
from keras.models import load_model
model_new = load_model("myModel.h5")
The architecture is saved as a JSON file or a YAML file. Look at the syntax below:
As a JSON:
from keras.models import model_from_json
save_model_json = model.to_json()
with open("myModel.json", "w") as json_file:
json_file.write(save_model_json )
As a YAML:
from keras.models import model_from_yaml
model_yaml = model.to_yaml()
with open("myModel.yaml", "w") as yaml_file:
yaml_file.write(model_yaml)
As a JSON:
json_file = open('myModel.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
new_model = model_from_json(loaded_model_json)
As a YAML:
yaml_file = open('myModel.yaml', 'r')
loaded_model_yaml = yaml_file.read()
yaml_file.close()
new_model = model_from_yaml(loaded_model_yaml)
model.save_weights("myModel.h5")
new_model.load_weights("myModel.h5")
Free Resources