Skip to content Skip to sidebar Skip to footer

Correct Way Of Loss Function

Hi I have been trying to implement a loss function in keras. But i was not able to figure a way to pass more than 2 arguments other than loss(y_true, y_predict) so I thought of usi

Solution 1:

Answers to your questions:

  1. I don't know whether your approach works, but there is an easier solution.

  2. You can pass multiple arguments by defining a partial function.

  3. The output of a loss function is a scalar.

Here is an example that demonstrates how to pass multiple arguments to a loss function:

from keras.layers import Input, Dense
from keras.models import Model
import keras.backend as K


def custom_loss(arg1, arg2):
    def loss(y_true, y_pred):
        # Use arg1 and arg2 here as you wish and return loss
        # For example:
        return K.mean(y_true - y_pred) + arg1 + arg2
    return loss

x = Input(shape=(1,))
arg1 = Input(shape=(1,))
arg2 = Input(shape=(1,))
out = Dense(1)(x)
model = Model([x, arg1, arg2], out)
model.compile('sgd', custom_loss(arg1, arg2))

Post a Comment for "Correct Way Of Loss Function"