How to Convert a Tensor to a Numpy Array in TensorFlow

by | Programming, Python, TensorFlow, Tips

The simplest way to convert a TensorFlow Tensor to a Numpy array is to use the numpy() method.

For example, numpy_array = tensor.numpy().

This tutorial will go through how to convert a TensorFlow Tensor to a NumPy array for both TensorFlow 2.x and 1.x with the help of code examples.


Convert Tensor to NumPy Array using numpy()

We can convert a tensor to a NumPy array in TensorFlow 2.x using the built-in numpy() method. Let’s look at an example:

import tensorflow as tf

t = tf.constant([[1, 3], [5, 7]])

arr = t.numpy()

print(arr)

print(type(arr))

Let’s run the code to see the result of the conversion:

[[1 3]
 [5 7]]
<class 'numpy.ndarray'>

Convert Tensor to NumPy Array using NumPy Operations on Tensors

When we perform NumPy operations on Tensors, the result of the operation will be a NumPy ndarray. Let’s look at an example where multiply a Tensor of integers by 3 using numpy.multiply().

import numpy as np
import tensorflow as tf

t = tf.constant([[1,3],[5,7]])
arr = np.multiply(t, 3)

print(arr)
print(type(arr))

Let’s run the code to see the result of the operation

[[ 3  9]
 [15 21]]
<class 'numpy.ndarray'>

Convert Tensor to NumPy Array using eval() or run() in TensorFlow 1.x

TensorFlow versions 1.x use Session objects to encapsulate the execution environment of Operation objects and the evaluation environment of Tensor objects. We can use the TensorFlow 1.x API using tf.compat.v1. We can convert a tensor to a NumPy array using the built-in eval() method and pass tf.compat.v1.Session() as an argument. Let’s look at an example

import tensorflow as tf
tf.compat.v1.disable_eager_execution()

t = tf.constant([[1,3],[5,7]])
arr = t.eval(session=tf.compat.v1.Session())

print(arr)
print(type(arr))

Note that we also have to disable eager execution in order to use eval(). Let’s run the code to see the result:

[[1 3]
 [5 7]]
<class 'numpy.ndarray'>

We can also use Session.run() and pass the tensor as an argument to the run() method. Let’s look at an example:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()

t = tf.constant([[1,3],[5,7]])
arr = tf.compat.v1.Session().run(t)

print(arr)
print(type(arr))
[[1 3]
 [5 7]]
<class 'numpy.ndarray'>

Note that not every tensor returned by eval() / Session.run() is a NumPy array. For example, SparseTensors return as SparseTensorValue. Let’s look at an example:

import tensorflow as tf
tf.compat.v1.disable_eager_execution()

t = tf.SparseTensor([[0, 0]],[1],[1,2])
arr = t.eval(session=tf.compat.v1.Session())

print(arr)
print(type(arr))
SparseTensorValue(indices=array([[0, 0]]), values=array([1], dtype=int32), dense_shape=array([1, 2]))
<class 'tensorflow.python.framework.sparse_tensor.SparseTensorValue'>

Although this method works, using Session objects and eval is outdated. TensorFlow 2 provides a function-based approach to graph computation with eager execution enabled by default. You can migrate your existing TensorFlow 1.x code to TensorFlow 2 by following the Tensorflow migration tutorial.

Summary

Congratulations on reading to the end of this tutorial. We have gone through the various ways to convert a TensorFlow tensor to a NumPy array for both Tensorflow 2.x and 1.x.

For further reading on TensorFlow, go to the article:

How to Solve ModuleNotFoundError: No module named ‘tensorflow.contrib’

Go to the online courses page on Python to learn more about Python for data science and machine learning.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee ✨