Pytorch中的损失函数

分类损失

二分类

torch.nn.BCELoss(reduction)

形状:

  • Input:任意形状
  • Target:任意形状,和输入形状一样
  • Output: 如果reduction is None,形状和target的形状一样,否则是标量

torch.nn.BCEWithLogitsLoss()

形状同上。BCEWithLogitsLoss是将Sigmoid和BCELoss合成一步,再对output和target进行BCELoss计算。
参考代码

import torch
import random
from torch import nn

random.seed(0)
torch.manual_seed(0)
input = torch.randn(3, 3)
out = torch.sigmoid(input)
target = torch.FloatTensor([[0, 1, 1],
                            [0, 0, 1],
                            [1, 0, 1]])
l1 = nn.BCELoss()
loss1 = l1(out, target) 
print(loss1)  # tensor(1.1805)

input2 = torch.FloatTensor([[1.5410, -0.2934, -2.1788],
                            [0.5684, -1.0845, -1.3986],
                            [0.4033,  0.8380, -0.7193]])
l2 = nn.BCEWithLogitsLoss()
loss2 = l2(input2, target)
print(loss2)  # tensor(1.1805)
# 可以发现loss1和loss2相等

多分类

torch.nn.Softmax()

S o f t m a x ( x i ) = e x p ( x i ) ∑ j e x p ( x j ) Softmax(x_i)=\frac{exp(x_i)}{\sum_j{exp(x_j)}} Softmax(xi)=jexp(xj)exp(xi)

torch.nn.LogSoftmax()

L o g S o f t m a x ( x i ) = l o g ( e x p ( x i ) ∑ j e x p ( x j ) ) LogSoftmax(x_i)=log(\frac{exp(x_i)}{\sum_j{exp(x_j)}}) LogSoftmax(xi)=log(jexp(xj)exp(xi))

torch.nn.CrossEntropyLoss(weight=None,size_average=True)

等价于LogSoftmx+NLLLoss。
如果提供的话,weight参数应该是一个1-D的tensor,里面的值对应类别的权重。当训练集样本不均衡的话,使用这个参数非常有用。如果给定的话,长度必须为nclasses。
输入应包含每个类别的原始、非标准化分数。
形状:

  • Input:Shape(C),(N,C) or (N,C,d1,d2,...dK)
  • Target:如果包含的是类别索引,则shape(),(N) or (N,d1,d2,...,dK),其中每一个值都必须介于[0,C);如果包含的是概率,形状要和输入的形状相同,每个值都介于[0,1]
  • Output: 如果reduction is None,形状和target的形状一样,否则是标量
loss = nn.CrossEntropyLoss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.empty(3, dtype=torch.long).random_(5)
output = loss(input, target)
output.backward()
# Example of target with class probabilities
input = torch.randn(3, 5, requires_grad=True)
target = torch.randn(3, 5).softmax(dim=1)
output = loss(input, target)
output.backward()

torch.nn.NLLLoss(weight=None,size_average=True,reduction=‘mean’)

用于训练一个n类分类器。通过前向调用给出的输入预计将包含每个类的对数概率。(通过在网络的最后一层添加LogSoftmax层,可以轻松获得神经网络中的对数概率。可以再将此对数概率作为NLLoss的输入x。)
如果提供的话,weight参数应该是一个1-D的tensor,里面的值对应类别的权重。当训练集样本不均衡的话,使用这个参数非常有用。如果给定的话,长度必须为nclasses。
size_average (bool, optional) – 默认情况下,会计算mini-batch loss的平均值。然而,如果size_average=False那么将会把mini-batch中所有样本的loss累加起来。
形状:

  • Input:(N,C),C是类别的个数,或(N,C,d1,d2,...,dk)
  • Target:(N),或(N,d1,d2,...,dk) target中每个值的大小满足 0 < = t a r g e t s [ i ] < = C − 1 0<=targets[i]<=C-1 0<=targets[i]<=C1
  • Output: 当reduction=None时,损失函数的计算方式如下:
    l ( x , y ) = L = { l 1 , . . . , l N } l n = − w y n x n , y n l(x,y)=L=\left\{l_1,...,l_N\right\} \newline l_n=-w_{y_n}x_{n,y_n} l(x,y)=L={l1,...,lN}ln=wynxn,yn
    当reduction不为None时,损失函数的计算方式如下:
    l ( x , y ) = { ∑ n = 1 N l n ∑ n = 1 N w y n , i f r e d u c t i o n = ′ m e a n ′ ; ∑ n = 1 N l n , i f r e d u c t i o n = ′ s u m ′ ; l(x,y)=\begin{cases} \sum_{n=1}^N \frac{l_n}{\sum_{n=1}^Nw_{y_n}} &,if \quad reduction='mean';\\ \sum_{n=1}^N{l_n} &,if\quad reduction='sum'; \end{cases} l(x,y)={n=1Nn=1Nwynlnn=1Nln,ifreduction=mean;,ifreduction=sum;
    如果reduction is none,输出的形状时(N) or (N,d1,d2,...,dK);如果reduction is not None,输出的是一个标量

回归损失

torch.nn.L1Loss(size_average=True)

创建一个衡量输入x和目标y之间差的绝对值的平均值的标准。
l o s s ( x , y ) = 1 / n ∑ ∣ x i − y i ∣ loss(x,y)=1/n\sum{|x_i-y_i|} loss(x,y)=1/nxiyi

  • 输入:x和y可以是任意形状,每个包含n个元素
  • 输出:维度为0的张量,例如:tensor(1.0379)
  • 如果在创建L1Loss实例的时候在构造函数中传入size_average=False,那么求出来的绝对值的和不会除以n
  • 对n个元素对应的差值的绝对值求和,得出来的结果除以n
  • 举例:
loss = nn.L1Loss()
input = torch.randn(3, 5, 4, requires_grad=True)
target = torch.randn(3, 5, 4)
output = loss(input, target)
print(output)#tensor(1.0379, grad_fn=<L1LossBackward0>)

torch.nn.MSELoss(size_average=True)

创建一个衡量输入x和目标y之间均方误差标准。
l o s s ( x , y ) = 1 / n ∑ ( x i − y i ) 2 loss(x,y)=1/n\sum{(x_i-y_i)^2} loss(x,y)=1/nxiyi2
其余用法同torch.nn.L1Loss()。

参考链接

https://pytorch.org/docs/stable/generated/torch.nn.BCEWithLogitsLoss.html#torch.nn.BCEWithLogitsLoss
https://pytorch-cn.readthedocs.io/zh/latest/package_references/torch-nn/#loss-functions

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值