如何在PyTorch中计算输入和目标张量之间的交叉熵损失?
为了计算输入和目标(预测值和实际值)之间的交叉熵损失,我们应用函数 **CrossEntropyLoss()**。它可以从 **torch.nn** 模块访问。它创建一个衡量交叉熵损失的标准。它是 **torch.nn** 模块提供的损失函数的一种类型。
损失函数用于通过最小化损失来优化深度神经网络。**CrossEntropyLoss()** 在训练多类分类问题中非常有用。输入预计包含每个类别的未归一化分数。
目标张量可能包含范围在 **[0,C-1]** 内的类索引,其中 **C** 是类的数量或类概率。
语法
torch.nn.CrossEntropyLoss()
步骤
为了计算交叉熵损失,可以遵循以下步骤
导入所需的库。在以下所有示例中,所需的 Python 库是 **torch**。确保您已安装它。
import torch
创建输入和目标张量并打印它们。
input = torch.rand(3, 5) target = torch.empty(3, dtype = torch.long).random_(5)
创建一个标准来衡量交叉熵损失。
loss = nn.CrossEntropyLoss()
计算交叉熵损失并打印它。
output = loss(input, target) print('Cross Entropy Loss: ', output)
**注意** - 在以下示例中,我们使用随机数来生成输入和目标张量。因此,您可能会注意到这些张量的值不同。
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例 1
在这个示例中,我们计算输入和目标张量之间的交叉熵损失。这里我们以具有类索引的目标张量为例。
# Example of target with class indices import torch import torch.nn as nn input = torch.rand(3, 5) target = torch.empty(3, dtype = torch.long).random_(5) print(target) loss = nn.CrossEntropyLoss() output = loss(input, target) print('input: ', input) print('target: ', target) print('Cross Entropy Loss: ', output)
输出
tensor([2, 0, 4]) input: tensor([[0.2228, 0.2523, 0.9712, 0.7887, 0.2820], [0.7778, 0.4144, 0.8693, 0.1355, 0.3706], [0.0823, 0.5392, 0.0542, 0.0153, 0.8475]]) target: tensor([2, 0, 4]) Cross Entropy Loss: tensor(1.2340)
示例 2
在这个示例中,我们计算输入和目标张量之间的交叉熵损失。这里我们以具有类概率的目标张量为例。
# Example of target with class probabilities import torch import torch.nn as nn input = torch.rand(3, 5, requires_grad=True) target = torch.empty(3, dtype=torch.long).random_(5) print(target.size()) loss = nn.CrossEntropyLoss() output = loss(input, target) output.backward() print("Input:",input) print("Target:",target) print("Cross Entropy Loss:",output) print('Input grads: ', input.grad)
输出
torch.Size([3]) Input: tensor([[0.8671, 0.0189, 0.0042, 0.1619, 0.9805], [0.1054, 0.1519, 0.6359, 0.6112, 0.9417], [0.9968, 0.3285, 0.9185, 0.0315, 0.9592]], requires_grad=True) Target: tensor([1, 0, 4]) Cross Entropy Loss: tensor(1.8338, grad_fn=<NllLossBackward>) Input grads: tensor([[ 0.0962, -0.2921, 0.0406, 0.0475, 0.1078], [-0.2901, 0.0453, 0.0735, 0.0717, 0.0997], [ 0.0882, 0.0452, 0.0815, 0.0336, -0.2484]])
广告