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 do I use Pytorch with Python 3.11 on Windows?
- How can I use Yolov5 with PyTorch?
- How can I use Python and PyTorch to parse XML files?
- How do I uninstall Python PyTorch?
- How can I use the Softmax function in Python with PyTorch?
- How can I use PyTorch with Python 3.9?
- How do I install Python PyTorch Lightning?
- How can I use Python, PyTorch, and YOLOv5 to build an object detection model?
- How do I upgrade PyTorch using Python?
- How do I use PyTorch with Python 3.10?
See more codes...