真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

pytorch中如何計(jì)算交叉熵?fù)p失-創(chuàng)新互聯(lián)

這篇文章將為大家詳細(xì)講解有關(guān)pytorch中如何計(jì)算交叉熵?fù)p失,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

麻江網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)建站!從網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、成都響應(yīng)式網(wǎng)站建設(shè)公司等網(wǎng)站項(xiàng)目制作,到程序開發(fā),運(yùn)營維護(hù)。創(chuàng)新互聯(lián)建站2013年開創(chuàng)至今到現(xiàn)在10年的時(shí)間,我們擁有了豐富的建站經(jīng)驗(yàn)和運(yùn)維經(jīng)驗(yàn),來保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選創(chuàng)新互聯(lián)建站。

公式

首先需要了解CrossEntropyLoss的計(jì)算過程,交叉熵的函數(shù)是這樣的:

pytorch中如何計(jì)算交叉熵?fù)p失

其中,其中yi表示真實(shí)的分類結(jié)果。這里只給出公式,關(guān)于CrossEntropyLoss的其他詳細(xì)細(xì)節(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("要計(jì)算label的類別:")
print(label)
print("計(jì)算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("自己的計(jì)算結(jié)果:")
print(res)

pytorch中如何計(jì)算交叉熵?fù)p失

測試代碼(多維)

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個(gè)5類:")
print(output)
print("要計(jì)算loss的類別:")
print(label)
print("計(jì)算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("自己的計(jì)算結(jié)果:")
print(res/3)

pytorch中如何計(jì)算交叉熵?fù)p失

nn.CrossEntropyLoss()中的計(jì)算方法

注意:在計(jì)算CrossEntropyLosss時(shí),真實(shí)的label(一個(gè)標(biāo)量)被處理成onehot編碼的形式。

在pytorch中,CrossEntropyLoss計(jì)算公式為:

pytorch中如何計(jì)算交叉熵?fù)p失

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

pytorch中如何計(jì)算交叉熵?fù)p失

關(guān)于“pytorch中如何計(jì)算交叉熵?fù)p失”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯(cuò),請把它分享出去讓更多的人看到。


新聞標(biāo)題:pytorch中如何計(jì)算交叉熵?fù)p失-創(chuàng)新互聯(lián)
鏈接分享:http://weahome.cn/article/decchc.html

其他資訊

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部