4

尝试在 keras 中自定义损失函数(平滑 L1 损失),如下所示

ValueError:形状必须为 0 级,但对于 'cond/Switch'(操作:'Switch')为 5 级,输入形状为:[?,24,24,24,?], [?,24,24,24,? ]。

from keras import backend as K
import numpy as np


def smooth_L1_loss(y_true, y_pred):
    THRESHOLD = K.variable(1.0)
    mae = K.abs(y_true-y_pred)
    flag = K.greater(mae, THRESHOLD)
    loss = K.mean(K.switch(flag, (mae - 0.5), K.pow(mae, 2)), axis=-1)
    return loss
4

3 回答 3

9

我知道我迟到了两年,但是如果你使用 tensorflow 作为 keras 后端,你可以像这样使用 tensorflow 的Huber 损失(本质上是一样的):

import tensorflow as tf


def smooth_L1_loss(y_true, y_pred):
    return tf.losses.huber_loss(y_true, y_pred)
于 2019-05-22T11:14:59.747 回答
6

这是使用 keras.backend 的 Smooth L1 loss 的实现:

HUBER_DELTA = 0.5
def smoothL1(y_true, y_pred):
   x   = K.abs(y_true - y_pred)
   x   = K.switch(x < HUBER_DELTA, 0.5 * x ** 2, HUBER_DELTA * (x - 0.5 * HUBER_DELTA))
   return  K.sum(x)
于 2017-05-23T10:39:00.027 回答
2
def smoothL1(y_true, y_pred):
    x = K.abs(y_true - y_pred)
    if K._BACKEND == 'tensorflow':
        import tensorflow as tf
        x = tf.where(x < HUBER_DELTA, 0.5 * x ** 2, HUBER_DELTA * (x - 0.5 * HUBER_DELTA))
        return  K.sum(x)
于 2017-06-07T02:58:03.387 回答