我想用 PyTorch 进行一些神经网络实验,但一个最小的测试案例却给出了错误的答案。该测试案例设置了一个简单的具有两个输入变量和一个输出变量的神经网络,输出变量只是输入的总和,并尝试将其作为回归问题进行学习;我期望它能收敛到均方误差为零,但实际上它收敛到了0.165。这可能是由于警告消息中提到的问题引起的;我该如何解决这个问题呢?
代码:
输出:
trainingC:\Users\russe\Anaconda3\envs\torch2\lib\site-packages\torch\nn\modules\loss.py:445: UserWarning: Using a target size (torch.Size([100])) that is different to the input size (torch.Size([100, 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) 50 0.167574 100 0.165108 150 0.165070 200 0.165052 250 0.165039 300 0.165028 350 0.165020 400 0.165013 450 0.165009 500 0.165006mean squared error: 0.1650056540966034
以及消息:
UserWarning: Using a target size (torch.Size([100])) that is different to the input size (torch.Size([100, 1])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size.
回答:
您需要更具体地说明是哪个张量(X 或 Y),但我们可以通过使用 torch.view 函数 来重新塑造我们的张量。
例如:
Y_tensor = torch.tensor(Ys)print(Y_tensor.shape)>> torch.Size([5])new_shape = (len(Ys), 1)Y_tensor = Y_tensor.view(new_shape)print(Y_tensor.shape)>> torch.Size([5, 1])
然而,我怀疑这种广播行为并不是您遇到准确性问题的真正原因。