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

后端 未结 5 852
小鲜肉
小鲜肉 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-13 19:49

    The accepted answer is too complicated. You can fully save and restore every aspect of your model in a .h5 file. Straight from the Keras FAQ:

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

    And the corresponding code:

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

提交回复
热议问题