Python

Convert Tensor to NumPy Array

This article explores the various methods and techniques of converting a TensorFlow Tensor into a NumPy array.

Let’s get started.

What Is a Tensor?

A TensorFlow Tensor or Tensor for short refers to a multidimensional array with a uniform type. For example, consider a tensor as a collection of vectors and matrices in a multidimensional array.

Like Python strings, a Tensor is immutable and does not allow you to change its content after declaration.

We can create a tensor as shown in the following snippet:

import tensorflow as tf
import numpy as np
tensor = tf.constant([[10,20], [30,40], [50,60]])
print(tensor)

In the given code, we start by importing the TensorFlow and NumPy modules as tf and n, respectively.

We then create a new Tensor using the constant function and pass it into an array. Printing the resulting value returns an output as shown in the following:

tf.Tensor(
[[10 20]
 [30 40]
 [50 60]], shape=(3, 2), dtype=int32)

The code returns a new Tensor of shape a (3,2) and data type of int32.

Method 1: Python Convert Tensor to NumPy Array

The first and most common method that we can use to convert a Tensor into a NumPy array is the Tensor.numpy() function.

The function returns a provided tensor as a NumPy ndarray.

An example code is as shown in the following:

import tensorflow as tf
import numpy as np

tensor = tf.constant([[10,20], [30,40], [50,60]])
tensor_array = tensor.numpy()
print(type(tensor))
print(type(tensor_array))

In the given example, we use the numpy() function which allows to convert an input tensor type into a NumPy ndarray.

The previous code should return the resulting types as follows:

<class 'tensorflow.python.framework.ops.EagerTensor'>
<class 'numpy.ndarray'>

We can see from the previous output that the value is converted from an EagerTensor to a NumPy ndarray.

NOTE: The previously depicted method works on TensorFlow version 2 and above.

Sometimes, you may need to enable the Eager Execution on your Tensorflow installation.

Method 2: Older TensorFlow Versions or Eager Execution Disabled

Suppose you have TensorFlow version 1.0 and would like to convert a Tensor into a NumPy array. For that, you can use the TensorFlow.Session() method.

The Tensor.Session() object provides us with the run() function which can help out in our case. Passing a tensor function returns a NumPy array as illustrated in the following code:

import tensorflow.compat.v1 as tf
tf.compat.v1.disable_v2_behavior()
tensor = tf.constant([[1,2], [3,4], [5,6]])
tensor_array = tf.Session().run(tensor)
print(type(tensor_array))

We started by importing the v1 version of TensorFlow in the previous code. This gives us access to the Session() function.

We then disable the v2 behavior as illustrated by the code in line 2.

The v2 block disables the tensorflow v2 features which may result in an error as shown in the following:

AttributeError: module 'tensorflow' has no attribute 'Session'

Next, we create a tensor with the constant function.

Lastly, we run the code to convert the tensor.

The resulting type is as shown in the following:

<class 'numpy.ndarray'>

Remember that not all tensors passed to the run function are returned as NumPy array.
For example:

import tensorflow.compat.v1 as tf
tf.compat.v1.disable_v2_behavior()
tensor = tf.sparse.SparseTensor(indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4])
tensor_array = tf.Session().run(tensor)
print(type(tensor_array))

We use a SparseTensor type in this example and pass it into the run function. The previous code returns a result as shown in the following:

<class 'tensorflow.python.framework.sparse_tensor.SparseTensorValue'>

In this case, we get a SparseTensorValue instead of a NumPy array.

Method 3: Using the Eval Function

If you are using the TensorFlow version 1, you can use the eval() function to accomplish the same thing.

The functionality is closely similar to the run function illustrated in the previous example. Let us look at the following example code:

import tensorflow.compat.v1 as tf
tf.compat.v1.disable_v2_behavior()
tensor = tf.constant([[1,2,3], [4,5,6]])
print(type(tensor))
tensor_array = tensor.eval(session=tf.Session())
print(type(tensor_array))
Similarly, the previous code returns a NumPy array.

Conclusion

This article explores the three main methods of converting a Tensor into a NumPy array. We hope you enjoyed the tutorial.

Thanks for reading!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list