Keras - Saving Models
Updated at 2017-08-04 21:01
To use your trained neural network model later, you need to save two things:
- Model layout; usually in JSON or YAML format.
- Model weights; usually in HDF5 format.
model_json = model.to_json()
with open('./model.json', 'w') as json_file:
json_file.write(model_json)
model.save_weights('./model.h5')
You can later load the model with model_from_json
.
from keras.models import model_from_json
with open('./model.json', 'r') as json_file:
loaded_model_json = json_file.read()
loaded_model = model_from_json(loaded_model_json)
loaded_model.load_weights('./model.h5')
# Model is ready for use after it's compiled.
loaded_model.compile(loss='binary_crossentropy', optimizer='rmsprop')
You can also load partial weights with by_name
.
model1 = Sequential()
model1.add(Dense(2, input_dim=3, name="dense_1"))
model1.add(Dense(3, name="dense_2"))
model.save_weights('./weights.h5')
model2 = Sequential()
model2.add(Dense(2, input_dim=3, name="dense_1"))
model2.add(Dense(10, name="new_dense"))
model2.load_weights('./weights.h5', by_name=True)
You can use ModelCheckpoint
to save model from a specific epoch. This can be advantageous if val_acc
is very spiky.
keras.callbacks.ModelCheckpoint(
filepath,
monitor='val_loss',
verbose=0,
save_best_only=True,
save_weights_only=False,
mode='auto',
period=1
)