Loss总结
L1Loss
mean absolute error

默认reduction参数为mean,是对所有的元素进行平均。

MSELoss

默认reduction参数为mean。除了使用MSE计算loss,其他的与L1Loss一样。
NLLLoss
negative log likelihood loss,用于多分类问题

在计算时,对于每个batch的 ln,只使用xn中与yn相对应的元素进行计算。减小loss以为这相对于元素增大,由于是经过softmax层的,代表其他类的元素值下降。
- 输入
- x: size = (batch,class,* ), x储存每个类的log-probabilities,在神经网络添加LogSoftmax层
- y:size = (batch,* )
- 参数
- weight:1D Tensor,每个类的weight
- ignore_index:忽略类的index
- reduction:'mean’和‘sum’是标量,对所有元素进行mean或者sum
CrossEntropyLoss
结合了LogSoftmax和NLLLoss
输入和NLLLoss一样,参数也相同。
BCELoss
Binary Cross Entropy

- 输入
- x:size = (N,*),由于是2分类问题,所以没有类的信息,神经网络的最后一层应是Sigmoid,将x归入[0,1]
- y:size = (N,*),元素非0即1
- 参数
- reduction
- weight:下面代码实验weight的选取
import torch.nn as nn
import torch
m = nn.Sigmoid()
input = torch.randn(4, 5, requires_grad=True)
target = torch.empty(4, 5).random_(2)
input = m(input)
loss1 = nn.BCELoss(reduction='none')
output1 = loss1(input, target)
print("output1:\n", output1)
#w2 = torch.empty(4).random_(2)
#loss2 = nn.BCELoss(reduction='none', weight=w2)
#output2 = loss2(input, target)
#print(w2, output2)
w3 = torch.empty(4, 1).random_(2)
loss3 = nn.BCELoss(reduction='none', weight=w3)
output3 = loss3(input, target)
print("w3:\n", w3,

本文详细总结了PyTorch中的几种损失函数,包括L1Loss、MSELoss、NLLLoss、CrossEntropyLoss、BCELoss和BCEWithLogitsLoss,以及它们在深度学习和神经网络中的应用和差异。
最低0.47元/天 解锁文章
364

被折叠的 条评论
为什么被折叠?



