需要使用 if 语句的自定义损失函数

Need custom loss function that uses if statement

我正在尝试训练输出 3 个值 (x,y,z) 的 DNN,其中 xy 是我正在寻找的对象的坐标,z 是对象存在的概率

我需要自定义损失函数:

如果 z_true<0.5 我不关心 xy 值,那么错误应该等于 (0, 0, sqr(z_true - z_pred))

否则错误应该像(sqr(x_true - x_pred), sqr(y_true - y_pred), sqr(z_true - z_pred))

我正在努力将张量和 if 语句混合在一起。

也许这个自定义损失函数的例子会让你兴奋 运行。它展示了如何将张量与 if 语句混合使用。

 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=...)

从 Keras 后端使用 switchhttps://keras.io/backend/#switch 它类似于 tf.cond 如何在此处描述的 Keras 中创建自定义损失: