Create a Numpy array from a torch.tensor

A Pytorch Tensor is basically the same as a NumPy array. This means it does not know anything about deep learning or computational graphs or gradients and is just a generic n-dimensional array to be used for arbitrary numeric computation.

Example 1: 

To create a Numpy array from Tensor, Tensor is converted to a tensor.numpy() first.

Python3




# pip install torch
import torch
tensor = torch.tensor([1, 2, 3, 4, 5])
 
np_a = tensor.numpy()


Output:

array([1, 2, 3, 4, 5])

Example 2: 

To create a Numpy array from Tensor, Tensor is converted to a tensor.detach.numpy() first.

Python3




# pip install torch
import torch
tensor = torch.tensor([1, 2, 3, 4, 5])
 
np_b = tensor.detach().numpy()


Output:

array([1, 2, 3, 4, 5])

Example 3: 

To create a Numpy array from Tensor, Tensor is converted to a tensor.detach().cpu().numpy() first.

Python3




# pip install torch
import torch
tensor = torch.tensor([1, 2, 3, 4, 5])
 
np_c = tensor.detach().cpu().numpy()


Output:

array([1, 2, 3, 4, 5])

TensorFlow – How to create a numpy ndarray from a tensor

TensorFlow is an open-source Python library designed by Google to develop Machine Learning models and deep-learning, neural networks.

Similar Reads

Create a Numpy array from a torch.tensor

A Pytorch Tensor is basically the same as a NumPy array. This means it does not know anything about deep learning or computational graphs or gradients and is just a generic n-dimensional array to be used for arbitrary numeric computation....

Create a numpy ndarray from a Tensorflow.tensor

...