我想为自编码器使用一个自定义的均方误差(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 lossdef 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))
编辑
在定义上述张量后,像这样创建两个模型
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)