nn.CrossEntropyLoss()这个损失函数和我们普通说的交叉熵还是有些区别。
xx是模型生成的结果,classclass是数据对应的label
nn.CrossEntropyLoss()的使用方式参见如下代码
import torch
import torch.nn as nn
# 表示模型的输出output(B,C)格式,B是batch,C是类别
output = torch.randn(2, 3, requires_grad = True) #batch_size设置为2,3分类
# 表示数据的标签label(B)格式,B是batch,其中的数值是位于[0,C-1]
label = torch.empty(2, dtype=torch.long).random_(3) # 0 - 2, 任意选取一个分类
print(output)
'''
tensor([[-1.1313, 0.5944, -1.5735],
[ 1.2037, -1.0548, -0.9253]], requires_grad=True)
'''
print(label)#tensor([0, 2])
loss = nn.CrossEntropyLoss()
#先对每个训练样本求损失,而后再求平均损失
print ('loss :', loss(output, label))#loss : tensor(2.1565, grad_fn=<NllLossBackward>)