nn.CrossEntropyLoss

import torch
import numpy as np
from torch.nn.functional import one_hot
from torch import nn

predicts = np.array(([
[-1.0606,  1.5613,  1.2007, -0.2481],
[-1.9652, -0.4367, -0.0645, -0.5104],
[ 0.1011, -0.5904,  0.0243,  0.1002]
]))
print("pred_shape:",predicts.shape)

label= torch.tensor([0,2,1])
#one_hot编码
label = one_hot(label,num_classes=4)
print("label:",label)
#使用softmax转化为概率值
print("softmax:",torch.softmax(torch.tensor(predicts),1))

#计算loss
#公式: -(1/n)*∑ ∑p(x)logq(x)    其中,q(x)是预测概率,p(x)实际概率
loss =-1/predicts.shape[0] * torch.sum(label*torch.log(torch.softmax(torch.tensor(predicts),1)))
print("loss:",loss)

#nn.CrossEntropyLoss
crit = nn.CrossEntropyLoss()
loss = crit(torch.tensor(predicts),torch.tensor([0,2,1]))
print("CrossEntropyLoss:",loss)


pred_shape: (3, 4)
label: tensor([[1, 0, 0, 0],
        [0, 0, 1, 0],
        [0, 1, 0, 0]])
softmax: tensor([[0.0376, 0.5172, 0.3606, 0.0847],
        [0.0603, 0.2780, 0.4034, 0.2583],
        [0.2919, 0.1462, 0.2703, 0.2916]], dtype=torch.float64)
loss: tensor(2.0373, dtype=torch.float64)
CrossEntropyLoss: tensor(2.0373, dtype=torch.float64)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值