nn.CrossEntropyLoss()這個損失函數和我們普通說的交叉熵還是有些區別。
$x$是模型生成的結果,$class$是數據對應的label
$loss(x,class)=-log(\frac{exp(x[class])}{\sum_j exp(x[j])})=-x[class]+log(\sum_j exp(x[j]))$
nn.CrossEntropyLoss()的使用方式參見如下代碼
import torch import torch.nn as nn # 表示模型的輸出output(B,C)格式,B是batch,C是類別 output = torch.randn(2, 3, requires_grad = True) #batch_size設置為2,3分類 # 表示數據的標簽label(B)格式,B是batch,其中的數值是位於[0,C-1] label = torch.empty(2, dtype=torch.long).random_(3) # 0 - 2, 任意選取一個分類 print(output) ''' tensor([[-1.1313, 0.5944, -1.5735], [ 1.2037, -1.0548, -0.9253]], requires_grad=True) ''' print(label)#tensor([0, 2]) loss = nn.CrossEntropyLoss() #先對每個訓練樣本求損失,而后再求平均損失 print ('loss :', loss(output, label))#loss : tensor(2.1565, grad_fn=<NllLossBackward>)