CrossEntropyLoss损失函数的计算过程

本文展示了在PyTorch中,使用nn.CrossEntropyLoss和分开使用nn.logSoftmax结合nn.NLLLoss计算损失函数得到相同结果的示例。通过创建随机张量并设定标签,证明了两种方法的等价性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CrossEntropyLoss = nn.logSoftmax()+nn.NLLLoss()

以下代码使用nn.CrossEntropyLoss和使用nn.logSoftmax()+nn.NLLLoss()分别求损失,根据最后的输出显示二者的效果相同

import torch
import torch.nn as nn
criterion = nn.CrossEntropyLoss()
output = torch.randn(3, 5, requires_grad=True)
print(f'output:{output}')
soft_max = nn.Softmax(dim=1)
output_soft = torch.log(soft_max(output))  # 进行log(softmax)
# output_soft:tensor([[-1.0698, -3.3372, -2.8469, -1.2050, -1.3331],
#         [-2.8625, -1.7787, -0.7658, -1.9911, -1.7573],
#         [-0.8101, -1.7529, -2.3501, -3.0553, -1.4295]], grad_fn=<LogBackward0>)
# loss_nll =(-1.0698 + -1.0698 + -1.7529) / 3 = 1.962  因为labels是[0,2,1], 即第一行取位置0,第二行取位置2,第三行取位置1
print(f'output_soft:{output_soft}')
nn_loss = nn.NLLLoss()
labels = torch.tensor([0,2,1])
loss_nll = nn_loss(output_soft, labels)     # 进行nllloss
l1 = loss_nll.detach().numpy()
l2 = criterion(output, labels).detach().numpy() # 进行CrossEntropyLoss
print(l1 == l2) # True



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值