标签不平衡的多标签分类



我正在构建多标签分类网络。我的GT是长度为512[0,0,0,1,0,1,0,...,0,0,0,1]的矢量大多数时候它们是zeroes,每个向量大约有5 ones,其余的都是零。

我正在考虑做:

使用sigmoid激活输出层。

损失函数使用binary_crossentropy

但我该如何解决失衡问题呢?网络可以学习预测always zeros,并且仍然具有非常低的学习损失分数。

我如何才能让它真正学会预测。。。

由于这是一个多标签的情况(我最初在帖子中遗漏了这一点(,您无法轻松地进行上采样。

您可以做的是给1更高的权重,类似于以下内容:

import torch

class BCEWithLogitsLossWeighted(torch.nn.Module):
def __init__(self, weight, *args, **kwargs):
super().__init__()
# Notice none reduction
self.bce = torch.nn.BCEWithLogitsLoss(*args, **kwargs, reduction="none")
self.weight = weight
def forward(self, logits, labels):
loss = self.bce(logits, labels)
binary_labels = labels.bool()
loss[binary_labels] *= labels[binary_labels] * self.weight
# Or any other reduction
return torch.mean(loss)

loss = BCEWithLogitsLossWeighted(50)
logits = torch.randn(64, 512)
labels = torch.randint(0, 2, size=(64, 512)).float()
print(loss(logits, labels))

此外,您还可以使用FocalLoss来关注积极的示例(在一些库中应该有一些可用的实现(。

编辑:

Focal Loss也可以按照这些线进行编码(功能形式原因是我在回购中有这样的东西,但你应该能够从中工作(:

def binary_focal_loss(
outputs: torch.Tensor,
targets: torch.Tensor,
gamma: float,
weight=None,
pos_weight=None,
reduction: typing.Callable[[torch.Tensor], torch.Tensor] = None,
) -> torch.Tensor:
probabilities = (1 - torch.sigmoid(outputs)) ** gamma
loss = probabilities * torch.nn.functional.binary_cross_entropy_with_logits(
outputs,
targets.float(),
weight,
reduction="none",
pos_weight=pos_weight,
)
return reduction(loss)

最新更新