Search code examples
rtensorflowkerasloss-function

How to load a Keras model with a custom loss function?


I have created the following custom loss function:

RMSE = function(y_true,y_pred) {
         k_sqrt(k_mean(k_square(y_pred - y_true))) 
    }

And it works fine when I saved the model. However, when I loaded the model back using:

load_model_hdf5(filepath= "modelpath") 

I get the following error:

#Error in py_call_impl(callable, dots$args, dots$keywords):
#      valueError: Unknown loss function:RMSE

Maybe this question has something in common with this one I made before. What should I do to stop getting this error?


Solution

  • Since you are using a custom loss function in your model, the loss function would not be saved when persisting the model on disk and instead only its name would be included in the model file. Then, when you want to load back the model at a later time, you need to inform the model of the corresponding loss function for the stored name. To provide that mapping, you can use custom_objects argument of load_model_hdf5 function:

    load_model_hdf5(filepath = "modelpath", custom_objects = list(RMSE = RMSE))
    

    Alternatively, after training is finished, if you just want to use the model for prediction you can just pass compile = False argument to load_model_hdf5 function (hence, the loss function would not be needed and loaded):

    load_model_hdf5(filepath = "modelpath", compile = False)