6 Different Ways to Convert a Tensor to NumPy Array

In this article, we will be discussing various ways we can convert a Python tensor to a NumPy array. But before we get into the different procedures, we must discuss what a Tensor is in Python.

What is a Tensor in Python?

Basically, tensors are a collection of vectors and matrices present within a multidimensional array. A vector in Python is a one-dimensional or a first-order tensor. A matrix is a two-dimensional or second-order tensor.

Tensors can be implemented in Python using N-dimensional arrays. Here’s an example of a Tensor in Python.

from numpy import array
exampleTensor = array([
  [[1,2,3],    [4,5,6],    [7,8,9]],
  [[11,12,13], [14,15,16], [17,18,19]],
  [[21,22,23], [24,25,26], [27,28,29]],
  ])
print(exampleTensor.shape)
print(exampleTensor)

Output

(3, 3, 3)
[[[ 1  2  3]
  [ 4  5  6]
  [ 7  8  9]]

 [[11 12 13]
  [14 15 16]
  [17 18 19]]

 [[21 22 23]
  [24 25 26]
  [27 28 29]]]

The .shape() function returns the dimension of the tensor. In this case, it is a 3x3x3 multidimensional structure.

What are NumPy Arrays in Python?

A NumPy array consists of a grid of values of a similar data type. It supports indexing using positive integers with square brackets. The dimensions of the NumPy array are its “Rank”. The array shape is represented by a tuple of integers giving its size along each dimension.

How is this any different from a regular list?

A Python list is the equivalent of a NumPy array. However, it is resizable and can contain different types. NumPy arrays are significantly better than Python lists in the following aspects:

Different Ways to Convert A Tensor to a NumPy Array

Converting One Dimensional Tensor to NumPy Array

To create tensor types, we are using the .tensor method from the torch module. The PyTorch module provides computation techniques for Tensors. The .numpy() function performs the conversion.

import torch
import numpy

sampleTensor = torch.tensor([4.32, 74.21, 67.50, 90.34, 21.3])

print(sampleTensor)

sampleTensor = sampleTensor.numpy()

print("After Conversion: ")
sampleTensor

For this implementation, we create a 1D tensor with float values. Upon passing the .numpy() function, it returns a NumPy array.

Output

tensor([ 4.3200, 74.2100, 67.5000, 90.3400, 21.3000])
After Conversion: 
array([ 4.32, 74.21, 67.5 , 90.34, 21.3 ], dtype=float32)

Converting N-Dimensional Tensors to NumPy Array

import torch
import numpy

# Creating a 2 dimensional Tensor
sampleTensor = torch.tensor([[3, 1, 5, 8, 4], [9, 3, 2, 1, 7], 
                  [8, 2, 7, 1, 3]])

print(sampleTensor)

sampleTensor = sampleTensor.numpy()

print("After Conversion: ")
sampleTensor

Using the torch module, we create a 2D tensor with integer values. In order to convert, we pass the .numpy() function to the Tensor.

Output

tensor([[3, 1, 5, 8, 4],
        [9, 3, 2, 1, 7],
        [8, 2, 7, 1, 3]])
After Conversion: 
array([[3, 1, 5, 8, 4],
       [9, 3, 2, 1, 7],
       [8, 2, 7, 1, 3]])

Converting N-Dimensional Tensors to NumPy Array Using .array() Method

Another technique is to use the numpy.array() function. This function allows converting data types such as Tensors to arrays. Let’s look at the following implementation

import torch
import numpy

# Creating a 2 dimensional Tensor
sampleTensor = torch.tensor([[3, 1, 5, 8, 4], [9, 3, 2, 1, 7], 
                  [8, 2, 7, 1, 3]])

print(sampleTensor)

sampleTensor = numpy.array(sampleTensor)

print("After Conversion: ")
sampleTensor

Output

tensor([[3, 1, 5, 8, 4],
        [9, 3, 2, 1, 7],
        [8, 2, 7, 1, 3]])
After Conversion: 
array([[3, 1, 5, 8, 4],
       [9, 3, 2, 1, 7],
       [8, 2, 7, 1, 3]])

Converting a Tensor to NumPy Array in TensorFlow

TensorFlow is an open-source library for AI/ML. It primarily focuses on training and analysis of Deep Neural Networks. Let’s see how we convert Tensors from TensorFlow into arrays.

import tensorflow as tf

values = tf.constant([[1, 2], [3, 4]])                 
tensor = tf.add(values, 1)
print(values.numpy())

Output

[[1 2]
 [3 4]]

How To Convert a Tensor into a Normal Array

Tensors can be converted into regular arrays with the help of the .eval() function. However, this method does not work in TensorFlow 2.0. It is recommended that you work with NumPy arrays rather than regular array structures. In this demonstration, we will force TensorFlow to have TF version 1 behavior.

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
sampleTensor = tf.constant([[4,1,2],[7,3,8],[2,1,2]])
print("Tensor = ",sampleTensor)
convertedArray = sampleTensor.eval(session=tf.Session())
print("Array = ",convertedArray)

Output

Tensor =  Tensor("Const_1:0", shape=(3, 3), dtype=int32)
Array =  [[4 1 2]
 [7 3 8]
 [2 1 2]]

First off, we are disabling the features of TF version 2 for the .eval function to work. We create a Tensor (sampleTensor) consisting of integer values. We pass the .eval() function on the Tensor and display the converted array result.

Converting Image Tensors To Python Arrays

This implementation is used to train Convolutional Neural Networks(CNN). CNN is an artificial neural network that deals with image recognition and classification. The following implementation converts image tensors that are fed into CNNs to NumPy arrays.

p=model_(x) 
s=p.numpy()
print(s.shape)
cv2.imwrite("hello.jpg",s.reshape(s.shape[1:]))

This will generate the shape of an array using the .numpy() function. The slicing allows us to change its shape to keep the image.

FAQs

How to convert a torch tensor to a NumPy array?

Torch tensors can be converted to NumPy arrays in 2 ways:
1) Using the .array() method
2) Using the .numpy() method

How to convert tensors to a normal array?

This cannot be done in the latest version of TensorFlow 2. However, in version 1, we can pass the .eval() function to convert a tensor to an array.

Conclusion

In this article, we discussed what Python tensors and Numpy arrays are. Arrays are significantly better than lists. They consume lesser memory and have better performance. We have also discussed how we can convert Tensors from TensorFlow into NumPy arrays.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments