Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to convert a NumPy ndarray to a PyTorch Tensor and vice versa?
A PyTorch tensor is like numpy.ndarray. The difference between these two is that a tensor utilizes the GPUs to accelerate numeric computation. We convert a numpy.ndarray to a PyTorch tensor using the function torch.from_numpy(). And a tensor is converted to numpy.ndarray using the .numpy() method.
Steps
Import the required libraries. Here, the required libraries are torch and numpy.
Create a numpy.ndarray or a PyTorch tensor.
Convert the numpy.ndarray to a PyTorch tensor using torch.from_numpy() function or convert the PyTorch tensor to numpy.ndarray using the .numpy() method.
Finally, print the converted tensor or numpy.ndarray.
Converting NumPy Array to PyTorch Tensor
The following Python program converts a numpy.ndarray to a PyTorch tensor ?
# import the libraries
import torch
import numpy as np
# Create a numpy.ndarray "a"
a = np.array([[1,2,3],[2,1,3],[2,3,5],[5,6,4]])
print("a:\n", a)
print("Type of a :\n", type(a))
# Convert the numpy.ndarray to tensor
t = torch.from_numpy(a)
print("t:\n", t)
print("Type after conversion:\n", type(t))
a:
[[1 2 3]
[2 1 3]
[2 3 5]
[5 6 4]]
Type of a :
<class 'numpy.ndarray'>
t:
tensor([[1, 2, 3],
[2, 1, 3],
[2, 3, 5],
[5, 6, 4]], dtype=torch.int32)
Type after conversion:
<class 'torch.Tensor'>
Converting PyTorch Tensor to NumPy Array
The following Python program converts a PyTorch tensor to a numpy.ndarray ?
# import the libraries
import torch
import numpy as np
# Create a tensor "t"
t = torch.Tensor([[1,2,3],[2,1,3],[2,3,5],[5,6,4]])
print("t:\n", t)
print("Type of t :\n", type(t))
# Convert the tensor to numpy.ndarray
a = t.numpy()
print("a:\n", a)
print("Type after conversion:\n", type(a))
t:
tensor([[1., 2., 3.],
[2., 1., 3.],
[2., 3., 5.],
[5., 6., 4.]])
Type of t :
<class 'torch.Tensor'>
a:
[[1. 2. 3.]
[2. 1. 3.]
[2. 3. 5.]
[5. 6. 4.]]
Type after conversion:
<class 'numpy.ndarray'>
Key Points
torch.from_numpy()creates a tensor that shares memory with the original NumPy array.The
.numpy()method only works on tensors that are on the CPU, not GPU.Data types are automatically preserved during conversion when possible.
Conclusion
Use torch.from_numpy() to convert NumPy arrays to PyTorch tensors and .numpy() to convert tensors back to NumPy arrays. Both methods preserve the original data structure and share memory for efficient conversion.
