Today I want to share with you how to load custom keras model with custom metric.
Saving a model is very easy and there are many ways to do it, all well explained in the official documentation. However sometimes we may ended up training our model with a custom metric(s), save it, and then got into trouble trying to load it again. (keras would still allow us to save it without a runtime error)
This happen because we should save it properly when using custom function in the model-compile phase. Not like this:
# model is our tensorflow trained model
# saving it
Because then in the loading phase we would get the following error:
Exception has occurred: ValueError
Unable to restore custom object of type _tf_keras_metric currently.
Please make sure that the layer implements get_config`and `from_config when saving.
In addition, please use the custom_objects arg when calling load_model().
But not all hope is lost. In fact, the error is due to the fact that keras is unable to correctly load our custom metrics, which are essential for training the model. You got it right … training, in fact they are not necessary if we only have to use model.predict (we only care about the weights!).
So, if you too find yourself in the same situation as I found myself today (not being able to load the model to make predictions), just change the parameters of the load function as follows:
Done.Now you are abel to load custom keras model with custom metric
Check my latest posts HERE