pytorch loss function 总结

最近看了下 PyTorch 的损失函数文档,整理了下自己的理解,重新格式化了公式如下,以便以后查阅。

值得注意的是,很多的 loss 函数都有 size_averagereduce 两个布尔类型的参数,需要解释一下。因为一般损失函数都是直接计算 batch 的数据,因此返回的 loss 结果都是维度为 (batch_size, ) 的向量。

  • 如果 reduce = False,那么 size_average 参数失效,直接返回向量形式的 loss;
  • 如果 reduce = True,那么 loss 返回的是标量
    • 如果 size_average = True,返回 loss.mean();
    • 如果 size_average = True,返回 loss.sum();

所以下面讲解的时候,一般都把这两个参数设置成 False,这样子比较好理解原始的损失函数定义。

下面是常见的损失函数。

nn.L1Loss

loss(xi,yi)=|xiyi| loss ( x i , y i ) = | x i − y i |

这里表述的还是不太清楚,其实要求 x x y y 的维度要一样(可以是向量或者矩阵),得到的 loss 维度也是对应一样的。这里用下标 i i 表示第 i 个元素。

loss_fn = torch.nn.L1Loss(reduce=False, size_average=False)
input = torch.autograd.Variable(torch.randn(3,4))
target = torch.autograd.Variable(torch.randn(3,4))
loss = loss_fn(input, target)
print(input); print(target); print(loss)
print(input.size(), target.size(), loss.size())

nn.SmoothL1Loss

也叫作 Huber Loss,误差在 (-1,1) 上是平方损失,其他情况是 L1 损失。

loss(xi,yi)={12(xiyi)2|xiyi|12,if |xiyi|<1otherwise loss ( x i , y i ) = { 1 2 ( x i − y i ) 2 if  | x i − y i | < 1 | x i − y i | − 1 2 , otherwise

这里很上面的 L1Loss 类似,都是 element-wise 的操作,下标 i i x 的第 i i 个元素。

loss_fn = torch.nn.SmoothL1Loss(reduce=False, size_average=False)
input = torch.autograd.Variable(torch.randn(3,4))
target = torch.autograd.Variable(torch.randn(3,4))
loss = loss_fn(input, target)
print(input); print(target); print(loss)
print(input.size(), target.size(), loss.size())

nn.MSELoss

均方损失函数,用法和上面类似,这里 loss, x, y 的维度是一样的,可以是向量或者矩阵,i 是下标。

loss(xi,yi)=(xiyi)2 loss ( x i , y i ) = ( x i − y i ) 2

loss_fn = torch.nn.MSELoss(reduce=False, size_average=False)
input = torch.autograd.Variable(torch.randn(3,4))
target = torch.autograd.Variable(torch.randn(3,4))
loss = loss_fn(input, target)
print(input); print(target); print(loss)
print(input.size(), target.size(), loss.size())

nn.BCELoss

二分类用的交叉熵,用的时候需要在该层前面加上 Sigmoid 函数。交叉熵的定义参考 wikipedia 页面: Cross Entropy

因为离散版的交叉熵定义是 H(p,q)=ipilogqi H ( p , q ) = − ∑ i p i log ⁡ q i ,其中 p,q p , q 都是向量,且都是概率分布。如果是二分类的话,因为只有正例和反例,且两者的概率和为 1,那么只需要预测一个概率就好了,因此可以简化成

loss(xi,yi)=wi[yilogxi+(1yi)log(1xi)] loss ( x i , y i ) = − w i [ y i log ⁡ x i + ( 1 − y i ) log ⁡ ( 1 − x i ) ]
注意这里 x,y x , y 可以是向量或者矩阵, i i 只是下标;xi 表示第 i i 个样本预测为 正例 的概率,yi 表示第 i i 个样本的标签,wi 表示该项的权重大小。可以看出,loss, x, y, w 的维度都是一样的。

import torch.nn.functional as F
loss_fn = torch.nn.BCELoss(reduce=False, size_average=False)
input = Variable(torch.randn(3, 4))
target = Variable(torch.FloatTensor(3, 4).random_(2))
loss = loss_fn(F.sigmoid(input), target)
print(input); print(target); print(loss)

这里比较奇怪的是,权重的维度不是 2,而是和 x, y 一样,有时候遇到正负例样本不均衡的时候,可能要多写一句话

class_weight = Variable(torch.FloatTensor([1, 10])) # 这里正例比较少,因此权重要大一些
target = Variable(torch.FloatTensor(3, 4).random_(2))
weight = class_weight[target.long()] # (3, 4)
loss_fn = torch.nn.BCELoss(weight=weight, reduce=False, size_average=False)
# balabala...

其实这样子做的话,如果每次 batch_size 长度不一样,只能每次都定义 loss_fn 了,不知道有没有更好的解决方案。

nn.BCEWithLogitsLoss

上面的 nn.BCELoss 需要手动加上一个 Sigmoid 层,这里是结合了两者,这样做能够利用 log_sum_exp trick,使得数值结果更加稳定(numerical stability)。建议使用这个损失函数。

值得注意的是,文档里的参数只有 weight, size_average 两个,但是实际测试 reduce 参数也是可以用的。此外两个损失函数的 target 要求是 FloatTensor,而且不一样是只能取 0, 1 两种值,任意值应该都是可以的。

nn.CrossEntropyLoss

多分类用的交叉熵损失函数,用这个 loss 前面不需要加 Softmax 层。

这里损害函数的计算,按理说应该也是原始交叉熵公式的形式,但是这里限制了 target 类型为 torch.LongTensr,而且不是多标签意味着标签是 one-hot 编码的形式,即只有一个位置是 1,其他位置都是 0,那么带入交叉熵公式中化简后就成了下面的简化形式。参考 cs231n 作业里对 Softmax Loss 的推导。

loss(x,label)=wlabellogexlabelNj=1exj=wlabel[xlabel+logj=1Nexj] loss ( x , label ) = − w label log ⁡ e x label ∑ j = 1 N e x j = w label [ − x label + log ⁡ ∑ j = 1 N e x j ]

这里的 xRN x ∈ R N ,是没有经过 Softmax 的激活值, N N x 的维度大小(或者叫特征维度); label[0,C1] label ∈ [ 0 , C − 1 ] 是标量,是对应的标签,可以看到两者维度是不一样的。C 是要分类的个数。 wRC w ∈ R C 是维度为 C C 的向量,表示标签的权重,样本少的类别,可以考虑把权重设置大一点。

weight = torch.Tensor([1,2,1,1,10])
loss_fn = torch.nn.CrossEntropyLoss(reduce=False, size_average=False, weight=weight)
input = Variable(torch.randn(3, 5)) # (batch_size, C)
target = Variable(torch.FloatTensor(3).random_(5))
loss = loss_fn(input, target)
print(input); print(target); print(loss)

nn.NLLLoss

用于多分类的负对数似然损失函数(Negative Log Likelihood)

loss(x,label)=xlabel

在前面接上一个 nn.LogSoftMax 层就等价于交叉熵损失了。事实上,nn.CrossEntropyLoss 也是调用这个函数。注意这里的 xlabel x label 和上个交叉熵损失里的不一样(虽然符号我给写一样了),这里是经过 logSoftMax logSoftMax 运算后的数值,

nn.NLLLoss2d

和上面类似,但是多了几个维度,一般用在图片上。现在的 pytorch 版本已经和上面的函数合并了。

  • input, (N, C, H, W)
  • target, (N, H, W)

比如用全卷积网络做 Semantic Segmentation 时,最后图片的每个点都会预测一个类别标签。

nn.KLDivLoss

KL 散度,又叫做相对熵,算的是两个分布之间的距离,越相似则越接近零。

loss(x,y)=1Ni=1N[yi(logyixi)] loss ( x , y ) = 1 N ∑ i = 1 N [ y i ∗ ( log ⁡ y i − x i ) ]

注意这里的 xi x i log log 概率,刚开始还以为 API 弄错了。

nn.MarginRankingLoss

评价相似度的损失

loss(x1,x2,y)=max(0,y(x1x2)+margin) loss ( x 1 , x 2 , y ) = max ( 0 , − y ∗ ( x 1 − x 2 ) + margin )

这里的三个都是标量,y 只能取 1 或者 -1,取 1 时表示 x1 比 x2 要大;反之 x2 要大。参数 margin 表示两个向量至少要相聚 margin 的大小,否则 loss 非负。默认 margin 取零。

nn.MultiMarginLoss

多分类(multi-class)的 Hinge 损失,

loss(x,y)=1Ni=1,iyNmax(0,(marginxy+xi)p) loss ( x , y ) = 1 N ∑ i = 1 , i ≠ y N max ( 0 , ( margin − x y + x i ) p )

其中 1yN 1 ≤ y ≤ N 表示标签, p p 默认取 1,margin 默认取 1,也可以取别的值。参考 cs231n 作业里对 SVM Loss 的推导。

nn.MultiLabelMarginLoss

多类别(multi-class)多分类(multi-classification)的 Hinge 损失,是上面 MultiMarginLoss 在多类别上的拓展。同时限定 p = 1,margin = 1.

loss(x,y)=1Ni=1,iyjnj=1yj0[max(0,1(xyjxi))] loss ( x , y ) = 1 N ∑ i = 1 , i ≠ y j n ∑ j = 1 y j ≠ 0 [ max ( 0 , 1 − ( x y j − x i ) ) ]

这个接口有点坑,是直接从 Torch 那里抄过来的,见 MultiLabelMarginCriterion 的描述。而 Lua 的下标和 Python 不一样,前者的数组下标是从 1 开始的,所以用 0 表示占位符。有几个坑需要注意,

  1. 这里的 x,y x , y 都是大小为 N N 的向量,如果 y 不是向量而是标量,后面的 j ∑ j 就没有了,因此就退化成上面的 MultiMarginLoss.
  2. 限制 y y 的大小为 N N ,是为了处理多标签中标签个数不同的情况,用 0 表示占位,该位置和后面的数字都会被认为不是正确的类。如 y=[5,3,0,0,4] 那么就会被认为是属于类别 5 和 3,而 4 因为在零后面,因此会被忽略。
  3. 上面的公式和说明只是为了和文档保持一致,其实在调用接口的时候,用的是 -1 做占位符,而 0 是第一个类别。

举个梨子,

import torch
loss = torch.nn.MultiLabelMarginLoss()
x = torch.autograd.Variable(torch.FloatTensor([[0.1, 0.2, 0.4, 0.8]]))
y = torch.autograd.Variable(torch.LongTensor([[3, 0, -1, 1]]))
print loss(x, y) # will give 0.8500

按照上面的理解,第 3, 0 个是正确的类,1, 2 不是,那么,

loss=14i=1,2j=3,0[max(0,1(xjxi))]=14[(1(0.80.2))+(1(0.10.2))+(1(0.80.4))+(1(0.10.4))]=14[0.4+1.1+0.6+1.3]=0.85 loss = 1 4 ∑ i = 1 , 2 ∑ j = 3 , 0 [ max ( 0 , 1 − ( x j − x i ) ) ] = 1 4 [ ( 1 − ( 0.8 − 0.2 ) ) + ( 1 − ( 0.1 − 0.2 ) ) + ( 1 − ( 0.8 − 0.4 ) ) + ( 1 − ( 0.1 − 0.4 ) ) ] = 1 4 [ 0.4 + 1.1 + 0.6 + 1.3 ] = 0.85

*注意这里推导的第二行,我为了简短,都省略了 max(0, x) 符号。

nn.SoftMarginLoss

多标签二分类问题,这 N N 项都是二分类问题,其实就是把 N 个二分类的 loss 加起来,化简一下。其中 y y 只能取 1,1 1 , − 1 两种,代表正类和负类。和下面的其实是等价的,只是 y y 的形式不同。

loss(x,y)=i=1Nlog(1+eyixi) loss ( x , y ) = ∑ i = 1 N log ⁡ ( 1 + e − y i x i )

nn.MultiLabelSoftMarginLoss

上面的多分类版本,根据最大熵的多标签 one-versue-all 损失,其中 y y 只能取 1,0 1 , 0 两种,代表正类和负类。

loss(x,y)=i=1N[yilogexi1+exi+(1yi)log11+exi] loss ( x , y ) = − ∑ i = 1 N [ y i log ⁡ e x i 1 + e x i + ( 1 − y i ) log ⁡ 1 1 + e x i ]

nn.CosineEmbeddingLoss

余弦相似度的损失,目的是让两个向量尽量相近。注意这两个向量都是有梯度的。

loss(x,y)={1cos(x,y)max(0,cos(x,y)+margin)if if y==1y==1 loss ( x , y ) = { 1 − cos ⁡ ( x , y ) if  y == 1 max ( 0 , cos ⁡ ( x , y ) + margin ) if  y == − 1

margin 可以取 [1,1] [ − 1 , 1 ] ,但是比较建议取 0-0.5 较好。

nn.HingeEmbeddingLoss

不知道做啥用的。另外文档里写错了, x,y x , y 的维度应该是一样的。

loss(x,y)=1N{ximax(0,marginxi)if if yi==1yi==1 loss ( x , y ) = 1 N { x i if  y i == 1 max ( 0 , margin − x i ) if  y i == − 1

nn.TripleMarginLoss

L(a,p,n)=1N(i=1Nmax(0, d(ai,pi)d(ai,ni)+margin)) L ( a , p , n ) = 1 N ( ∑ i = 1 N max ( 0 ,   d ( a i , p i ) − d ( a i , n i ) + margin ) )
其中 d(xi,yi)=xiyi22 d ( x i , y i ) = ‖ x i − y i ‖ 2 2

  • 112
    点赞
  • 413
    收藏
    觉得还不错? 一键收藏
  • 15
    评论
In PyTorch, `loss.item()` is a method that returns the scalar value of a loss tensor. During training of a neural network, we typically compute the loss function on a batch of input data and corresponding targets. The loss function is a scalar value that measures how well the network is performing on the given batch. In PyTorch, the loss function is typically defined as a tensor, and we can use the `loss.item()` method to get the scalar value of the tensor. For example: ``` import torch.nn.functional as F import torch.optim as optim # Define the model class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.fc1 = nn.Linear(10, 5) self.fc2 = nn.Linear(5, 1) def forward(self, x): x = F.relu(self.fc1(x)) x = self.fc2(x) return x model = MyModel() optimizer = optim.SGD(model.parameters(), lr=0.1) # Loop over the training data for input, target in train_set: optimizer.zero_grad() output = model(input) loss = F.mse_loss(output, target) loss.backward() optimizer.step() # Get the scalar value of the loss tensor print(loss.item()) ``` In this example, we define a simple neural network `MyModel` and an optimizer `optim.SGD` to update the model's weights. During training, we compute the mean squared error (MSE) loss between the network's output and the target values. We then call `loss.item()` to get the scalar value of the loss tensor and print it to the console. Note that `loss.item()` returns a Python float, not a PyTorch tensor. This can be useful when we want to use the loss value for logging or other purposes outside of PyTorch computations.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值