Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving the best weights and model in Keras

I'm using Keras API with Tensorflow back-end to train the DL model. I'm using ModelCheckPoint to monitor the validation accuracy and store only the weights if there is an improvement. In the process, I end up storing the model architecture as JSON and the weights for every improvement. I finally load the best weights and the model architecture to predict on the test data. Here is my code:

    filepath="weights-improvement-{epoch:02d}-{val_acc:.2f}.hdf5"
    checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')
    callbacks_list = [checkpoint]
    history = model.fit_generator(train_generator,steps_per_epoch=nb_train_samples // batch_size, epochs=epochs, validation_data=validation_generator, callbacks=callbacks_list, validation_steps=nb_validation_samples // batch_size, verbose=1)
    model_json = model.to_json()
    with open("model.json", "w") as json_file:
        json_file.write(model_json)
    model.save('model_complete.h5')

I also attempted to save the entire model with "model.save" however, this saved model stores not the best weights but the weights learned at the final epoch which definitely is not the best weights learned in my case. Is there a way to store the architecture and the best weights into a single model file?

like image 987
shiva Avatar asked Sep 16 '25 10:09

shiva


1 Answers

That is already the default behaviour of ModelCheckpoint as save_weights_only=False. If you look at the source you'll see it already calls model.save if you do not specify for it to save the weights only.

like image 60
nuric Avatar answered Sep 19 '25 08:09

nuric