How do I load a keras saved model with custom Optimizer

拥有回忆 提交于 2020-05-14 18:24:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!