pytorch线性回归

时间:2018-07-30 03:38:55

标签: pytorch

我尝试对ForestFires数据集运行线性回归。 数据集在Kaggle上可用,我的尝试要点在这里: https://gist.github.com/Chandrak1907/747b1a6045bb64898d5f9140f4cf9a37

我面临两个问题:

  1. 预测的输出形状为32x1,目标数据形状为32。
  

输入形状与目标形状不匹配:输入[32 x 1],目标[32]¶

使用视图重塑了预测张量。

  

y_pred = y_pred.view(inputs.shape [0])

为什么预测张量和实际张量的形状不匹配?

    pytorch中的
  1. SGD从未收敛。我尝试使用
  2. 手动计算MSE
  

print(torch.mean((y_pred-标签)** 2))

此值不匹配

  

损失=准则(y_pred,标签)

有人可以突出显示我的代码中的错误在哪里吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

问题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

因此,您需要使用torch.unsqueeze(labels, 1)labels.view(-1,1)

来扩展标签的暗色:(32)->(32,1)

https://pytorch.org/docs/stable/torch.html#torch.unsqueeze

  

torch.unsqueeze(输入,暗淡,输出=无)→张量

     

返回在指定位置插入的尺寸为1的新张量。

     

返回的张量与此张量共享相同的基础数据。

问题2

在检查了代码之后,我意识到您已经向MSELoss添加了size_average参数:

criterion = torch.nn.MSELoss(size_average=False)
  

size_average(布尔型,可选)–已弃用(请参见缩减)。默认情况下,损失是批次中每个损失元素的平均数。请注意,对于某些损失,每个样本有多个元素。如果将字段size_average设置为False,则对每个小批量将损失相加。当reduce为False时被忽略。默认值:True

这就是为什么两个计算值不匹配的原因。这是示例代码:

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)
相关问题