赞
踩
在PyTorch中进行二分类,有三种主要的全连接层,激活函数和loss function组合的方法,分别是:torch.nn.Linear+torch.sigmoid+torch.nn.BCELoss,torch.nn.Linear+BCEWithLogitsLoss,和torch.nn.Linear(输出维度为2)+torch.nn.CrossEntropyLoss,BCEWithLogitsLoss集成了Sigmoid,但是CrossEntropyLoss集成了Softmax。
下面重点写写几点区别:
来点代码:
- import torch
- from torch import nn
- import math
-
- loss_f = nn.CrossEntropyLoss(reduction='none')
- output = torch.randn(2, 3) # 表示2个样本,3个类别
- # target = torch.from_numpy(np.array([1, 0])).type(torch.LongTensor)
- target = torch.LongTensor([0, 2]) # 表示label0和label2
- loss = loss_f(output, target)
-
- print('CrossEntropy loss: ', loss)
- print(f'reduction=none,所以可以看到每一个样本loss,输出为[{loss}]')
-
- nll = nn.NLLLoss(reduction='none')
- logsoftmax = nn.LogSoftmax(dim=-1)
- print('logsoftmax(output) result: {}'.format(logsoftmax(output)))
- #可以清晰地看到nll这个loss在pytorch多分类里作用就是取个负号,同时去target对应下标拿一下已经算好的logsoftmax的值
- print('nll(logsoftmax(output), target) :{}'.format(nll(logsoftmax(output), target)))
-
-
- def manual_cal(sample_index, target, output):
- # 输入是样本下标
- sample_output = output[sample_index]
- sample_target = target[sample_index]
- x_class = sample_output[sample_target]
- sample_output_len = len(sample_output)
- log_sigma_exp_x = math.log(sum(math.exp(sample_output[i]) for i in range(sample_output_len)))
- sample_loss = -x_class + log_sigma_exp_x
- print(f'交叉熵手动计算loss{sample_index}:{sample_loss}')
- return sample_loss
-
- for i in range(2):
- manual_cal(i, target, output)
-
- # 如果nn.CrossEntropyLoss(reduction='mean')模式,刚好是手动计算的每个样本的loss取平均,最后输出的是一个值
- # 如果nn.CrossEntropyLoss(reduction='none')模式,手动计算的loss0和loss1都会被列出来
-
- '''
- 贴一个输出
- CrossEntropy loss: tensor([2.7362, 0.9749])
- reduction=none,所以可以看到每一个样本loss,输出为[tensor([2.7362, 0.9749])]
- logsoftmax(output) result: tensor([[-2.7362, -1.4015, -0.3726],
- [-0.8505, -1.6319, -0.9749]])
- nll(logsoftmax(output), target) :tensor([2.7362, 0.9749])
- 交叉熵手动计算loss0:2.736179828643799
- 交叉熵手动计算loss1:0.9749272465705872
- '''
-
如果用Pytorch来实现,可以看以下脚本,顺带连rce(logit和pred对换)和sce(ce和rce加强)也实现了:
- import torch.nn.functional as F
- import torch
- import torch.nn as nn
- # nn.CrossEntropyLoss() 和 KLDivLoss 关系
-
- class SCELoss(nn.Module):
- def __init__(self, num_classes=10, a=1, b=1, eps=1e-18):
- super(SCELoss, self).__init__()
- self.num_classes = num_classes
- self.a = a #两个超参数
- self.b = b
- self.cross_entropy = nn.CrossEntropyLoss()
- self.cross_entropy_none = nn.CrossEntropyLoss(reduction="none")
- self.eps = eps
-
- def forward(self, raw_pred, labels):
- # CE 部分,正常的交叉熵损失
- ce = self.cross_entropy(raw_pred, labels)
- # RCE
- pred = F.softmax(raw_pred, dim=1)
- pred = torch.clamp(pred, min=self.eps, max=1.0)
- label_one_hot = F.one_hot(labels, self.num_classes).float().to(pred.device)
- label_one_hot = torch.clamp(label_one_hot, min=self.eps, max=1.0) #最小设为 1e-4,即 A 取 -4
-
- my_ce = (-1 * torch.sum(label_one_hot * torch.log(pred), dim=1))
- print('pred={} label_one_hot={} my_ce={}'.format(pred, label_one_hot, my_ce))
- print('raw_pred={} labels={} official_ce={}'.format(raw_pred, labels, self.cross_entropy_none(raw_pred, labels)))
-
- rce = (-1 * torch.sum(pred * torch.log(label_one_hot), dim=1))
- print('pred={} label_one_hot={} rce={}'.format(pred, label_one_hot, rce))
-
- loss = self.a * ce + self.b * rce.mean()
- return loss
-
- y_pred = torch.tensor([[10.0, 5.0, -6.0], [8.0, 8.0, 8.0]])
- y_true = torch.tensor([0, 2])
- ce1 = SCELoss(num_classes=3)(y_pred, y_true)
-
来个各种CE的完整实现:
- import torch
- import torch.nn as nn
- import torch.nn.functional as F
-
- class MyCE1(nn.Module):
- def __init__(self):
- super(MyCE1, self).__init__()
- self.nll = nn.NLLLoss(reduction='none')
- self.logsoftmax = nn.LogSoftmax(dim=-1)
- def forward(self, logits, targets):
- return self.nll(self.logsoftmax(logits), targets)
-
- class MyCE2(nn.Module):
- def __init__(self):
- super(MyCE2, self).__init__()
-
- def forward(self, logits, targets):
- label_one_hot = F.one_hot(targets, num_classes=max(targets)+1)
- logits_softmax_log = torch.log(logits.softmax(dim=-1))
- res = -1*torch.sum(label_one_hot*logits_softmax_log, dim=-1)
- return res
-
- if __name__ == '__main__':
- logits = torch.rand(4,3)
- targets = torch.LongTensor([1,2,1,0])
- myce1 = MyCE1()
- myce2 = MyCE2()
- ce = nn.CrossEntropyLoss(reduction='none')
- print(myce1(logits, targets))
- print(myce2(logits, targets))
- print(ce(logits, targets))
- '''
- tensor([0.8806, 0.9890, 1.1915, 1.2485])
- tensor([0.8806, 0.9890, 1.1915, 1.2485])
- tensor([0.8806, 0.9890, 1.1915, 1.2485])
- '''
----------------------------------------
转载自: 二分类问题,应该选择sigmoid还是softmax? - 知乎
pytorch验证CrossEntropyLoss ,BCELoss 和 BCEWithLogitsLoss - CodeAntenna
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。