Iterate in Keras custom loss function

Viewed 96

I know that is better avoid loop in Keras custom loss function, but I think I have to do it. The problem is the following: I'm trying to implement a loss function that compute a loss value for multiple bunches of data and then aggregate this values in an unique value.

For example I have 6 data entry, so in my Keras loss I'll have 6 y_true and 6 y_pred. I want to compute 2 loss value: one for the first 3 elements and one for the last 3 elements.

Example of hypothetical code:

def custom_loss(y_true, y_pred): 
    start_range = 0
    losses = []
    for index in range(0,2):
        end_range = start_range + 3
        y_true_bunch = y_true[start_range:end_range]
        y_pred_bunch = y_pred[start_range:end_range]
        loss_value = ...some processing on bunches...
        losses.append(loss_value)
        start_range = end_range
    final_loss = ...aggregate loss_value...
    return final_loss

Is it possible to achieve something like this without for loop? I need to process the whole dataset and calculate loss for multiple bunches and then aggregate all bunches value in a single value.

0 Answers
Related