我正在尝试创建一个自定义损失函数,custom_loss(y_true, y_pred). 我知道这y_pred是由我的模型计算但我想交付两种y_true,例如y_true1和ytrue2(这些是预先计算的,未交付在model.fit(),并使用如下:(y_pred - y_true1/ y_pred - ytrue2)。问题是,我的批量大小不匹配问题,因为,我的自定义y_true1 and y_true2是在我的总数据集上创建的。如何使它们的批量大小为y_pred?
keras中的自定义损失,批量大小问题
数据挖掘
喀拉斯
损失函数
2022-03-11 02:15:51
1个回答
一种方法可能是:
class CustomLoss():
def __init__(self, steps_per_epoch):
super().__init__()
self.steps_per_epoch = steps_per_epoch
self.step = 0
def calc_custom_loss(self, y_true, y_pred):
y_true1 = get_y_true1(self.step)
y_true2 = get_y_true2(self.step)
self.step += 1
self.step %= self.steps_per_epoch
这样你只需要提供get_y_true1()和get_y_true2()接收步骤索引的函数。该索引用于生成适当的批次。
在代码中使用它:
# Assuming there are 100 batches in one epoch ...
custom_loss = CustomLoss(steps_per_epoch=100)
model.compile(loss=custom_loss.calc_custom_loss, ...)
如果您在训练期间还提供验证数据,请小心,因为它可能会改变您的self.step值……如果您想使用验证数据,则需要适当地处理该步骤。
其它你可能感兴趣的问题