如何在 Keras 中实现自定义加权 MSE 损失函数?

How to implement Custom weighted MSE Loss Function in Keras?

我想为自动编码器使用自定义 MSE。我有自动编码器的输入(X)和输出(Y)图像,它们实际上是相同的图像。现在在计算 MSE 期间,我们计算真实输出 (Y=X) 和预测输出图像 (Y') 之间的 MSE。

比方说,对于每个图像 X,我都有一个派生图像 X',它是该图像的权重矩阵。 X' 的大小与 X 或 Y 相同。它包含 0 到 1 之间的值。因此,在计算 MSE 期间,我想使用 X(也是 Y 和预期的重构输出)、X' 和预测输出 Y '.

如果有人能给我建议如何在 Keras 中实现它,我将非常感激。

你可以像这样做一个损失层

class LossLayer(Layer):
    def __init__(self,  **kwargs):
        super(LossLayer, self).__init__(**kwargs)

    def build(self, input_shape):
        super(LossLayer, self).build(input_shape)  # Be sure to call this somewhere!

    def call(self, x):
        input_image, weighted_image, predicted = x
        loss = weightedmse(input_image, weighted_image, predicted)
        return loss

def dummy_loss(y_true, y_pred):
    return tf.sqrt(tf.reduce_sum(y_pred))

构建模型时这样使用。

input_image = Input(...)
weighted_image = Input(...)
x = Conv2D(...)(input_image)
.
.
loss_layer = LossLayer()([input_image, weighted_image, x])  # x here is the last Conv layer

您的数据生成器必须 return __getitem___

中的类似内容
[input_img, weighted], np.zeros((batch_size, 1))

编辑

定义上面的张量后创建 2 个这样的模型

train_model = Model([input_image, weighted_image], loss_layer)
pridict_model = Model([input_image, weighted_image], x)
train_model.compile(optimizer='sgd', loss=dummy_loss)