Pytorch 損失函數之nn.CrossEntropyLoss()、nn.NLLLoss()、 nn.LogSoftmax()

在pytorch中nn.CrossEntropyLoss()是nn.logSoftmax()和nn.NLLLoss()的整合,可以直接使用它來替換網絡中的這兩個操作。
This criterion combines :func:`nn.LogSoftmax` and :func:`nn.NLLLoss` in one single class。

下面是交叉熵計算公式:

`input` has to be a Tensor of size either :math:`(minibatch, C)` or
:math:`(minibatch, C, d_1, d_2, ..., d_K)`

我的理解是輸入必須包含minibatch 和類別數,而target則是減少一個相應的C類別的維度。

如果給定了各個類別的權重,還要乘以權重,爲一維權重。

損失函數中的weight爲權重參數設置,若設置權重,則公式爲:



例子
>>> 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()

補充:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章