Need custom loss function that uses if statement

Viewed 1718

I'm trying to train DNN that outputs 3 values (x,y,z) where x and y are coordinates of the object I'm looking for and z is the probability that object is present

I need custom loss function:

If z_true<0.5 I don't care of x and y values, so error should be equal to (0, 0, sqr(z_true - z_pred))

otherwise error should be like (sqr(x_true - x_pred), sqr(y_true - y_pred), sqr(z_true - z_pred))

I'm in a struggle with mixing tensors and if statements together.

2 Answers

Maybe this example of a custom loss function will get you up and running. It shows how you can mix tensors with if statements.

 def conditional_loss_function(l):
        def loss(y_true, y_pred):
            if l == 0: 
                return loss_funtion1(y_true, y_pred)
            else: 
                return loss_funtion2(y_true, y_pred)
        return loss

 model.compile(loss=conditional_loss_function(l), optimizer=...)
Related