How to Convert Pytorch tensor to Numpy array?
In this article, we are going to convert Pytorch tensor to NumPy array.
Method 1: Using numpy().
Syntax: tensor_name.numpy()
Example 1: Converting one-dimensional a tensor to NumPy array
Python3
import torch
import numpy
b = torch.tensor([ 10.12 , 20.56 , 30.00 , 40.3 , 50.4 ])
print (b)
b = b.numpy()
b
|
Output:
tensor([10.1200, 20.5600, 30.0000, 40.3000, 50.4000])
array([10.12, 20.56, 30. , 40.3 , 50.4 ], dtype=float32)
Example 2: Converting two-dimensional tensors to NumPy array
Python3
import torch
import numpy
b = torch.tensor([[ 1 , 2 , 3 , 4 , 5 ], [ 3 , 4 , 5 , 6 , 7 ],
[ 4 , 5 , 6 , 7 , 8 ]])
print (b)
b = b.numpy()
b
|
Output:
tensor([[1, 2, 3, 4, 5],
[3, 4, 5, 6, 7],
[4, 5, 6, 7, 8]])
array([[1, 2, 3, 4, 5],
[3, 4, 5, 6, 7],
[4, 5, 6, 7, 8]])
Method 2: Using numpy.array() method.
This is also used to convert a tensor into NumPy array.
Syntax: numpy.array(tensor_name)
Example: Converting two-dimensional tensor to NumPy array
Python3
import torch
import numpy
b = torch.tensor([[ 1 , 2 , 3 , 4 , 5 ], [ 3 , 4 , 5 , 6 , 7 ],
[ 4 , 5 , 6 , 7 , 8 ]])
print (b)
b = numpy.array(b)
b
|
Output:
tensor([[1, 2, 3, 4, 5],
[3, 4, 5, 6, 7],
[4, 5, 6, 7, 8]])
array([[1, 2, 3, 4, 5],
[3, 4, 5, 6, 7],
[4, 5, 6, 7, 8]])
Last Updated :
30 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...