1
votes

I'm trying to use my own loss function in Keras. In particular, being y_pred the predicted vector and y_true the true vector, i want that:

y_pred[i] = y_pred[i] if y_true[i] != 0
y_pred[i] = 0 if y_true[i] == 0

so I've tried the following:

def myloss(y_true, y_pred):
        mask = K.not_equal(y_true, 0)
        mask = K.cast(mask, dtype = 'float32')
        loss_value = K.mean(K.square(mask*y_pred - y_true), axis = 1)
        return loss_value

but I'm getting this error:

TypeError: Value passed to parameter 'x' has DataType bool not in list of allowed values: bfloat16, float16, float32, float64, uint8, int8, uint16, int16, int32, int64, complex64, complex128

Someone knows how to help me?

1
What is shape and datatype of your labels? - Vivek Mehta
Data type is float64, the shape is (n, 30), where n is the number of images I am passing to the network - Gianluca_27
Can you post full error stack trace? because this loss function is not causing any error. Although you might want to check out this function because it is returning array of length (n,) instead of a single loss value. - Vivek Mehta
Hi Vivek, thank you so much for your help. I'm trying a different approach and seems it could work, so maybe at the end I will add the solution. Thanks again - Gianluca_27
@Gianluca_27 Did you manage to resolve the issue? If yes, can you please share the details of it. - Tensorflow Warrior

1 Answers

0
votes

You can try using tf.boolean_mask :

def myloss(y_true, y_pred):
        mask = K.not_equal(y_true, 0)
        pred_masked = tf.boolean_mask(y_pred - y_true, mask)
        loss_value = K.mean(K.square(pred_masked), axis = 1)
        return loss_value