【发布时间】:2021-02-21 08:15:09
【问题描述】:
我正在研究语言任务的多类分类(4 类),我正在使用 BERT 模型进行分类任务。我关注this blog as reference。 我的 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)
我的结果不太好,所以我想用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中实现权重,我可以在nn.CrossEntropyLoss()中使用weights参数 - 如果这个工具不正确,这个工具的正确代码应该是什么,包括权重(如果可能的话)
【问题讨论】:
标签: python machine-learning deep-learning neural-network pytorch