Octavian Costache
Octavian Costache

Reputation: 101

How to write a conditional custom loss function for a Keras model

I am trying to build a model that can do landmark detection for Dog Faces - if a dog face is present, extract the x/y coordinates of the eyes and the nose, otherwise tell me that there's no dog face.

I would like my output tensor to be of size 7:

I can't figure out how to write a custom loss function that would go something like this:

# This is largely pseudo-code!
def custom_l1_loss(y_true, y_pred):
  if y_true[0] == 1:
    # Probability that there's a dog face = 1
    return K.sum(K.abs(y_pred[1:] - y_true[1:]), axis=-1)
  else:
    # Only return the difference in probabilities that a dog face is present
    return y_true[0] - y_pred[0]

Question: Has anybody had experience with writing a similar conditional loss function in Keras?

Upvotes: 1

Views: 2317

Answers (1)

James Dong
James Dong

Reputation: 404

You can extract column [0] and use it as a mask as shown in the following code, so that your conditional loss calculation is simplified into one line calculation.

def custom_l1_loss(y_true, y_pred):

    y_true_present = y_true[...,0:1]
    y_pred_present = y_pred[...,0:1]

    loss = K.sum(y_true_present*K.abs(y_pred[...,1:] - y_true[...,1:]),axis=-1)+ K.sum((1-y_true_present)*K.abs(y_true_present-y_pred_present),axis=-1)

    return loss

Upvotes: 4

Related Questions