pytorch中使用nn.CrossEntropyLoss()创建出来的交叉熵损失函数计算损失默认是求平均值的,即多个样本输入后获取的是一个均值标量,而不是样本大小的向量。
net = nn.Linear(4, 2)
loss = nn.CrossEntropyLoss()
X = torch.rand(10, 4)
y = torch.ones(10, dtype=torch.long)
y_hat = net(X)
l = loss(y_hat, y)
print(l)
打印的结果:tensor(0.7075, grad_fn=<NllLossBackward0>)
以上是对10个样本做的均值的标量
net = nn.Linear(4, 2)
loss = nn.CrossEntropyLoss(reduction='none')
X = torch.rand(10, 4)
y = torch.ones(10, dtype=torch.long)
y_hat = net(X)
l = loss(y_hat, y)
print(l)
在构造CrossEntropyLoss时候加入 reduction='none',就把默认求平均取消掉了
打印结果:
tensor([0.6459, 0.7372, 0.6373, 0.6843, 0.6251, 0.6555, 0.5510, 0.7016, 0.6975,0.6849], grad_fn=<NllLossBackward0>)
以上是10个样本各自的loss值
上图是pytorch的CrossEntropyLoss的构造方法,默认是 reduction='mean'