I am trying to create the custom loss function using Keras. I want to compute the loss function based on the input and predicted the output of the neural network.
I tried using the customloss function in Keras. I think y_true is the output that we give for training and y_pred is the predicted output of the neural network. The below loss function is same as "mean_squared_error" loss in Keras.
def customloss(y_true, y_pred):
return K.mean(K.square(y_pred - y_true), axis=-1)
I would like to use the input to the neural network also to compute the custom loss function in addition to mean_squared_error loss. Is there a way to send an input to the neural network as an argument to the customloss function.
Thank you.
I have come across 2 solutions to the question you asked.
This solution is also mentioned in the accepted answer here
This solution can be found also here in this thread.
I have only used the 2nd method when I had to use input feature columns in the loss. I have used the first method with scalar arguments; but I believe a tensor input works as well.
You could wrap your custom loss with another function that takes the input tensor as an argument:
And then compile your model as follows:
where
x
is your input tensor.NOTE: Not tested.