How to save Scikit-Learn-Keras Model into a Persistence File (pickle/hd5/json/yaml)

后端 未结 5 854
小鲜肉
小鲜肉 2020-12-13 19:23

I have the following code, using Keras Scikit-Learn Wrapper:

from keras.models import Sequential
from sklearn import datasets
from keras.layers import Dense
         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-13 19:47

    Another great alternative is to use callbacks when you fit your model. Specifically the ModelCheckpoint callback, like this:

    from keras.callbacks import ModelCheckpoint
    #Create instance of ModelCheckpoint
    chk = ModelCheckpoint("myModel.h5", monitor='val_loss', save_best_only=False)
    #add that callback to the list of callbacks to pass
    callbacks_list = [chk]
    #create your model
    model_tt = KerasClassifier(build_fn=create_model, nb_epoch=150, batch_size=10)
    #fit your model with your data. Pass the callback(s) here
    model_tt.fit(X_train,y_train, callbacks=callbacks_list)
    

    This will save your training each epoch to the myModel.h5 file. This provides great benefits, as you are able to stop your training when you desire (like when you see it has started to overfit), and still retain the previous training.

    Note that this saves both the structure and weights in the same hdf5 file (as showed by Zach), so you can then load you model using keras.models.load_model.

    If you want to save only your weights separately, you can then use the save_weights_only=True argument when instantiating your ModelCheckpoint, enabling you to load your model as explained by Gaarv. Extracting from the docs:

    save_weights_only: if True, then only the model's weights will be saved (model.save_weights(filepath)), else the full model is saved (model.save(filepath)).

提交回复
热议问题