2

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?

petezurich
  • 9,280
  • 9
  • 43
  • 57
Atilla
  • 33
  • 2
  • 9
  • Oh, I have solve it by saving the model as '.yaml' file instead '.json'. Then, load the weights and compile it. – Atilla Aug 01 '18 at 08:40

3 Answers3

3

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()
Upasana Mittal
  • 2,480
  • 1
  • 14
  • 19
0

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")
0

also, You can do this way

Save model

 model.save('clasification_model.h5')

Read Model

from keras.models import load_model
classifier = load_model('clasification_model.h5')

Prediction

res = classifier.predict_classes(x, batch_size=32, verbose=1)

classifier.predict_classes vs classifier.predict

keras Sequential model API

Dulanga Heshan
  • 1,335
  • 1
  • 19
  • 36