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

标签 machine-learning keras deep-learning computer-vision autoencoder

我想为自动编码器使用自定义 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

您的数据生成器必须在 __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)

关于machine-learning - 如何在Keras中实现自定义加权MSE损失函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58672006/

相关文章:

keras - 如何在 Keras 中进行权重不平衡类的交叉熵损失?

python - Keras 最简单的 NN 模型 : error in training. py 带索引

machine-learning - 关于 SegNet 架构中两个相继放置的卷积层

python-3.x - tensorflow中不同学习率的多任务学习

python - 为 sklearn 的 GradientBoostingClassifier 生成代码

python - 使用 Scipy 实现逻辑回归 : Why does this Scipy optimization return all zeros?

algorithm - 轨迹聚类 : Which Clustering Method?

python - 再次调用 model.fit 方法是否会重新初始化已经训练好的权重?

python - 如何创建一个层来反转softmax(TensorFlow,python)?

python - Scikit Learn Pipeline 的自定义变压器