首页 > 技术文章 > pytorch中常用损失函数

foghorn 2021-09-13 16:03 原文

LogSoftmax(dim=None)

对n维输入张量做softmax操作并取对数。

\[LogSoftmax(x_{i})=log(\frac{exp(x_{i})}{\sum_{j}exp(x_{j})}) \]

shape

  • input(*): *代表任意的维度
  • output(*): 和输入维度相同

parameters

  • dim(int): 维度为dim的张量

return

返回值在[-inf, 0)之间

NLLLoss()

函数签名

NLLLoss(weight=None, size_average=None, ignore_index=-100, reduce=None, reduction='mean')

具体含义

  • 负对数似然损失。用作带有\(C\)个类别的分类问题的损失函数。如果提供参数weight,则weight应该是1D的张量,其中每个元素表示对应类别的权重,适用于类别不平衡的情况。
  • 输入的维度:(minibatch, C)
  • 目标维度(真实标签):(N)
  • 在使用NLLLoss()之前需要将输入数据做Softmax()处理,将输入映射到(0, 1)之间

CrossEntropyLoss()

函数签名

CrossEntropyLoss(weight=None, size_average=None, ignore_index=-100, reduce=None, reduction='mean')

具体含义

  • 是LogSoftmax()和NLLLoss()的结合,即先对输入数据做LogSoftmax处理,再做NLLLoss处理
  • 输入维度: (minibatch, C)
  • 目标维度(真实标签):(N)

\[loss(x,class)=-log(\frac{exp(x[class])}{\sum_{j}exp(x[j])}) \]

举例

loss = nn.CrossEntropyLoss()
input = torch.randn(3, 5, required_grad=True)  #shape: (3, 5)
target = torch.empty(3, dtype=torch.long).random_(5)  #shape: (3,),其中每个元素是其类别编号
output = loss(input, target)
output.backward()

推荐阅读