CrossEntropyLoss in Pytorch

in mathematics

  • softmax function (normalized exponential function)
    softmax(Q) = \frac{e^{Q}}{\sum_i e^{Q_i}}

  • cross entropy
    H(P,Q) =- \sum_y P(y) \log{Q(y)}

in pytorch

  • NLLLoss
    L(P,Q) = - \sum_y P(y)Q(y)

  • cross entropy loss
    \begin{aligned} CrossEntropyLoss(P,Q) &= H(P, softmax(Q)) \\ &= - \sum_y P(y) \log (softmax(Q(y))) \\ &= NLLLoss(P, logSoftmax(Q)) \end{aligned}
    doc : This criterion combines nn.LogSoftmax() and nn.NLLLoss() in one single class.

import torch
import torch.nn.functional as F

output = torch.randn(3, 5, requires_grad=True)
target = torch.tensor([1, 0, 4])


y1 = F.cross_entropy(output,target)
y2 = F.nll_loss(F.log_softmax(output,dim=1), target)

# y1 == y2
print(y1)
print(y2)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 呆呆兽大危机 我来到了桧皮市,刚来到道馆前,只见上面贴了一个牌子,写着“本道馆关门”这五个大字。 ...
    小迦QAQ阅读 146评论 0 0
  • 人成长的代价是什么? 人成长的目的是什么? J先生正在被这些问题困扰,随着时间的流逝,曾经有几年对J先生来说成长似...
    笔冢客阅读 304评论 0 7
  • 偶尔熬夜看电影,偶尔懒床,这就是生活(PS:工地狗没有周末⁽⁽ଘ( ˊᵕˋ )ଓ⁾⁾)
    刘阿莫阅读 310评论 9 4