重现错误
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)。