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
Convert a 1D IntTensor to int in PyTorch

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Machine Learning frameworks like PyTorch and Tensorflow is a testament to his versatility and commitment to the craft.