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 np
x = torch.tensor(
[
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
]
)
x
x.numpy()
np.array(x)
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"))
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 oftensor
into 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()
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()
list(x)
list(torch.tensor([1, 2, 3]))