How to Convert Pytorch tensor to Numpy array?

How to Convert Pytorch tensor to Numpy array?

To convert a PyTorch tensor to a NumPy array, you can use the numpy() method provided by the PyTorch tensor object. Here's how you can do it:

  • First, ensure you have both PyTorch and NumPy installed. If not, install them:
pip install torch numpy 
  • Use the numpy() method to convert a PyTorch tensor to a NumPy array:
import torch # Create a PyTorch tensor tensor = torch.tensor([1, 2, 3, 4, 5]) # Convert tensor to NumPy array numpy_array = tensor.numpy() print(type(numpy_array)) # <class 'numpy.ndarray'> print(numpy_array) # [1 2 3 4 5] 

Note:

  • The resulting NumPy array and the original tensor share the same memory. This means if you modify the NumPy array, the tensor will also be modified, and vice-versa.
  • If the tensor is on the GPU (CUDA), you need to first move it to the CPU before converting it to a NumPy array. You can do this using the cpu() method:
# Assume tensor is on CUDA tensor = torch.tensor([1, 2, 3, 4, 5], device='cuda') # Move tensor to CPU and then convert to NumPy array numpy_array = tensor.cpu().numpy() 

More Tags

memory-leak-detector .net-core-3.0 blob material-components destroy selenium-chromedriver quicksort visual-studio-code sqlcmd workflow-activity

More Programming Guides

Other Guides

More Programming Examples