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