具有条件返回值的自定义损失

时间:2019-06-21 12:24:20

标签: python tensorflow keras loss-function

我想要具有这种正则化的损失函数:对于每个预测,如果预测点的范数小于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”(op:“ Select”)的形状应为0和1。

我尝试了在喀拉斯邦环境之外的损失,这似乎行之有效。 例如:

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损失函数内部如何工作?

1 个答案:

答案 0 :(得分:0)

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)
相关问题