【问题标题】:PyTorch shows the error " 'NoneType' object has no attribute 'zero_' " when calling the zero_ methodPyTorch 在调用 zero_ 方法时显示错误“'NoneType' object has no attribute 'zero_'”
【发布时间】:2021-04-01 03:04:46
【问题描述】:

有人可以回答为什么我的代码显示错误。 提前致谢。

代码:

import torch
torch.manual_seed(0)

a = torch.rand((1, 3), requires_grad = True)
w1 = torch.rand((3, 3), requires_grad = True)
w2 = torch.rand((3, 1), requires_grad = True)

d = torch.matmul(torch.matmul(a, w1), w2)

L = (10 - d)

L.backward()

w1 = w1 - w1.grad*0.001
w1.grad.zero_()

错误: 属性错误 “NoneType”对象没有属性“zero_”

【问题讨论】:

    标签: pytorch


    【解决方案1】:

    线

    w1 = w1 - w1.grad*0.001
    

    正在重新分配w1,因此之后w1 不再指代它之前所做的相同张量。要维护w1 的所有内部状态(例如.grad 成员),您必须就地更新w1。由于这是一个叶张量,我们还需要禁用计算图的构建。

    with torch.no_grad():
        w1.sub_(w1.grad * 0.001)
    

    【讨论】:

      猜你喜欢
      • 2021-06-11
      • 1970-01-01
      • 2022-12-15
      • 1970-01-01
      • 2023-02-10
      • 2017-10-20
      • 2021-03-13
      • 2021-08-22
      • 1970-01-01
      相关资源
      最近更新 更多