python-pytorchHow do I convert a torch tensor to a numpy array in Python?
To convert a torch tensor to a numpy array in Python, you can use the .numpy()
method. This method converts a torch tensor to a numpy array.
Example
import torch
x = torch.tensor([1, 2, 3])
# convert tensor to numpy array
y = x.numpy()
print(y)
Output example
[1 2 3]
The code above consists of the following parts:
import torch
: This imports thetorch
library into the programx = torch.tensor([1, 2, 3])
: This creates a torch tensor with the values1
,2
, and3
y = x.numpy()
: This converts the torch tensorx
to a numpy array and stores it in the variabley
print(y)
: This prints the numpy array stored in the variabley
Helpful links
More of Python Pytorch
- How can I use Python and PyTorch to create a Zoom application?
- How can I use Yolov5 with PyTorch?
- How do I install Python PyTorch Lightning?
- How can I use Python, PyTorch, and YOLOv5 to build an object detection model?
- How can I use Numba and PyTorch together for software development?
- How can I use Python and PyTorch to parse XML files?
- How can I use Python and PyTorch to create an XOR gate?
- How do I use Pytorch with Python 3.11 on Windows?
- How can I use Python PyTorch with CUDA?
- How do I uninstall Python PyTorch?
See more codes...