需要张量操作的keras(tf后端)中的自定义丢失

时间:2018-06-02 22:46:40

标签: tensorflow keras loss-function

我的目标是预测2点的坐标:[x1,x2]。 (2点的y坐标是固定的)。 除了均方误差(xtrue - xpred)**2之外,我想最小化斜率误差:大约(1/(x2true - x1true) - 1/(x2pred - x1pred))**2

enter image description here

这是我的实现,它引发了以下错误:

Shape must be rank 2 but is rank 1 for 'concat_1' (op: 'ConcatV2')
with input shapes: [?,?], [?], [].

-

自定义丢失

def combo_mse():
    def combo_loss(y_true, y_pred):
        slope_true = 1/( y_true[:, 1] - y_true[:, 0] )
        combo_true = K.concatenate([y_true, slope_true])

    slope_pred = 1/( y_pred[:, 1] - y_pred[:, 0] )
    combo_pred = K.concatenate([y_pred, slope_pred])

    se = K.square( combo_pred - combo_true)
    loss = K.mean(se, axis=-1)
    return loss
return combo_loss

如何切割输出张量y_truey_pred,运行一些操作并使用K.concatenate()创建新的张量以生成新的自定义丢失函数?

1 个答案:

答案 0 :(得分:1)

在连接之前,您必须更改slope_true和slope_pred的形状。以下代码应该有效。原因是您的slope tensors是一个维度,而y_truey_pred张量是二维的。相同维度张量之间允许连接操作。

def combo_mse():
        def combo_loss(y_true, y_pred):
            slope_true = 1/( y_true[:, 1] - y_true[:, 0] )
            slope_true = tf.reshape(slope_true, (-1, 1))
            combo_true = K.concatenate([y_true, slope_true])

        slope_pred = 1/( y_pred[:, 1] - y_pred[:, 0] )
        slope_pred = tf.reshape(slope_pred, (-1, 1))
        combo_pred = K.concatenate([y_pred, slope_pred])

        mse = K.square( combo_pred - combo_true)
        loss = K.mean(mse, axis=-1)
        return loss
    return combo_loss