pytorch中BCELoss、CrossEntropyLoss和NLLLoss

2024-03-17 14:18

本文主要是介绍pytorch中BCELoss、CrossEntropyLoss和NLLLoss,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在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。

下面重点写写几点区别:

  • CrossEntropyLoss的输入logits=(3,2),target=(3)就够了,但是BCELoss、BCEWithLogitsLoss的输入得是logits=(3,2),target=(3,2)。也就是说BCE系列在设计的时候是期待把输出压缩成一维再过;但是CrossEntropyLoss是可以多维且每一维对应某一个类别的logit。
  • CrossEntropyLoss的target是LongTensor,表示是哪一类;但是BCE系列是0到1之间的FloatTensor
  • CrossEntropyLoss和BCE系列从数值上看除了0.5的情况下其他情况完全不一样。BCE系列的数值计算思路是target*log(logits)+(1-target)*log(1-logits);但是CrossEntropyLoss实际上是Softmax+NLLLoss, 最后数值计算思路变成-logits[sample_index][选中类别]+sum(exp(logits[sample_index][i]) for i in all),CE的推导可以参考信息熵 条件熵 交叉熵 联合熵 相对熵 KL散度 SCE MAE 互信息(信息增益)

来点代码:

import torch
from torch import nn
import mathloss_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_xprint(f'交叉熵手动计算loss{sample_index}:{sample_loss}')return sample_lossfor 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_classesself.a = a #两个超参数self.b = bself.cross_entropy = nn.CrossEntropyLoss()self.cross_entropy_none = nn.CrossEntropyLoss(reduction="none")self.eps = epsdef forward(self, raw_pred, labels):# CE 部分,正常的交叉熵损失ce = self.cross_entropy(raw_pred, labels)# RCEpred = 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 取 -4my_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 lossy_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 Fclass 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 resif __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

PyTorch二分类时BCELoss,CrossEntropyLoss,Sigmoid等的选择和使用 - 知乎

这篇关于pytorch中BCELoss、CrossEntropyLoss和NLLLoss的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/819193

相关文章

Pytorch介绍与安装过程

《Pytorch介绍与安装过程》PyTorch因其直观的设计、卓越的灵活性以及强大的动态计算图功能,迅速在学术界和工业界获得了广泛认可,成为当前深度学习研究和开发的主流工具之一,本文给大家介绍Pyto... 目录1、Pytorch介绍1.1、核心理念1.2、核心组件与功能1.3、适用场景与优势总结1.4、优

conda安装GPU版pytorch默认却是cpu版本

《conda安装GPU版pytorch默认却是cpu版本》本文主要介绍了遇到Conda安装PyTorchGPU版本却默认安装CPU的问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的... 目录一、问题描述二、网上解决方案罗列【此节为反面方案罗列!!!】三、发现的根本原因[独家]3.1 p

PyTorch中cdist和sum函数使用示例详解

《PyTorch中cdist和sum函数使用示例详解》torch.cdist是PyTorch中用于计算**两个张量之间的成对距离(pairwisedistance)**的函数,常用于点云处理、图神经网... 目录基本语法输出示例1. 简单的 2D 欧几里得距离2. 批量形式(3D Tensor)3. 使用不

PyTorch高级特性与性能优化方式

《PyTorch高级特性与性能优化方式》:本文主要介绍PyTorch高级特性与性能优化方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、自动化机制1.自动微分机制2.动态计算图二、性能优化1.内存管理2.GPU加速3.多GPU训练三、分布式训练1.分布式数据

判断PyTorch是GPU版还是CPU版的方法小结

《判断PyTorch是GPU版还是CPU版的方法小结》PyTorch作为当前最流行的深度学习框架之一,支持在CPU和GPU(NVIDIACUDA)上运行,所以对于深度学习开发者来说,正确识别PyTor... 目录前言为什么需要区分GPU和CPU版本?性能差异硬件要求如何检查PyTorch版本?方法1:使用命

pytorch自动求梯度autograd的实现

《pytorch自动求梯度autograd的实现》autograd是一个自动微分引擎,它可以自动计算张量的梯度,本文主要介绍了pytorch自动求梯度autograd的实现,具有一定的参考价值,感兴趣... autograd是pytorch构建神经网络的核心。在 PyTorch 中,结合以下代码例子,当你

在PyCharm中安装PyTorch、torchvision和OpenCV详解

《在PyCharm中安装PyTorch、torchvision和OpenCV详解》:本文主要介绍在PyCharm中安装PyTorch、torchvision和OpenCV方式,具有很好的参考价值,... 目录PyCharm安装PyTorch、torchvision和OpenCV安装python安装PyTor

pytorch之torch.flatten()和torch.nn.Flatten()的用法

《pytorch之torch.flatten()和torch.nn.Flatten()的用法》:本文主要介绍pytorch之torch.flatten()和torch.nn.Flatten()的用... 目录torch.flatten()和torch.nn.Flatten()的用法下面举例说明总结torch

使用PyTorch实现手写数字识别功能

《使用PyTorch实现手写数字识别功能》在人工智能的世界里,计算机视觉是最具魅力的领域之一,通过PyTorch这一强大的深度学习框架,我们将在经典的MNIST数据集上,见证一个神经网络从零开始学会识... 目录当计算机学会“看”数字搭建开发环境MNIST数据集解析1. 认识手写数字数据库2. 数据预处理的

Pytorch微调BERT实现命名实体识别

《Pytorch微调BERT实现命名实体识别》命名实体识别(NER)是自然语言处理(NLP)中的一项关键任务,它涉及识别和分类文本中的关键实体,BERT是一种强大的语言表示模型,在各种NLP任务中显著... 目录环境准备加载预训练BERT模型准备数据集标记与对齐微调 BERT最后总结环境准备在继续之前,确