2

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.

Nikita
  • 163
  • 2
  • 9

2 Answers2

2

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=...)
AaronDT
  • 3,940
  • 8
  • 31
  • 71
  • 1
    in this way, I have to know `l` before compiling model and if I will generate new samples for every epoch, I won't be able to change `l` anymore? – Nikita Jan 11 '19 at 20:10
  • I assume you could write a custom generator that calculates „l“ depending on the current batch you are processing. Then you could call that function to update the value of „l“ in the lossfunction. – AaronDT Jan 11 '19 at 21:13
1

Use switch from Keras backend: https://keras.io/backend/#switch It is similar to tf.cond How to create a custom loss in Keras described here: Make a custom loss function in keras

Dmytro Prylipko
  • 4,762
  • 2
  • 25
  • 44