Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python PyTorch张量中的就地算术运算与正规算术运算_Python_Machine Learning_Pytorch - Fatal编程技术网

Python PyTorch张量中的就地算术运算与正规算术运算

Python PyTorch张量中的就地算术运算与正规算术运算,python,machine-learning,pytorch,Python,Machine Learning,Pytorch,我尝试使用Pytorch框架构建线性回归,在实现梯度下降时,我观察到两种不同的输出,这两种输出基于我在Python代码中使用算术运算的方式。代码如下: #X and Y are input and target labels respectively X = torch.randn(100,1)*10 Y = X + 3*torch.randn(100,1) +2 plt.scatter(X.numpy(),Y.numpy()) #Initialiation of weight a

我尝试使用Pytorch框架构建线性回归,在实现梯度下降时,我观察到两种不同的输出,这两种输出基于我在Python代码中使用算术运算的方式。代码如下:

 #X and Y are input and target labels respectively
 X = torch.randn(100,1)*10
 Y = X + 3*torch.randn(100,1) +2
 plt.scatter(X.numpy(),Y.numpy())


 #Initialiation of weight and bias
 w = torch.tensor(1.0,requires_grad=True)
 b = torch.tensor(1.0,requires_grad=True)

 #forward pass
 def forward_feed(x):
   y = w*x +b
   return y

 #Parameters Learning
 epochs = 100
 lr = 0.00008
 loss_list = []
 for epoch in range(epochs):
   print('epoch',epoch)
   Y_pred = forward_feed(X)
   loss = torch.sum((Y - Y_pred)**2)
   loss_list.append(loss)
   loss.backward()
   with torch.no_grad():
     w -= lr*w.grad
     b -= lr*b.grad
     w.grad.zero_()
     b.grad.zero_()
如果我使用这个代码,我会得到预期的结果,即我的代码能够估计权重和偏差。但是,如果我更改梯度下降代码行,如下所示:

  w =w- lr*w.grad
  b =b- lr*b.grad
我得到以下错误:

 AttributeError                            Traceback (most recent call 
 last)
 <ipython-input-199-84b86804d4d5> in <module>()
 ---> 41         w.grad.zero_()
      42         b.grad.zero_()

 AttributeError: 'NoneType' object has no attribute 'zero_'
AttributeError回溯(最近的调用
最后)
在()
--->41 w.grad.zero_uz()
42 b.零年级
AttributeError:“非类型”对象没有属性“零”
有人能帮我吗


我试着在谷歌上查看答案,发现了一个相关链接:。但这与我所面临的恰恰相反。根据这一联系,他们说,由于张量共享相同的存储空间,就地赋值导致了一个问题。然而,对于我的代码,就地操作不是正常操作。

我认为原因很简单。当您这样做时:

w = w - lr * w.grad
b = b - lr * b.grad
左侧的
w
b
是两个新的张量,它们的
.grad
为无


但是,当您执行就地操作时,不会创建任何新的张量,只需更新相关张量的值。因此,在这种情况下,需要就地操作。

非常感谢您的帮助。这让我想到,在其他python库中也会发生这种情况吗?如果我们对python变量/numpy数组执行常规算术运算,它们确实具有相同的属性。张量也会携带相同的梯度,因此我们需要对这种情况进行就地算术运算。这是有道理的。试想一下,我们还有其他类似的例子吗?