如图,上边的为真值,下边的为预测值,可见预测值都是在30左右

一直debug不出来。后来发现是loss处写错了

用的torch.nn.MSELoss(pred,target),其中pred的size是(batchsize,1), target的size是(batchsize),此时会有警告但不报错:

media/cfs/user/.pylib/lib/python3.6/site-packages/torch/nn/modules/loss.py:445: UserWarning: Using a target size (torch.Size([2560])) that is different to the input size (torch.Size([2560, 1])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size.
  return F.mse_loss(input, target, reduction=self.reduction)
/media/cfs/user/.pylib/lib/python3.6/site-packages/torch/nn/modules/loss.py:445: UserWarning: Using a target size (torch.Size([360])) that is different to the input size (torch.Size([360, 1])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size.
  return F.mse_loss(input, target, reduction=self.reduction)

因此需要把pred的1那维给去掉,用squeeze或者reshape都行

我们做个简单的实验。下图中的3.1375才是正确的结果(因为MSELoss是对所有样本的mse求均值)。而对target进行squeeze后,input和target的size不再相同,所得结果2.450也是错的

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐