Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Keras自定义损失函数huber_Python_Tensorflow_Machine Learning_Keras_Loss Function - Fatal编程技术网

Python Keras自定义损失函数huber

Python Keras自定义损失函数huber,python,tensorflow,machine-learning,keras,loss-function,Python,Tensorflow,Machine Learning,Keras,Loss Function,我使用Keras后端函数编写了huber loss,效果很好: 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.

我使用Keras后端函数编写了huber loss,效果很好:

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)

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

我喜欢通过使用类似Desmos的程序绘制自定义函数来调试它们


。唯一的问题是当B小于A时。如果B的值大于A,那么损失函数就不会有问题。如果这不是问题,那么您可以尝试在目标和输出之间切换减法,因为我不熟悉tensorflow如何处理微分,但顺序会影响渐变的方向。

如果顺序更改,则tensorflow中的渐变方向也会更改。
def best_loss(y_true, y_pred, 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, squared_loss, tf_where(cond2, linear_loss, sqrt_loss))