Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I load a keras saved model with custom Optimizer

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?

like image 325
Delta Avatar asked Feb 22 '19 21:02

Delta


People also ask

How do I save Keras model and load it?

Save Your Neural Network Model to JSON This can be saved to a file and later loaded via the model_from_json() function that will create a new model from the JSON specification. The weights are saved directly from the model using the save_weights() function and later loaded using the symmetrical load_weights() function.

How do I retrain a saved model in Keras?

After loading the saved model, you can retrain as usual using loaded_model. fit() . Please check detailed example here. Another most important point is that when you have a custom_objects, then you need to select compile=False when you load the model and then compile the model with the custom_objects.


1 Answers

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})
like image 141
Faeze Zps Avatar answered Oct 11 '22 10:10

Faeze Zps