python - Pytorch:无法在需要 grad 的变量上调用 numpy()。改用 var.detach().numpy()
问题描述
我的代码中有一个错误,无论我尝试哪种方式都没有得到修复。
错误很简单,我返回一个值:
torch.exp(-LL_total/T_total)
并稍后在管道中获取错误:
RuntimeError: Can't call numpy() on Variable that requires grad. Use var.detach().numpy() instead.
诸如cpu().detach().numpy()
给出相同错误的解决方案。
我该如何解决?谢谢。
解决方案
错误重现
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 数组。参照。这个讨论.pytorch 帖子。Variable
(我认为,更准确地说,为了从它的 pytorch包装器中取出实际的张量,需要这样做,参见另一个讨论.pytorch 帖子)。