Correct way of loss function

后端 未结 1 1794
走了就别回头了
走了就别回头了 2020-12-20 00:07

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

相关标签:
1条回答
  • 2020-12-20 00:57

    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))
    
    0 讨论(0)
提交回复
热议问题