pytorch损失函数

学习深度学习的过程中一直会遇到损失函数,均方损失函数、交叉熵损失函数、负对数似然损失函数
有些时候觉得有点不清晰,所以总结、梳理一下,加深自己的理解

MSELoss损失函数

# MSELoss有一个参数 reduction='sum' 求误差和
# reduction='mean', 求误差平均
import torch
mseLoss = torch.nn.MSELoss(reduction='sum')
a = torch.Tensor([[1,2], [2,3]])
b = torch.Tensor([[1,3], [2,4]])
loss = mseLoss(a,b)
loss
tensor(2.)

CrossEntropyLoss损失函数

CrossEntropyLoss的损失计算公式如下
l o s s ( x , c l a s s ) = l o g ( e x p ( x [ c l a s s ] j e x p ( x [ j ] ) ) loss(x,class)=-log(\frac{exp(x[class]}{\sum_j{exp(x[j])}})
公式其实就是先求向量的LogSoftmax,再找到样本正确类对应向量中的值,求一个相反数
如果是多个样本的话求和、求平均都可以
CrossEntropyLoss损失函数与MSELoss损失函数相比,其在误差大的情况下,参数变动的幅度越大
所以训练速度相比均方差损失函数要快。

#假设分类问题是二分类,矩阵a是对两个样本进行预测的结果
# CrossEntropyLoss有一个参数 reduction='sum' 求误差和
# reduction='mean', 求误差平均
crossLoss = torch.nn.CrossEntropyLoss(reduction='sum')
b = torch.LongTensor([0, 1])
loss = crossLoss(a, b)
loss
tensor(1.6265)
#先LogSoftmax,再找到样本正确类对应向量中的值,求一个相反数,最后求和
logSoftmax = torch.nn.LogSoftmax(dim=1)
aLogSoftmax = logSoftmax(a)
-aLogSoftmax[0][0] - aLogSoftmax[1][1]
tensor(1.6265)

NLLLoss损失函数

NLLLoss损失函数称为负对数似然损失函数,其实官方文档说明LogSoftmax+NLLLoss==CrossEntropyLoss
先LogSoftmax,再NLLLoss,两步操作就相当于一步CrossEntropyLoss操作

nllLoss = torch.nn.NLLLoss(reduction='sum')
softmax = torch.nn.LogSoftmax(dim=1)
#print (a)
aSoftmax = softmax(a)
#print (aSoftmax)
loss = nllLoss(aSoftmax, b)
loss
tensor(1.6265)
发布了176 篇原创文章 · 获赞 97 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/zycxnanwang/article/details/94465375