【问题标题】:Custom loss with conditional return value具有条件返回值的自定义损失
【发布时间】:2019-06-21 12:24:20
【问题描述】:

我想要一个带有这种正则化的损失函数:对于每个预测,如果预测点的范数低于 0.9 或大于 1,我想应用正则化。

所以我写了这个:

def custom_loss(y_true, y_pred):

ret = keras.losses.mean_squared_error(y_true, y_pred)

n = tf.norm(y_pred, axis = 1)
intern_circle_distance = n - 0.9        
return tf.where(tf.logical_and(tf.greater(intern_circle_distance, 0),
                               tf.less(intern_circle_distance, 0.1))
                        ret,
                        ret*2)

当我在model.compile中使用这个时,返回错误:

形状必须具有相同的等级,但对于输入形状为 [?]、[]、[] 的“loss_71/Hyper_loss/Select”(操作:“Select”)为 0 和 1。

我尝试了 keras 环境之外的损失,它似乎有效。 例如:

a = tf.constant([[-1.0, 1.5]])
n = a - 1
K.eval(tf.where(tf.logical_and(tf.greater(n, 0)),
                               tf.less(n, 2)),
                a, a*2))

返回张量 [-2., 1.5]

为什么它在 keras 损失函数之外起作用而在 keras 损失函数内部不起作用? 它如何在 keras 损失函数中工作?

【问题讨论】:

    标签: python tensorflow keras loss-function


    【解决方案1】:

    keras.losses.mean_squared_error 为您提供一个标量数,即所有平方误差的平均值。如果您想更改每个示例的错误计算,请执行以下操作:

    def custom_loss(y_true, y_pred):
        diff = tf.squared_difference(y_true, y_pred)
        n = tf.norm(y_pred, axis=1)
        intern_circle_distance = n - 0.9
        diff_reg = tf.where((intern_circle_distance > 0) & (intern_circle_distance <0.1))
                            diff, 2 * diff)
        return tf.reduce_mean(diff_reg)
    

    【讨论】:

    • 为方便起见,我将第一个参数中的语法更改为 tf.where,但这与您的相同。
    • @NooneBug 很高兴它有帮助。如果您认为答案解决了您的问题,请考虑投票和/或将答案标记为已接受。
    • @NooneBug 没关系。如果需要,您可以将问题的答案标记为已接受(绿色勾号),以表明问题已解决。
    猜你喜欢
    • 2021-03-16
    • 1970-01-01
    • 2018-12-08
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    相关资源
    最近更新 更多