
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert NumPy ndarray to 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.
Example 1
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))
Output
When you run the above code, it will produce the following output
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'>
Example 2
The following Python program converts a PyTorch tensor to a numpy.ndarray.
# import the libraries import torch import numpy # 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))
Output
When you run the above code, it will produce the following output
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'>