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

created at 07-10-2021 views: 4

description

pytorch Tensor to numpy got error:

RuntimeError: Cant 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.

Please log in to leave a comment.