python-pytorchHow can I convert a Python PyTorch tensor to a NumPy array?
To convert a Python PyTorch tensor to a NumPy array, you can use the PyTorch .numpy()
method. This method will return the tensor as a NumPy array.
Example
import torch
x = torch.tensor([1, 2, 3])
y = x.numpy()
print(y)
Output example
[1 2 3]
The code above consists of the following parts:
import torch
imports the PyTorch library.x = torch.tensor([1, 2, 3])
creates a PyTorch tensor with values 1, 2, and 3.y = x.numpy()
converts the PyTorch tensor to a NumPy array.print(y)
prints the NumPy array.
Helpful links
More of Python Pytorch
- How can I use Python, PyTorch, and YOLOv5 to build an object detection model?
- How can I use Python and PyTorch to parse XML files?
- How can I use Yolov5 with PyTorch?
- How do I install Python PyTorch Lightning?
- How can I use Python PyTorch with CUDA?
- How do I use Pytorch with Python 3.11 on Windows?
- How can I use Python PyTorch without a GPU?
- How can I use the Softmax function in Python with PyTorch?
- How can I install Python PyTorch on Ubuntu using ROCm?
- How can I calculate the mean value using Python and PyTorch?
See more codes...