【问题标题】:`RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn` for linear regression with gradient descent using torch`RuntimeError:张量的元素 0 不需要 grad 并且没有 grad_fn` 用于使用 Torch 进行梯度下降的线性回归
【发布时间】:2022-01-11 21:04:33
【问题描述】:

我正在尝试使用 pytorch 为线性回归实现简单的梯度下降,如文档中的this example 所示:

import torch
from torch.autograd import Variable

learning_rate = 0.01
y = 5
x = torch.tensor([3., 0., 1.])
w = torch.tensor([2., 3., 9.], requires_grad=True)
b = torch.tensor(1., requires_grad=True)

for z in range(100):
    y_pred = b + torch.sum(w * x)
    loss = (y_pred - y).pow(2)
    loss = Variable(loss, requires_grad = True)
    # loss.requires_grad = True
    loss.backward()
    
    with torch.no_grad():
        w = w - learning_rate * w.grad
        b = b - learning_rate * b.grad
        
        w.grad = None
        b.grad = None

当我运行代码时,我收到错误RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn

我已阅读herehere 表示可以解决

使用

  • loss = Variable(loss, requires_grad = True) 导致TypeError: unsupported operand type(s) for *: 'float' and 'NoneType'

  • loss.requires_grad = True 导致RuntimeError: you can only change requires_grad flags of leaf variables.

我该如何解决这个问题?

【问题讨论】:

    标签: error-handling pytorch linear-regression gradient-descent


    【解决方案1】:

    在向后为我解决问题之前调用.retain_grad()

    learning_rate = 0.01
    y = 5
    x = torch.tensor([3., 0., 1.])
    w = torch.tensor([2., 3., 9.], requires_grad=True)
    b = torch.tensor(1., requires_grad=True)
    
    for z in range(100):
        y_pred = b + torch.sum(w * x)
        loss = (y_pred - y).pow(2)
        
        w.retain_grad()
        b.retain_grad()
        loss.backward()
        
        w = w - learning_rate * w.grad
        b = b - learning_rate * b.grad
    

    很好的解释可以阅读here

    【讨论】:

      猜你喜欢
      • 2020-03-26
      • 2020-08-31
      • 2019-07-17
      • 2020-10-23
      • 2021-07-23
      • 2019-04-07
      • 2022-08-14
      • 2021-10-26
      • 2023-03-11
      相关资源
      最近更新 更多