使用logit loss函数创建自定义BCE



我想为多标签分类创建一个自定义的损失函数。这个想法是以不同的方式衡量正面和负面标签。为此,我使用了这个自定义代码实现。

class WeightedBCEWithLogitLoss(nn.Module):
def __init__(self, pos_weight, neg_weight):
super(WeightedBCEWithLogitLoss, self).__init__()
self.register_buffer('neg_weight', neg_weight)
self.register_buffer('pos_weight', pos_weight)
def forward(self, input, target):
assert input.shape == target.shape, "The loss function received invalid input shapes"
y_hat = torch.sigmoid(input + 1e-8)
loss = -1.0 * (self.pos_weight * target * torch.log(y_hat + 1e-6) + self.neg_weight * (1 - target) * torch.log(1 - y_hat + 1e-6))
# Account for 0 times inf which leads to nan
loss[torch.isnan(loss)] = 0
# We average across each of the extra attribute dimensions to generalize it
loss = loss.mean(dim=1)
# We use mean reduction for our task
return loss.mean()

我开始获取nan值,我意识到这是因为0乘以inf。我如图所示处理了它。接下来,我再次看到得到inf作为错误值,并通过在日志中添加1e-6来更正它(我尝试使用1e-8,但仍然给了我inf错误值(。

如果有人能看一看,提出进一步的改进建议,并纠正这里出现的任何错误,那就太好了。

您不必实现它。它已经完成了
BCEWithLogits接受参数pos_weight,根据文档,该参数被用作

pos_weight ( Tensor , optional ) – a weight of positive examples.
Must be a vector with length equal to the number of classes

最新更新