我有一个 VAE 模型,我已将其分解为编码器和解码器部分,并实现了自定义损失。一个简化的例子如下
input = Input(shape=(self.image_height, self.image_width, self.image_channel))
encoded = build_encoder(input)
decoded = build_decoder(encoded)
model = Model(input, decoded)
损失(简化)是
loss = K.mean(decoded[0] + decoded[1] + encoded[0]**2)
model.add_loss(loss)
model.compile(optimizer=self.optimizer)
我的主要问题是我想使用 Keras 的 modelcheckpoint 函数,这将要求我设置自定义指标。然而,我在网上看到的一切都类似于https://keras.io/metrics/#custom_metrics .这只接受 y_true 和 y_pred,并从那里修改验证损失。我将如何在我的示例模型中实现它,其中损失是根据多个输入计算的,而不仅仅是“解码”的最终输出?
最佳答案
很显然,您仍然可以使用变量(keras 层)而不将它们传递给自定义损失函数。
所以对于我的例子,损失可以计算为
def custom_loss(y_true, y_pred):
return K.mean(decoded[0] + decoded[1] + encoded[0]**2)
model.compile(optimizer=self.optimizer, loss=custom_loss)
y_true 和 y_pred 从未使用过,但仍然可以调用实际所需的输入(当然只要它们与自定义损失函数在同一范围内)。
关于python - 具有两个以上输入的 Keras 自定义指标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52621995/