简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM