pytorch 交叉熵损失函数计算过程

pytorch方法测试——损失函数(CrossEntropyLoss)_tmk_01的博客-CSDN博客_crossentropyloss weight

其中x[class]表示 类别对应预测正确的那个项的得分 

pytorch 交叉熵损失函数计算过程_第1张图片

 

单类

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("网络输出为5类:")
print(output)
print("要计算label的类别:")
print(label)
print("计算loss的结果:")
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))

myres = math.log(math.exp(-1*first) / second)
print("自己的计算结果:")
print(res)
print(myres)

多类 

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)

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("自己的计算结果:")
print(res/3)

a = torch.empty(1, dtype=torch.long).random_(5)

 

你可能感兴趣的:(算法,pytorch,深度学习,python)