How to convert a PyTorch tensor to a NumPy array?
Published on Aug. 22, 2023, 12:18 p.m.
To convert a PyTorch tensor to a NumPy array, you can use the .numpy()
method. Here is an example:
import torch
import numpy as np
# Create a PyTorch tensor
x = torch.tensor([[1, 2], [3, 4]])
# Convert the tensor to a NumPy array
y = x.numpy()
# Print the NumPy array
print(y)
In this code, we create a PyTorch tensor x
and then use the .numpy()
method to convert it to a NumPy array y
. Note that if the PyTorch tensor is on the GPU, you will need to move it to the CPU before calling .numpy()
, like this:
# Move the PyTorch tensor to the GPU
x = x.to('cuda')
# Convert the tensor to a NumPy array (on CPU)
y = x.to('cpu').numpy()
In this code, we use the .to()
method to move the tensor to the GPU, and then move it back to the CPU using the .to()
method again before calling .numpy()
. This is necessary because NumPy does not support GPU tensors.