Pytorch 损失函数之nn.CrossEntropyLoss()、nn.NLLLoss()、 nn.LogSoftmax()

在pytorch中nn.CrossEntropyLoss()是nn.logSoftmax()和nn.NLLLoss()的整合,可以直接使用它来替换网络中的这两个操作。
This criterion combines :func:`nn.LogSoftmax` and :func:`nn.NLLLoss` in one single class。

下面是交叉熵计算公式:

`input` has to be a Tensor of size either :math:`(minibatch, C)` or
:math:`(minibatch, C, d_1, d_2, ..., d_K)`

我的理解是输入必须包含minibatch 和类别数,而target则是减少一个相应的C类别的维度。

如果给定了各个类别的权重,还要乘以权重,为一维权重。

损失函数中的weight为权重参数设置,若设置权重,则公式为:


例子
>>> loss = nn.CrossEntropyLoss()
>>> input = torch.randn(3, 5, requires_grad=True)
>>> target = torch.empty(3, dtype=torch.long).random_(5)
>>> output = loss(input, target)
>>> output.backward()

补充:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值