实施使用 Keras 训练批数据的自定义损失

Implementing custom loss that makes use of training batch data with Keras

我正在尝试实现 Apple 研究人员提出的名为 SimGAN 的 GAN。 SimGAN 用于改进 标记 合成图像,使它们看起来更像 未标记 真实图像。

论文的 link 可以在 arXiv here 上找到。

在论文中,包含生成器和判别器的组合模型的损失函数具有 L1 loss 形式的自正则化组件,它会惩罚合成模型之间的太大差异图像和细化后的图像。换句话说,细化不应该太激烈。

我想知道如何在 Keras 中实现这种自正则化损失。这是我尝试过的:

def self_regularization_loss(refined_images, syn_images):
    
    def l1loss(y_true, y_pred):
        return keras.metrics.mean_absolute_error(refined_images, syn_images)
        
    return l1loss
    

但是,我认为我无法按以下方式编译模型,因为在训练期间精细化和合成图像的批次会发生变化。

model.compile(loss=[self_regularization_loss(current_batch_of_refined, current_batch_of_synthetic),
                    local_adversarial_loss],
              optimizer=opt)
    

这个损失的实现方式是什么?

尝试使用 tf.function 装饰器和 tf.GradientTape():

@tf.function
def train_step(model, batch):
    with tf.GradientTape() as tape:
        refined_images, syn_images = batch
        loss = self_regularization_loss(model, refined_images, syn_images)

    gradients = tape.gradient(loss, model.trainable_variables)
    self.optimizer.apply_gradients(zip(gradients, model.trainable_variables))

你的训练循环看起来像:

for image_batch in dataset:
  train_step(model, image_batch)

这里假设model的类型是tf.keras.Model。有关模型 class 的更多详细信息,请参见 here。请注意,model 也会传递给 self_regularization_loss。在此函数中,您的 model 接收两个图像作为输入,然后为您提供相应的输出。然后你计算你的损失。