pytorch中交叉熵损失(nn.CrossEntropyLoss())的计算过程详解
作者:aift 时间:2021-06-03 09:28:09
公式
首先需要了解CrossEntropyLoss的计算过程,交叉熵的函数是这样的:
其中,其中yi表示真实的分类结果。这里只给出公式,关于CrossEntropyLoss的其他详细细节请参照其他博文。
测试代码(一维)
import torch
import torch.nn as nn
import math
criterion = nn.CrossEntropyLoss()
output = torch.randn(1, 5, requires_grad=True)
label = torch.empty(1, dtype=torch.long).random_(5)
loss = criterion(output, label)
print("网络输出为5类:")
print(output)
print("要计算label的类别:")
print(label)
print("计算loss的结果:")
print(loss)
first = 0
for i in range(1):
first = -output[i][label[i]]
second = 0
for i in range(1):
for j in range(5):
second += math.exp(output[i][j])
res = 0
res = (first + math.log(second))
print("自己的计算结果:")
print(res)
测试代码(多维)
import torch
import torch.nn as nn
import math
criterion = nn.CrossEntropyLoss()
output = torch.randn(3, 5, requires_grad=True)
label = torch.empty(3, dtype=torch.long).random_(5)
loss = criterion(output, label)
print("网络输出为3个5类:")
print(output)
print("要计算loss的类别:")
print(label)
print("计算loss的结果:")
print(loss)
first = [0, 0, 0]
for i in range(3):
first[i] = -output[i][label[i]]
second = [0, 0, 0]
for i in range(3):
for j in range(5):
second[i] += math.exp(output[i][j])
res = 0
for i in range(3):
res += (first[i] + math.log(second[i]))
print("自己的计算结果:")
print(res/3)
nn.CrossEntropyLoss()中的计算方法
注意:在计算CrossEntropyLosss时,真实的label(一个标量)被处理成onehot编码的形式。
在pytorch中,CrossEntropyLoss计算公式为:
CrossEntropyLoss带权重的计算公式为(默认weight=None):
来源:https://blog.csdn.net/ft_sunshine/article/details/92074842
标签:pytorch,交叉熵损失,nn.CrossEntropyLoss
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python数学建模StatsModels统计回归模型数据的准备
2021-10-08 09:19:24
![](https://img.aspxhome.com/file/2023/1/79511_0s.png)
Python线程池thread pool创建使用及实例代码分享
2022-02-26 00:43:35
![](https://img.aspxhome.com/file/2023/9/69569_0s.png)
python中下标和切片的使用方法解析
2022-10-26 07:14:52
CSS背景 background 图像属性解读
2008-08-01 18:19:00
Python torch.fft.rfft()函数用法示例代码
2022-02-15 02:03:36
用MSXML2.ServerXMLHTTP的setTimeouts属性解决并死问题
2010-03-02 20:21:00
SQL语句的执行原理分析
2012-01-29 18:17:36
asp实现将人民币数字改为大写
2008-05-21 14:08:00
asp.net 将一个图片以二进制值的形式存入Xml文件中的实例代码
2023-07-23 13:31:30
Entity Framework Core生成列并跟踪列记录
2023-07-01 07:06:46
利用Python实现绘制论文中的曲线图
2022-12-14 12:04:37
![](https://img.aspxhome.com/file/2023/9/78489_0s.png)
如何修改MySQL密码(方法大总结)
2009-11-18 11:07:00
解释FCKeditor样式的工作原理
2007-10-11 13:34:00
基于Python实现的扫雷游戏实例代码
2023-06-26 12:29:34
php常量详细解析
2023-11-20 14:24:40
从传文件功能看本地化
2009-12-29 13:03:00
Python实现实时显示进度条的六种方法
2022-03-27 02:09:35
![](https://img.aspxhome.com/file/2023/2/70112_0s.jpg)
用Python编写个解释器实现方法接受
2023-01-11 15:50:08
![](https://img.aspxhome.com/file/2023/5/65505_0s.png)
关于超级链接的一些问题
2007-12-07 14:00:00
![](https://img.aspxhome.com/file/UploadPic/200712/7/200712714819482s.jpg)
Python 装饰器代码解析
2022-06-29 20:48:01
![](https://img.aspxhome.com/file/2023/4/79764_0s.png)