How to save a trained model in Keras to use it in an application?

£可爱£侵袭症+ 提交于 2019-12-13 17:03:44

问题


I have trained a model in Keras, and saved it in different ways like;

model.save("filename")

or

model.to_json()  
model.save_weights("filename")

But when I load the trained model in another program to make predictions, I get very different results from the test results.

Why does that happens and how can I handle that?


回答1:


save it like:

     model.save('model.h5')
     model_json = model.to_json()
     with open("model.json", "w") as json_file:
         json_file.write(model_json)

Then for loading it into application efficiently, make it a global like following so that it doesn't load again and again:

    def load_model():

        global model

        json_file = open('model.json', 'r')
        model_json = json_file.read()
        model = model_from_json(model_json)
        model.load_weights("model.h5")
        model._make_predict_function()



回答2:


You can try saving the model in .h5 format

from keras.models import model_from_json   
# serialize model to JSON
model_json = parallel_model.to_json()
with open("model.json", "w") as json_file:
    json_file.write(model_json)
# serialize weights to HDF5
model.save_weights("model.h5")
print("Saved model to disk")


来源:https://stackoverflow.com/questions/51628450/how-to-save-a-trained-model-in-keras-to-use-it-in-an-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!