Des*_*wal 5 python machine-learning neural-network deep-learning pytorch
我正在研究语言任务的多类分类(4 个类),我正在使用 BERT 模型进行分类任务。我正在关注这个博客作为参考。我的 BERT Fine Tuned 模型返回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)
Run Code Online (Sandbox Code Playgroud)
我的结果不太好,所以我想到了实验 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
Run Code Online (Sandbox Code Playgroud)
我现在有3个问题。首先也是最重要的是
Focal Loss,我可以weights在里面使用参数吗 nn.CrossEntropyLoss()小智 4
您可能会通过以下方式找到问题的答案:
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
Run Code Online (Sandbox Code Playgroud)
您还可以尝试另一个可用的焦点损失版本
| 归档时间: |
|
| 查看次数: |
1878 次 |
| 最近记录: |