我正在研究语言任务的多类分类(4 个类),我正在使用 BERT 模型进行分类任务。我正在关注 this blog as reference . 我的 BERT 微调模型返回 nn.LogSoftmax(dim=1)
.
我的数据非常不平衡,所以我使用了 sklearn.utils.class_weight.compute_class_weight
计算类的权重并使用损失中的权重。
class_weights = compute_class_weight('balanced', np.unique(train_labels), train_labels)
weights= torch.tensor(class_weights,dtype=torch.float)
cross_entropy = nn.NLLLoss(weight=weights)
我的结果不太好,所以我想用 Focal Loss
做实验。并有一个 Focal Loss 代码。class FocalLoss(nn.Module):
def __init__(self, alpha=1, gamma=2, logits=False, reduce=True):
super(FocalLoss, self).__init__()
self.alpha = alpha
self.gamma = gamma
self.logits = logits
self.reduce = reduce
def forward(self, inputs, targets):
BCE_loss = nn.CrossEntropyLoss()(inputs, targets)
pt = torch.exp(-BCE_loss)
F_loss = self.alpha * (1-pt)**self.gamma * BCE_loss
if self.reduce:
return torch.mean(F_loss)
else:
return F_loss
我现在有3个问题。首先也是最重要的是Focal Loss
, 我可以用 weights
里面的参数 nn.CrossEntropyLoss()
最佳答案
您可以通过以下方式找到问题的答案:
pred_sigmoid = pred.sigmoid()
target = target.type_as(pred)
pt = (1 - pred_sigmoid) * target + pred_sigmoid * (1 - target)
focal_weight = (alpha * target + (1 - alpha) *
(1 - target)) * pt.pow(gamma)
loss = F.binary_cross_entropy_with_logits(
pred, target, reduction='none') * focal_weight
loss = weight_reduce_loss(loss, weight, reduction, avg_factor)
return loss
您也可以尝试使用 another focal loss version available
关于python - 如何在 PyTorch 中使用具有焦点损失的类权重用于多类分类的不平衡数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64751157/