你不能轻易上采样,因为这是一个多标签案例(我最初从帖子中遗漏了)。
你可以做的是给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)