nn.CrossEntropyLoss()

用於多分類,直接寫標籤序號就可以:0,1,2.

預測需要維度與標籤長度一致。

import torch
import torch.nn as nn
import math
criterion = nn.CrossEntropyLoss()
output = torch.randn(3, 5, requires_grad=True)
label = torch.empty(3, dtype=torch.long).random_(5)
loss = criterion(output, label)

print("網絡輸出爲3個5類:")
print(output)
print("要計算loss的類別:")
print(label)
print("計算loss的結果:")
print(loss)

預測代碼:log_softmax好像沒有歸一化,要不要好像沒區別

  output = model(img_arr)
        score = m_func.log_softmax(output, dim=1)
        _, match = torch.max(score.data, 1)


        index=match.item()
import torch
import torch.nn as nn
x_input=torch.randn(3,3)#隨機生成輸入 
print('x_input:\n',x_input) 
y_target=torch.tensor([1,2,0])#設置輸出具體值 print('y_target\n',y_target)

#計算輸入softmax,此時可以看到每一行加到一起結果都是1
softmax_func=nn.Softmax(dim=1)
soft_output=softmax_func(x_input)
print('soft_output:\n',soft_output)

#在softmax的基礎上取log
log_output=torch.log(soft_output)
print('log_output:\n',log_output)

#對比softmax與log的結合與nn.LogSoftmaxloss(負對數似然損失)的輸出結果,發現兩者是一致的。
logsoftmax_func=nn.LogSoftmax(dim=1)
logsoftmax_output=logsoftmax_func(x_input)
print('logsoftmax_output:\n',logsoftmax_output)

#pytorch中關於NLLLoss的默認參數配置爲:reducetion=True、size_average=True
nllloss_func=nn.NLLLoss()
nlloss_output=nllloss_func(logsoftmax_output,y_target)
print('nlloss_output:\n',nlloss_output)

#直接使用pytorch中的loss_func=nn.CrossEntropyLoss()看與經過NLLLoss的計算是不是一樣
crossentropyloss=nn.CrossEntropyLoss()
crossentropyloss_output=crossentropyloss(x_input,y_target)
print('crossentropyloss_output:\n',crossentropyloss_output)
發佈了2649 篇原創文章 · 獲贊 964 · 訪問量 524萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章