Keras自定义损失功能中心

问题描述

我使用Keras后端函数编写了Huber损失,并且效果很好:

def huber_loss(y_true,y_pred,clip_delta=1.0):
    error = y_true - y_pred
    cond  = K.abs(error) < clip_delta
         
    squared_loss = 0.5 * K.square(error)
    linear_loss  = clip_delta * (K.abs(error) - 0.5 * clip_delta)

    return tf_where(cond,squared_loss,linear_loss)

但是我需要一个更复杂的损失函数

  1. 如果error <= A,请使用 squared_loss
  2. 如果A <= error < B,请使用 linear_loss
  3. 如果error >= B使用了 sqrt_loss

我这样写的东西:

def best_loss(y_true,A,B):
    error = K.abs(y_true - y_pred)
    cond  = error <= A
    cond2 = tf_logical_and(A < error,error <= B)

    squared_loss = 0.5 * K.square(error)
    linear_loss  = A * (error - 0.5 * A)
    sqrt_loss = A * np.sqrt(B) * K.sqrt(error) - 0.5 * A**2

    return tf_where(cond,tf_where(cond2,linear_loss,sqrt_loss))

但是它不起作用,具有此损失函数的模型无法收敛,这是什么错误

解决方法

我喜欢通过使用Desmos之类的图形化自定义函数来调试它们。 I graphed the Huber Loss using your implementation and it looks like how it should

When I tried to graph your second function it looks like a valid loss function too。唯一的问题是B小于A。如果B的值大于A,那么损失函数就不成问题了。如果这不是问题,那么您可以尝试在目标和输出之间切换减法,因为我不熟悉tensorflow如何处理微分,但顺序会影响梯度的方向。