pytorch中交叉熵損失(nn.CrossEntropyLoss())的計算過程詳解
公式
首先需要了解CrossEntropyLoss的計算過程,交叉熵的函數(shù)是這樣的:

其中,其中yi表示真實的分類結(jié)果。這里只給出公式,關(guān)于CrossEntropyLoss的其他詳細細節(jié)請參照其他博文。
測試代碼(一維)
import torch
import torch.nn as nn
import math
criterion = nn.CrossEntropyLoss()
output = torch.randn(1, 5, requires_grad=True)
label = torch.empty(1, dtype=torch.long).random_(5)
loss = criterion(output, label)
print("網(wǎng)絡(luò)輸出為5類:")
print(output)
print("要計算label的類別:")
print(label)
print("計算loss的結(jié)果:")
print(loss)
first = 0
for i in range(1):
first = -output[i][label[i]]
second = 0
for i in range(1):
for j in range(5):
second += math.exp(output[i][j])
res = 0
res = (first + math.log(second))
print("自己的計算結(jié)果:")
print(res)

測試代碼(多維)
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("網(wǎng)絡(luò)輸出為3個5類:")
print(output)
print("要計算loss的類別:")
print(label)
print("計算loss的結(jié)果:")
print(loss)
first = [0, 0, 0]
for i in range(3):
first[i] = -output[i][label[i]]
second = [0, 0, 0]
for i in range(3):
for j in range(5):
second[i] += math.exp(output[i][j])
res = 0
for i in range(3):
res += (first[i] + math.log(second[i]))
print("自己的計算結(jié)果:")
print(res/3)

nn.CrossEntropyLoss()中的計算方法
注意:在計算CrossEntropyLosss時,真實的label(一個標量)被處理成onehot編碼的形式。
在pytorch中,CrossEntropyLoss計算公式為:

CrossEntropyLoss帶權(quán)重的計算公式為(默認weight=None):

以上這篇pytorch中交叉熵損失(nn.CrossEntropyLoss())的計算過程詳解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python?Pandas數(shù)據(jù)處理高頻操作詳解
這篇文章主要為大家整理了一些Python?Pandas數(shù)據(jù)處理高頻操作,文中的示例代碼講解詳細,對我們學習Python有一定的幫助,需要的可以參考一下2022-06-06
Python 相對路徑報錯:"No such file or 
如果你取相對路徑不是在主文件里,可能就會有相對路徑問題:"No such file or directory",由于python 的相對路徑,相對的都是主文件所以會出現(xiàn)Python 相對路徑報錯,今天小編給大家?guī)砹送昝澜鉀Q方案,感興趣的朋友一起看看吧2023-02-02
使用Python實現(xiàn)U盤數(shù)據(jù)自動拷貝
這篇文章主要為大家詳細介紹了如何使用Python實現(xiàn)U盤數(shù)據(jù)自動拷貝,即當電腦上有U盤插入時自動復制U盤內(nèi)的所有內(nèi)容,希望對大家有所幫助2025-02-02
Python接口自動化之淺析requests模塊post請求
這篇文章Python接口自動化之淺析requests模塊post請求,以下主要介紹requests模塊中的post請求的使用,post源碼,data、json參數(shù)應(yīng)用場景及實戰(zhàn)2021-08-08

