首页 文章

用pytorch进行线性回归

提问于
浏览
0

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

我面临两个问题:

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

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

使用视图我重塑了预测张量 .

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

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

  • pytorch中的SGD永远不会收敛 . 我尝试使用手动计算MSE

print(torch.mean((y_pred - labels)** 2))

该值不匹配

loss = criterion(y_pred,labels)

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

谢谢 .

1 回答

  • 1

    问题1

    这是关于来自Pytorch docs的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)→Tensor返回在指定位置插入尺寸为1的新张量 . 返回的张量与此张量共享相同的基础数据 .

    问题2

    在查看了您的代码后,我意识到您已将 size_average param添加到MSELoss:

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

    size_average(bool,optional) - 已弃用(请参阅缩小) . 默认情况下,损失是批次中每个损失元素的平均值 . 请注意,对于某些损失,每个样本有多个元素 . 如果字段size_average设置为False,则将每个小批量的损失相加 . 当reduce为False时忽略 . 默认值:True

    这就是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)
    

相关问题