Error in load a model saved by callbakcs.ModelCheckpoint() in Keras












1















I saved my model automatically by callbacks.ModelCheckpoint() with a HDF5 file.



# Checkpoint In the /output folder
filepath = "./model/mnist-cnn-best.hd5"

# Keep only a single checkpoint, the best over test accuracy.
checkpoint = keras.callbacks.ModelCheckpoint(filepath, monitor='val_acc',
verbose=1, save_best_only=True,
mode='max')

# Train
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test),
callbacks=[checkpoint])


When I load a model, an error occured.



  model = keras.models.load_model("./mnist-cnn-best.hd5")

File "D:Program FilesAnaconda3libsite-packagestensorflowpythonkerasenginesaving.py", line 251, in load_model
training_config['weighted_metrics'])
KeyError: 'weighted_metrics'


If I load model with param 'compile=False', it works correctly.



I know the normal way to save model in keras is:



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


By the way, this error also happened when me convert this model by Tensorflow Lite.
But I don't know what's wrong with my model.
Does anyone has an idea?










share|improve this question

























  • The function load_model() can load model saved by func save_model(). In class callbacks, model saved by model.save(). What's the difference between these ways? How can I load a model saved by the second way?

    – Jonathan.H
    Oct 11 '18 at 7:08













  • Are you using the same Keras versions to save and load the model?

    – Matias Valdenegro
    Oct 11 '18 at 8:38











  • @MatiasValdenegro I'm using same version:2.2.2 both in Windows 10 and Ubuntu 16.04 platform, this problem occured in Windows 10, works fine in Ubuntu 16.04.

    – Jonathan.H
    Oct 12 '18 at 1:34
















1















I saved my model automatically by callbacks.ModelCheckpoint() with a HDF5 file.



# Checkpoint In the /output folder
filepath = "./model/mnist-cnn-best.hd5"

# Keep only a single checkpoint, the best over test accuracy.
checkpoint = keras.callbacks.ModelCheckpoint(filepath, monitor='val_acc',
verbose=1, save_best_only=True,
mode='max')

# Train
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test),
callbacks=[checkpoint])


When I load a model, an error occured.



  model = keras.models.load_model("./mnist-cnn-best.hd5")

File "D:Program FilesAnaconda3libsite-packagestensorflowpythonkerasenginesaving.py", line 251, in load_model
training_config['weighted_metrics'])
KeyError: 'weighted_metrics'


If I load model with param 'compile=False', it works correctly.



I know the normal way to save model in keras is:



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


By the way, this error also happened when me convert this model by Tensorflow Lite.
But I don't know what's wrong with my model.
Does anyone has an idea?










share|improve this question

























  • The function load_model() can load model saved by func save_model(). In class callbacks, model saved by model.save(). What's the difference between these ways? How can I load a model saved by the second way?

    – Jonathan.H
    Oct 11 '18 at 7:08













  • Are you using the same Keras versions to save and load the model?

    – Matias Valdenegro
    Oct 11 '18 at 8:38











  • @MatiasValdenegro I'm using same version:2.2.2 both in Windows 10 and Ubuntu 16.04 platform, this problem occured in Windows 10, works fine in Ubuntu 16.04.

    – Jonathan.H
    Oct 12 '18 at 1:34














1












1








1








I saved my model automatically by callbacks.ModelCheckpoint() with a HDF5 file.



# Checkpoint In the /output folder
filepath = "./model/mnist-cnn-best.hd5"

# Keep only a single checkpoint, the best over test accuracy.
checkpoint = keras.callbacks.ModelCheckpoint(filepath, monitor='val_acc',
verbose=1, save_best_only=True,
mode='max')

# Train
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test),
callbacks=[checkpoint])


When I load a model, an error occured.



  model = keras.models.load_model("./mnist-cnn-best.hd5")

File "D:Program FilesAnaconda3libsite-packagestensorflowpythonkerasenginesaving.py", line 251, in load_model
training_config['weighted_metrics'])
KeyError: 'weighted_metrics'


If I load model with param 'compile=False', it works correctly.



I know the normal way to save model in keras is:



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


By the way, this error also happened when me convert this model by Tensorflow Lite.
But I don't know what's wrong with my model.
Does anyone has an idea?










share|improve this question
















I saved my model automatically by callbacks.ModelCheckpoint() with a HDF5 file.



# Checkpoint In the /output folder
filepath = "./model/mnist-cnn-best.hd5"

# Keep only a single checkpoint, the best over test accuracy.
checkpoint = keras.callbacks.ModelCheckpoint(filepath, monitor='val_acc',
verbose=1, save_best_only=True,
mode='max')

# Train
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test),
callbacks=[checkpoint])


When I load a model, an error occured.



  model = keras.models.load_model("./mnist-cnn-best.hd5")

File "D:Program FilesAnaconda3libsite-packagestensorflowpythonkerasenginesaving.py", line 251, in load_model
training_config['weighted_metrics'])
KeyError: 'weighted_metrics'


If I load model with param 'compile=False', it works correctly.



I know the normal way to save model in keras is:



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


By the way, this error also happened when me convert this model by Tensorflow Lite.
But I don't know what's wrong with my model.
Does anyone has an idea?







keras hdf5 tensorflow-lite






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Oct 11 '18 at 7:10







Jonathan.H

















asked Oct 11 '18 at 6:43









Jonathan.HJonathan.H

145




145













  • The function load_model() can load model saved by func save_model(). In class callbacks, model saved by model.save(). What's the difference between these ways? How can I load a model saved by the second way?

    – Jonathan.H
    Oct 11 '18 at 7:08













  • Are you using the same Keras versions to save and load the model?

    – Matias Valdenegro
    Oct 11 '18 at 8:38











  • @MatiasValdenegro I'm using same version:2.2.2 both in Windows 10 and Ubuntu 16.04 platform, this problem occured in Windows 10, works fine in Ubuntu 16.04.

    – Jonathan.H
    Oct 12 '18 at 1:34



















  • The function load_model() can load model saved by func save_model(). In class callbacks, model saved by model.save(). What's the difference between these ways? How can I load a model saved by the second way?

    – Jonathan.H
    Oct 11 '18 at 7:08













  • Are you using the same Keras versions to save and load the model?

    – Matias Valdenegro
    Oct 11 '18 at 8:38











  • @MatiasValdenegro I'm using same version:2.2.2 both in Windows 10 and Ubuntu 16.04 platform, this problem occured in Windows 10, works fine in Ubuntu 16.04.

    – Jonathan.H
    Oct 12 '18 at 1:34

















The function load_model() can load model saved by func save_model(). In class callbacks, model saved by model.save(). What's the difference between these ways? How can I load a model saved by the second way?

– Jonathan.H
Oct 11 '18 at 7:08







The function load_model() can load model saved by func save_model(). In class callbacks, model saved by model.save(). What's the difference between these ways? How can I load a model saved by the second way?

– Jonathan.H
Oct 11 '18 at 7:08















Are you using the same Keras versions to save and load the model?

– Matias Valdenegro
Oct 11 '18 at 8:38





Are you using the same Keras versions to save and load the model?

– Matias Valdenegro
Oct 11 '18 at 8:38













@MatiasValdenegro I'm using same version:2.2.2 both in Windows 10 and Ubuntu 16.04 platform, this problem occured in Windows 10, works fine in Ubuntu 16.04.

– Jonathan.H
Oct 12 '18 at 1:34





@MatiasValdenegro I'm using same version:2.2.2 both in Windows 10 and Ubuntu 16.04 platform, this problem occured in Windows 10, works fine in Ubuntu 16.04.

– Jonathan.H
Oct 12 '18 at 1:34












2 Answers
2






active

oldest

votes


















1














I hit a similar problem that yields the same error message, but the cause might be different than yours:



Code: (Tensorflow 1.11 and tf.keras.version: 2.1.6-tf)



 if load_model_path.endswith('.h5'):
model = tf.keras.models.load_model(load_model_path)


Error message:



  File "...../lib/python3.6/site-packages/tensorflow/python/keras/engine/saving.py", line 251, in load_model
training_config['weighted_metrics'])
KeyError: 'weighted_metrics'


And I found out it's because the model was saved in an older Keras version.
I had to comment out the code related to weighted_metrics to be able to load the model. However, it's just a workaround before I can find a sustainable solution to the mismatching problem. Interestingly, @fchollet just added weighted_metrics to the latest Keras version recently (Oct 2018).
https://github.com/keras-team/keras/blob/master/keras/engine/saving.py#L136
I hope this will help the people who hit the same problem as I did.






share|improve this answer

































    0














    If you haven't figured out the answer to this yet, I think I've got it.



    I haven't dug into the code to exactly figure out why, but basically the model checkpoint callback can only be loaded with the load_weights() function, which is then used for evaluation.



    If you want to save a model that you can load to train again later you need to use model.save and model.load_model. Hopefully helpful to someone who wanders upon this.






    share|improve this answer

























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52753846%2ferror-in-load-a-model-saved-by-callbakcs-modelcheckpoint-in-keras%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      I hit a similar problem that yields the same error message, but the cause might be different than yours:



      Code: (Tensorflow 1.11 and tf.keras.version: 2.1.6-tf)



       if load_model_path.endswith('.h5'):
      model = tf.keras.models.load_model(load_model_path)


      Error message:



        File "...../lib/python3.6/site-packages/tensorflow/python/keras/engine/saving.py", line 251, in load_model
      training_config['weighted_metrics'])
      KeyError: 'weighted_metrics'


      And I found out it's because the model was saved in an older Keras version.
      I had to comment out the code related to weighted_metrics to be able to load the model. However, it's just a workaround before I can find a sustainable solution to the mismatching problem. Interestingly, @fchollet just added weighted_metrics to the latest Keras version recently (Oct 2018).
      https://github.com/keras-team/keras/blob/master/keras/engine/saving.py#L136
      I hope this will help the people who hit the same problem as I did.






      share|improve this answer






























        1














        I hit a similar problem that yields the same error message, but the cause might be different than yours:



        Code: (Tensorflow 1.11 and tf.keras.version: 2.1.6-tf)



         if load_model_path.endswith('.h5'):
        model = tf.keras.models.load_model(load_model_path)


        Error message:



          File "...../lib/python3.6/site-packages/tensorflow/python/keras/engine/saving.py", line 251, in load_model
        training_config['weighted_metrics'])
        KeyError: 'weighted_metrics'


        And I found out it's because the model was saved in an older Keras version.
        I had to comment out the code related to weighted_metrics to be able to load the model. However, it's just a workaround before I can find a sustainable solution to the mismatching problem. Interestingly, @fchollet just added weighted_metrics to the latest Keras version recently (Oct 2018).
        https://github.com/keras-team/keras/blob/master/keras/engine/saving.py#L136
        I hope this will help the people who hit the same problem as I did.






        share|improve this answer




























          1












          1








          1







          I hit a similar problem that yields the same error message, but the cause might be different than yours:



          Code: (Tensorflow 1.11 and tf.keras.version: 2.1.6-tf)



           if load_model_path.endswith('.h5'):
          model = tf.keras.models.load_model(load_model_path)


          Error message:



            File "...../lib/python3.6/site-packages/tensorflow/python/keras/engine/saving.py", line 251, in load_model
          training_config['weighted_metrics'])
          KeyError: 'weighted_metrics'


          And I found out it's because the model was saved in an older Keras version.
          I had to comment out the code related to weighted_metrics to be able to load the model. However, it's just a workaround before I can find a sustainable solution to the mismatching problem. Interestingly, @fchollet just added weighted_metrics to the latest Keras version recently (Oct 2018).
          https://github.com/keras-team/keras/blob/master/keras/engine/saving.py#L136
          I hope this will help the people who hit the same problem as I did.






          share|improve this answer















          I hit a similar problem that yields the same error message, but the cause might be different than yours:



          Code: (Tensorflow 1.11 and tf.keras.version: 2.1.6-tf)



           if load_model_path.endswith('.h5'):
          model = tf.keras.models.load_model(load_model_path)


          Error message:



            File "...../lib/python3.6/site-packages/tensorflow/python/keras/engine/saving.py", line 251, in load_model
          training_config['weighted_metrics'])
          KeyError: 'weighted_metrics'


          And I found out it's because the model was saved in an older Keras version.
          I had to comment out the code related to weighted_metrics to be able to load the model. However, it's just a workaround before I can find a sustainable solution to the mismatching problem. Interestingly, @fchollet just added weighted_metrics to the latest Keras version recently (Oct 2018).
          https://github.com/keras-team/keras/blob/master/keras/engine/saving.py#L136
          I hope this will help the people who hit the same problem as I did.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Oct 29 '18 at 15:55

























          answered Oct 29 '18 at 15:33









          Nicole FinnieNicole Finnie

          89158




          89158

























              0














              If you haven't figured out the answer to this yet, I think I've got it.



              I haven't dug into the code to exactly figure out why, but basically the model checkpoint callback can only be loaded with the load_weights() function, which is then used for evaluation.



              If you want to save a model that you can load to train again later you need to use model.save and model.load_model. Hopefully helpful to someone who wanders upon this.






              share|improve this answer






























                0














                If you haven't figured out the answer to this yet, I think I've got it.



                I haven't dug into the code to exactly figure out why, but basically the model checkpoint callback can only be loaded with the load_weights() function, which is then used for evaluation.



                If you want to save a model that you can load to train again later you need to use model.save and model.load_model. Hopefully helpful to someone who wanders upon this.






                share|improve this answer




























                  0












                  0








                  0







                  If you haven't figured out the answer to this yet, I think I've got it.



                  I haven't dug into the code to exactly figure out why, but basically the model checkpoint callback can only be loaded with the load_weights() function, which is then used for evaluation.



                  If you want to save a model that you can load to train again later you need to use model.save and model.load_model. Hopefully helpful to someone who wanders upon this.






                  share|improve this answer















                  If you haven't figured out the answer to this yet, I think I've got it.



                  I haven't dug into the code to exactly figure out why, but basically the model checkpoint callback can only be loaded with the load_weights() function, which is then used for evaluation.



                  If you want to save a model that you can load to train again later you need to use model.save and model.load_model. Hopefully helpful to someone who wanders upon this.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jan 11 at 6:41









                  Common Man

                  1,24621226




                  1,24621226










                  answered Jan 11 at 4:15









                  Adam CollinsAdam Collins

                  1




                  1






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52753846%2ferror-in-load-a-model-saved-by-callbakcs-modelcheckpoint-in-keras%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Contact image not getting when fetch all contact list from iPhone by CNContact

                      count number of partitions of a set with n elements into k subsets

                      A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks