我正在构建多标签分类网络。
我的 GT 是长度为 512
[0,0,0,1,0,1,0,...,0,0,0,1]
的向量
大多数时候它们是 zeroes
,每个向量大约有 5 ones
,其余的都是零。
我正在考虑:
使用 sigmoid
激活输出层。
使用 binary_crossentropy
作为损失函数。
但是我如何解决不平衡问题?
网络可以学习预测 always zeros
并且仍然具有非常低的学习损失分数。
我如何让它真正学会预测......
答案 0 :(得分:3)
您不能轻易上采样,因为这是一个多标签案例(我最初从帖子中遗漏了什么)。
你能做的是给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 也可以按照这些方式进行编码(功能形式原因就是我在 repo 中所拥有的,但您应该能够从中工作):
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)