RuntimeError: Can‘t call numpy() on Tensor that requires grad

created at 07-10-2021 views: 159

description

pytorch Tensor to numpy got error:

RuntimeError: Can‘t call numpy() on Tensor that requires grad

solution

Use Tensor.detach().numpy() when converting to numpy:

a = torch.ones(5)
b = a.detach().numpy()
print(b)

When the tensor in the calculation is converted, because it has a gradient value, it cannot be directly converted to numpy format, so it is best to call .detach().numpy() anyway.

created at:07-10-2021
edited at: 07-10-2021: