Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keras, best way to save state when optimizing

Tags:

python

keras

I was just wondering what is the best way to save the state of a model while it it optimizing. I want to do this so I can run it for a while, save it, and come back to it some time later. I know there is a function to save the weights and another function to save the model as JSON. During learning I would need to save both the weights and the parameters of the model. This includes parameters like the momentum and learning rate. Is there a way to save both the model and weights in the same file. I read that it is not considered good practice to use pickle. Also would the momentums for the graident decent be included with the models JSON or in the weights?

like image 980
chasep255 Avatar asked May 10 '16 03:05

chasep255


People also ask

How do you save the best model in keras?

We can use the Keras callback keras. callbacks. ModelCheckpoint() to save the model at its best performing epoch.

How do you save model weights in keras?

The weights are saved directly from the model using the save_weights() function and later loaded using the symmetrical load_weights() function.

What is Optimizer state?

Optimizer state sharding is a useful memory-saving technique that shards the optimizer state (the set of weights that describes the state of optimizer) across data parallel device groups.

What is H5 file in keras?

H5 is a file format to store structured data, it's not a model by itself. Keras saves models in this format as it can easily store the weights and model configuration in a single file.


1 Answers

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

You can use model.save(filepath) to save a Keras model into a single HDF5 file which will contain:

  • the architecture of the model, allowing to re-create the model
  • the weights of the model
  • the training configuration (loss, optimizer)
  • the state of the optimizer, allowing to resume training exactly where you left off.

You can then use keras.models.load_model(filepath) to reinstantiate your model. load_model will also take care of compiling the model using the saved training configuration (unless the model was never compiled in the first place).

Keras FAQ: How can I save a Keras model?

like image 121
Matt Kleinsmith Avatar answered Sep 20 '22 11:09

Matt Kleinsmith