15

I have compiled and trained a keras model with a custom optimizer. I saved the model but when I try to load the model, it throws an error stating ValueError: Unknown optimizer: MyOptimizer. I tried to pass MyOptimizer as a custom object something like : models.load_model('myModel.h5', custom_objects={'optimizer':MyOptimizer}) and it still throws an error. How do I load the model a keras model with custom Objects?

1

3 Answers 3

18

I ran into the same problem :)

I made it work by loading the model with models.load_model('myModel.h5', compile=False).

From the keras source code:

If an optimizer was found as part of the saved model, the model is already compiled. Otherwise, the model is uncompiled and a warning will be displayed. When compile is set to False, the compilation is omitted without any warning.

After the uncompiled model is loaded, I can compile it again with my custom optimizer.

1
  • btw, you don't need to compile for inference only Aug 1, 2019 at 9:59
9

You have to use the name of optimizer class as the key in the custom_objects dictionary, in your case, as the optimizer would be 'MyOptimizer' object,

models.load_model('myModel.h5', custom_objects={'MyOptimizer': MyOptimizer})

should work

1

I had the same problem. However, I had two different custom things in my model. One was my optimizer and the other was a custom layer. Therefore, I solved my problem as follow:

my_loaded_model = tf.keras.models.load_model('my_models_name.h5', custom_objects={'KerasLayer':hub.KerasLayer , 'AdamWeightDecay': optimizer})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.