Keras – 10. Save&Reload Your Model&Weights

Welcome to CS With James

In this tutorial I will explain how to save and reload your model using your disk.

First of all we have to install a python package by

pip3 install h5py
or
pip install h5py for python2 users

In order to save some time on training I will use the MNIST dataset with the Dense layers only.

Save the trained model and weights to the disk

Here is the Code

You should be able to understand everything except the last cell

# Convert model into JSON Format
model_json = model.to_json()
with open("model.json", "w") as json_file:
    json_file.write(model_json)
    
# Save the trained weights in to .h5 format
model.save_weights("model.h5")
print("Saved model to disk")

This cell will convert the model into JSON Format and write (save) into your disk (working directory) and you can save the trained weight into .h5 format.

This will allow you to save the model architecture and its weight and you can reload this and use it for inference.

Reload the saved model and weight from the disk

Here is the Code

In this section you have to import a new API by

from keras.models import model_from_json

this will allow you to load the model from JSON format and convert it into a Keras model.

after load the MNIST dataset

json_file = open('model.json', 'r')
model = model_from_json(json_file.read())
json_file.close()

model.load_weights("model.h5")

This will allow you to reload the saved model and weight

before evaluate or predict you have to compile the model. Now this should be very easy for you. 

Once you evaluate the model with the test dataset you can see the same result from previous trained model. 

Conclusion

This not just works for the MNIST dataset or you can save the DenseNet or any other custom designed model and weight into your disk and reload it into your memory anytime you need it. 

While you are training you can save the weights every 100 epochs, so even there were some power outage you don’t have to start all over again. Saving the model and the weights are essential for you to deploy the model into production.

 

Leave a Reply

Your email address will not be published. Required fields are marked *