How to Convert PyTorch Tensor to Numpy Array

To convert a PyTorch tensor to a NumPy array, you can “use the .numpy() method on the tensor.”

Here’s a step-by-step guide:

Step 1: Import the PyTorch library

import torch

Step 2: Create a PyTorch tensor

tensor = torch.tensor([1, 2, 3, 4, 5])

Step 3: Convert the tensor to a NumPy array

numpy_array = tensor.numpy()

Complete code

import torch

tensor = torch.tensor([1, 2, 3, 4, 5])

numpy_array = tensor.numpy()

print(numpy_array)
print(type(numpy_array))

Output

[1 2 3 4 5]

<class 'numpy.ndarray'>

Notable points

The returned NumPy array will share the same memory as the original tensor. This means modifying the NumPy array will change the original tensor and vice-versa.

If the tensor is on the GPU (i.e., CUDA), you’ll first need to bring it to the CPU using the .cpu() method before converting it to a NumPy array:

if tensor.is_cuda:
  numpy_array = tensor.cpu().numpy()

That’s it!

Related posts

Python List to PyTorch Tensor

PyTorch Tensor to Python List

Convert a 1D IntTensor to int in PyTorch

Leave a Comment