PyTorch中具有矢量梯度下降和自微分的线性回归

问题描述 投票:0回答:1

我正在学习PyTorch,我正在尝试使用PyTorch和自动分化功能对合成数据建立简单的线性回归,但由于某些原因而失败。这是我的代码:

import torch
from torch.autograd import Variable

X1 = np.arange(1000).astype(float).reshape(-1, 1)
X2 = np.arange(1000).astype(float).reshape(-1,1)
X0 = np.ones(1000).astype(float).reshape(-1,1)

Y = X0 * 2 + X1*5 + X2*7 + np.random.randn(1000).reshape(-1, 1)

X = np.concatenate([X0, X1, X2], axis = 1)

W = np.random.randn(3,3)

X = torch.tensor(X, requires_grad = True)

Y = torch.tensor(Y, requires_grad = True)

W = Variable(torch.tensor(W), requires_grad = True)

Y = torch.tensor(Y)

def loss(Y, Y_):

    return((Y - Y_)**2).mean()

losses = []

for epoch in range(20):

    Y_ = X@W

    l = loss(Y, Y_)

    l.backward()

    W.data = W.data - 0.01 * W.grad.data

    W.grad.data.zero_()

    print(l)

    losses.append(l)

这里是打印输出:

enter image description here

您能更正我的代码并解释错误吗?

python-3.x pytorch linear-regression gradient-descent autodiff
1个回答
0
投票

代码中的主要问题是简单的大小不匹配:

Y #vector of size Mx1
X #vector of size Mx3

但是您的W的大小为3x3,这意味着您的Y_=X@W最终的大小为Mx3,而不是Mx1。因此,简单的解决方法是将W更改为

W = np.random.randn(3,1)

我认为促成该问题的第二个问题是学习率。将其降低到1e-7附近会导致这种损失:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.