【问题标题】:Pytorch: Can't call numpy() on Variable that requires grad. Use var.detach().numpy() insteadPytorch:无法在需要 grad 的变量上调用 numpy()。改用 var.detach().numpy()
【发布时间】:2019-08-23 06:42:08
【问题描述】:

我的代码中有一个错误,无论我尝试哪种方式都无法修复。

错误很简单,我返回一个值:

torch.exp(-LL_total/T_total)

然后在管道中得到错误:

RuntimeError: Can't call numpy() on Variable that requires grad. Use var.detach().numpy() instead.

cpu().detach().numpy() 等解决方案给出了相同的错误。

我该如何解决?谢谢。

【问题讨论】:

  • 调用var.detach().numpy(),如前所述,是您想要的(其中var 是您要转换为numpy 数组的张量的名称)。如果由于某种原因这不起作用,您需要提供有关您正在运行什么代码来获取此错误的更多详细信息。 torch.exp(... 行不相关。 cpu 这里是什么?那是您要转换的张量的名称吗?如果是这样,请执行cpu.detach().numpy()。还是返回张量的函数?

标签: python numpy pytorch


【解决方案1】:

我刚遇到这个问题 在运行时期时,我将损失记录到一个列表中

final_losses.append(loss)

一旦我跑遍了所有的时期,我想绘制输出图表

plt.plot(range(epochs), final_loss)
plt.ylabel('RMSE Loss')
plt.xlabel('Epoch');

我在我的 Mac 上运行它,没有问题,但是,我需要在 Windows PC 上运行它,它产生了上面提到的错误。所以,我检查了每个变量的类型。

Type(range(epochs)), type(final_losses)

范围,列表

看起来应该没问题。

花了一点时间才意识到 final_losses 列表是张量列表。然后我将它们转换为带有新列表变量 fi_los 的实际列表。

fi_los = [fl.item() for fl in final_losses ]
plt.plot(range(epochs), fi_los)
plt.ylabel('RMSE Loss')
plt.xlabel('Epoch');

成功了!

【讨论】:

    【解决方案2】:

    我有同样的错误信息,但它是用于在 matplotlib 上绘制散点图。

    我可以从这个错误消息中得到两个步骤:

    1. 使用 from fastai.basics import * 导入 fastai.basics

    2. 如果你只使用torch库,记得把requires_grad去掉:

      with torch.no_grad():
          (your code)
      

    【讨论】:

    • 导入fastai.basics后要做什么?
    • 抱歉无法及时回复,导入后,您只需将代码复制/粘贴到 with torch.no_grad(): 部分,然后让魔法消失
    • 那是1路2步,不是2路。
    【解决方案3】:

    对于现有的张量

    from torch.autograd import Variable
    
    type(y)  # <class 'torch.Tensor'>
    
    y = Variable(y, requires_grad=True)
    y = y.detach().numpy()
    
    type(y)  #<class 'numpy.ndarray'>
    

    【讨论】:

      【解决方案4】:

       重现错误

      import torch
      
      tensor1 = torch.tensor([1.0,2.0],requires_grad=True)
      
      print(tensor1)
      print(type(tensor1))
      
      tensor1 = tensor1.numpy()
      
      print(tensor1)
      print(type(tensor1))
      

      这会导致 tensor1 = tensor1.numpy() 行出现完全相同的错误:

      tensor([1., 2.], requires_grad=True)
      <class 'torch.Tensor'>
      Traceback (most recent call last):
        File "/home/badScript.py", line 8, in <module>
          tensor1 = tensor1.numpy()
      RuntimeError: Can't call numpy() on Variable that requires grad. Use var.detach().numpy() instead.
      
      Process finished with exit code 1
      

      通用解决方案

      这是在您的错误消息中向您建议的,只需将 var 替换为您的变量名

      import torch
      
      tensor1 = torch.tensor([1.0,2.0],requires_grad=True)
      
      print(tensor1)
      print(type(tensor1))
      
      tensor1 = tensor1.detach().numpy()
      
      print(tensor1)
      print(type(tensor1))
      

      按预期返回

      tensor([1., 2.], requires_grad=True)
      <class 'torch.Tensor'>
      [1. 2.]
      <class 'numpy.ndarray'>
      
      Process finished with exit code 0
      

      一些解释

      除了实际值定义之外,您还需要将您的张量转换为不需要梯度的另一个张量。这个其他张量可以转换为 numpy 数组。参照。 this discuss.pytorch post。 (我认为,更准确地说,为了从它的 pytorch Variable 包装器中取出实际的张量,需要这样做,参见 this other discuss.pytorch post)。

      【讨论】:

      • 这发生在我的 fast.ai 第二个教程中。在这种情况下,不是直接使用 nn.Parameter 变量进行绘图,而是将分离的变量复制到单独的张量中并绘制它们解决了这个问题。
      • 有关为什么需要分离方法的进一步说明,请参阅我授予赏金的this question
      猜你喜欢
      • 1970-01-01
      • 2023-04-09
      • 2021-07-01
      • 2021-11-11
      • 2020-12-14
      • 2021-07-23
      • 2018-08-17
      • 2020-08-31
      • 1970-01-01
      相关资源
      最近更新 更多