问题 1
这是 Pytorch 文档中关于 MSELoss 的参考:https://pytorch.org/docs/stable/nn.html#torch.nn.MSELoss
Shape:
- Input: (N,∗) where * means, any number of additional dimensions
- Target: (N,∗), same shape as the input
因此,您需要扩展标签的尺寸:(32) -> (32,1),使用:torch.unsqueeze(labels, 1) 或 labels.view(-1,1)
https://pytorch.org/docs/stable/torch.html#torch.unsqueeze
torch.unsqueeze(input, dim, out=None) → 张量
返回一个新张量,尺寸为一,插入指定位置。
返回的张量与该张量共享相同的基础数据。
问题 2
查看您的代码后,我意识到您已将 size_average 参数添加到 MSELoss:
criterion = torch.nn.MSELoss(size_average=False)
size_average (bool, optional) – 已弃用(见减少)。默认情况下,损失是批次中每个损失元素的平均值。请注意,对于某些损失,每个样本有多个元素。如果字段 size_average 设置为 False,则将每个 minibatch 的损失相加。当 reduce 为 False 时忽略。默认值:真
这就是为什么 2 个计算值不匹配的原因。这是示例代码:
import torch
import torch.nn as nn
loss1 = nn.MSELoss()
loss2 = nn.MSELoss(size_average=False)
inputs = torch.randn(32, 1, requires_grad=True)
targets = torch.randn(32, 1)
output1 = loss1(inputs, targets)
output2 = loss2(inputs, targets)
output3 = torch.mean((inputs - targets) ** 2)
print(output1) # tensor(1.0907)
print(output2) # tensor(34.9021)
print(output3) # tensor(1.0907)