How to save final model using keras?

前端 未结 6 653
一整个雨季
一整个雨季 2020-11-28 07:01

I use KerasClassifier to train the classifier.

The code is below:

import numpy
from pandas import read_csv
from keras.models import Sequential
from k         


        
6条回答
  •  迷失自我
    2020-11-28 07:51

    you can save the model in json and weights in a hdf5 file format.

    # keras library import  for Saving and loading model and weights
    
    from keras.models import model_from_json
    from keras.models import load_model
    
    # serialize model to JSON
    #  the keras model which is trained is defined as 'model' in this example
    model_json = model.to_json()
    
    
    with open("model_num.json", "w") as json_file:
        json_file.write(model_json)
    
    # serialize weights to HDF5
    model.save_weights("model_num.h5")
    

    files "model_num.h5" and "model_num.json" are created which contain our model and weights

    To use the same trained model for further testing you can simply load the hdf5 file and use it for the prediction of different data. here's how to load the model from saved files.

    # load json and create model
    json_file = open('model_num.json', 'r')
    
    loaded_model_json = json_file.read()
    json_file.close()
    loaded_model = model_from_json(loaded_model_json)
    
    # load weights into new model
    loaded_model.load_weights("model_num.h5")
    print("Loaded model from disk")
    
    loaded_model.save('model_num.hdf5')
    loaded_model=load_model('model_num.hdf5')
    

    To predict for different data you can use this

    loaded_model.predict_classes("your_test_data here")
    

提交回复
热议问题