Search code examples
pythonkeraslossloss-function

Python Keras Custom Loss, use feature from input in loss function


I am trying to create a custom loss function for a Keras regression task.

I am predicting the points scored per minute in a game, and training on "matches" of variable lengths, in minutes. In an attempt to help the model learn, I would like to include the number of minutes the group played as part of the loss function, so we can properly "punish" for missing on groups that play for longer durations.

I know I need to use Keras Backend/tensor operations, but I'm stuck on how to multiply the minutes tensor. Here's some basic code what I have so far (pseudo code/skipped where not important):

def penalized_loss(minutes):
    def loss(y_true, y_pred):

        # Normal mean_squared_error
        lost = K.mean(K.square(y_pred - y_true), axis=-1)

        # Would like something like this where minutes are included, but as a valid tensor operation
        not_valid_result = K.mean(K.square(y_pred - y_true) * minutes, axis=-1)

        return lost

    return loss

minutes = np.array(of some sort)

def baseline_model():
    # create model here...
    # ....

    # Compile model
    model.compile(loss=[penalized_loss(minutes)], optimizer='adam')
    return model

The closure to pass in minutes works as I expect, I'm just stuck on how to do the * minutes portion of the loss calculation.

Thanks in advance!


Solution

  • For you to use minutes in the graph it needs to be a tensor, unless minutes is a constant which has a fixed value for the lifetime of your program (in which case what you are doing should work).