问题
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