验证 CrossEntropyLoss 内部运算过程

## 验证 CrossEntropyLoss 内部运算过程
import torch
from torch.nn import CrossEntropyLoss
from torch.optim import SGD

# 假设三分类真实值real 和预测值pred
real = [0,1,1,2]
pred = [[0.7,0.2,0.1],
        [0.1,0.6,0.3],
        [0.1,0.6,0.3],
        [0.2,0.2,0.6]]
real = torch.tensor(real)
pred = torch.tensor(pred)

# 使用torch 内置模块计算
cel = CrossEntropyLoss()
print(cel(pred,real)) --> # 得出结果tensor(0.8312)


# 按自己理解计算,先把真实标签转化为one-hot编码,再乘以log(softmax(pred)),每个样本结果求和再求平均数
#1. 先真实标签one-hot化
def func(x):
    res = np.zeros(len(set(real.tolist())))
    res[x] = 1
    return res
real_ = torch.tensor(list(map(func,real)))
real_
'''
tensor([[1., 0., 0.],
        [0., 1., 0.],
        [0., 1., 0.],
        [0., 0., 1.]], dtype=torch.float64)
'''

#2. 将预测值转化为softmax值
pred_softmax = torch.softmax(pred,dim=1)
pred_softmax
'''
tensor([[0.4640, 0.2814, 0.2546],
        [0.2584, 0.4260, 0.3156],
        [0.2584, 0.4260, 0.3156],
        [0.2864, 0.2864, 0.4272]])
'''
#3. 计算交叉熵

-1*(torch.mv(real_[0].unsqueeze(dim=0).float(),torch.log(pred_softmax[0]).float())
+torch.mv(real_[1].unsqueeze(dim=0).float(),torch.log(pred_softmax[1]).float())
+torch.mv(real_[2].unsqueeze(dim=0).float(),torch.log(pred_softmax[2]).float())
+torch.mv(real_[3].unsqueeze(dim=0).float(),torch.log(pred_softmax[3]).float()))/4
# --> tensor([0.8312]) 与上述函数求出结果一样

posted @ 2022-02-09 09:40  旁人怎会懂  阅读(40)  评论(0编辑  收藏  举报