Pytorch CrossEntropyLoss 用例
交叉熵计算损失
import torch
loss_func = torch.nn.CrossEntropyLoss()
v1 = torch.tensor([[0.1, 0.7, 0.2]])
v2 = torch.tensor([[0.2, 0.3, 0.5]])
v3 = torch.tensor([[0.8, 0.1, 0.1]])
t1 = torch.tensor([0], dtype=torch.long)
t3 = torch.tensor([2], dtype=torch.long)
loss11 = loss_func(v1, t1)
loss12 = loss_func(v2, t1)
loss13 = loss_func(v3, t1)
loss31 = loss_func(v1, t3)
loss32 = loss_func(v2, t3)
loss33 = loss_func(v3, t3)
print('loss11', loss11)
print('loss12', loss12)
print('loss13', loss13)
print('loss31', loss31)
print('loss32', loss32)
print('loss33', loss33)
输出
loss11 tensor(1.3679)
loss12 tensor(1.2398)
loss13 tensor(0.6897)
loss31 tensor(1.2679)
loss32 tensor(0.9398)
loss33 tensor(1.3897)