python-pytorchHow can I convert a Python Torch tensor to a Numpy array?
To convert a Python Torch tensor to a Numpy array, the numpy()
function can be used. It takes in a tensor as a parameter and returns a Numpy array.
Example code
import torch
import numpy as np
tensor = torch.randn(2,3)
numpy_array = tensor.numpy()
print(tensor)
print(numpy_array)
Example output:
tensor([[ 0.9016, 0.2183, -0.2770],
[-0.6709, 0.9398, -1.1486]])
[[ 0.9016 0.2183 -0.277 ]
[-0.6709 0.9398 -1.1486]]
The numpy()
function is part of the Torch tensor class, and it can be used to convert a Torch tensor to a Numpy array. The code above shows an example of using the numpy()
function to convert a Torch tensor to a 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 do I use Pytorch with Python 3.11 on Windows?
- How can I use Yolov5 with PyTorch?
- How can I use Python PyTorch without a GPU?
- How do I install the latest version of Python for PyTorch?
- How do I install a Python PyTorch .whl file?
- How do I use PyTorch with Python version 3.11?
- How do I install PyTorch on Ubuntu using Python?
- How can I use Python PyTorch with CUDA?
See more codes...