keras model saving and loading

It sometimes takes a while to run a ML model, and so when we need to do other things, we should save the model so we can reuse it at another point.

This is how to....

There are 2 ways

  • json
  • h5py

Complete Model

from keras.models import load_model

model.save('my_model.h5')  # creates a HDF5 file 'my_model.h5'
del model  # deletes the existing model

# returns a compiled model
# identical to the previous one
model = load_model('my_model.h5')

Model's Archectuecture

Json

I am going to assume we have generated the model, run the iterations and now are happy with the result..... So we now can call

Saving

 serialize model to JSON
model_json = model.to_json()
with open("model.json", "w") as json_file:
    json_file.write(model_json)

Loading

# 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)

Post Load

When we have reloaded the model - we then have to compile it again (Json or h5.py).

# evaluate loaded model on test data
loaded_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
score = loaded_model.evaluate(X, Y, verbose=0)
print("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100))

hdf5

Frankly very similar to JSON.

Saving

# serialize weights to HDF5
model.save_weights("model.h5")
print("Saved model to disk")

Loading

loaded_model = model_from_json(loaded_model_json)
# load weights into new model
loaded_model.load_weights("model.h5")
print("Loaded model from disk")

And then

compiling
# evaluate loaded model on test data
loaded_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
score = loaded_model.evaluate(X, Y, verbose=0)
print("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100))