我正在学习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)
这里是打印输出:
您能更正我的代码并解释错误吗?