Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
Tips¶
There are multiple ways to convert a Tensor to a numpy array in PyTorch.
First,
you can call the method Tensor.numpy.
my_tensor.numpy()Second,
you can use the function numpy.array.
import numpy as np
np.array(my_tensor)It is suggested that you use the function numpy.array
to convert a Tensor to a numpy array.
The reason is that numpy.array is more generic.
You can also use it to convert other objects (e.g., PIL.Image)
to numpy arrays
while those objects might not have a method named numpy.
Notice that a Tensor on CUDA cannot be converted to a numpy array directly. You have to move it to CPU first and then convert to a numpy array.
import numpy as np
np.array(my_tensor.to("cpu"))As a matter of fact, this is the suggested way to convert a Tensor to a numpy array as it works for Tensors on different devices.
Tensor to Numpy Array¶
import torch
import numpy as npx = torch.tensor(
[
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
]
)
xtensor([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10]])x.numpy()array([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10]])np.array(x)array([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10]])Move a Tensor to CPU and then convert it to a numpy array. This is the suggested way to convert a Tensor to a numpy array.
np.array(x.to("cpu"))array([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10]])Tensor to list¶
You can also convert a Tensor to a list using the method
Tensor.tolist. If you work across different devices (CPU, GPU, etc.), it is suggested that you useTensor.cpu().tolist.list(tensor)put all first-level element oftensorinto a list. It is the reverse operation oftorch.stack. This is not what you want, geneerally speaking.
Convert the tensor x to a list.
x.tolist()[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]Move the tensor to CPU first and then convert it to a list. This is the recommended way to convert a Tensor to a list.
x.cpu().tolist()[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]list(x)[tensor([1, 2, 3, 4, 5]), tensor([ 6, 7, 8, 9, 10])]list(torch.tensor([1, 2, 3]))[tensor(1), tensor(2), tensor(3)]