1. nn.MSELoss()
模型的预测值与标签的L2距离。一般用于回归问题。之所以不用于分类问题,可能原因为:使用sigmoid之后,函数形式不是凸函数 ,不容易求解 ,容易进入局部最优。
loss = nn.MSELoss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.randn(3, 5)
output = loss(input, target)
output.backward()
2. nn.BCELoss()
交叉熵损失函数,衡量两个分布之间的差异,一般用于分类问题。输入的x值需先经过sigmoid压缩到(0,1)之间。标签形式为[0, 0, 1], [0, 1, 1]等,各个类别预测概率独立,类与类之间不互斥,可见不仅能用于二分类问题,也能用于多标签分类问题。
m = nn.Sigmoid()
loss = nn.BCELoss()
input = torch.randn(3, requires_grad=True)
target = torch.empty(3).random_(2)
output = loss(m(input), target)
output.backward()
3. nn.BCEWithLogitsLoss()
交叉熵损失函数, 与nn.BCELoss()不同的是网络的输出无需用sigmoid压缩,函数内部整合了nn.sigmoid()和nn.BCELoss(),并且使用log-sum-exp trick提高了数值稳定性。同样可用于二分类及多标签分类。
这里简单介绍一下log-sum-exp trick:
原始的log-sum-exp公式为:
y = l o g ∑ i e x i y = log\sum_{i}^{}e^{x_{i}} y=logi∑exi
在 x i x_{i}