问题
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:
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.
回答2:
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
来源:https://stackoverflow.com/questions/54835331/how-do-i-load-a-keras-saved-model-with-custom-optimizer