Do you want to convert the Tensorflow tensor to NumPy array? If yes then you have come to the right place. In this entire tutorial, You will know how to convert TensorFlow tensor to NumPy array step by step.
Steps to Convert Tensorflow Tensor to Numpy array
Step 1: Import the required libraries.
The first step is to import the required library and it is Tensorflow. Let’s import it using the import statement.
import tensorflow as tf
Step 2: Create a Sample Tensorflow tensor.
Now let’s create a sample tensor for implementing the conversion to the NumPy array. In my example, I am creating a simple tensor of constant values. To do so you have to use the tf.constant() method.
Execute the code below to create it.
tensor = tf.constant([[10,20,30],[40,50,60],[70,80,90]])
Output

To see the type of the object just pass the tensor variable inside the type().
print(type(tensor))

You can clearly see in the output that the tensor is created. In the next section, I will show you the methods to convert Tensorflow Tensor to Numpy array.
Step 3: Methods to convert Tensorflow Tensor to Numpy array
In this step, I will show you the two methods to convert tensor to NumPy array.
Method 1: Using the numpy() method.
If you have already installed the latest version and Eager Execution is already enabled. Then you can directly use your_tensor.numpy() function. For example, I want to convert the tensor created in step 2 to the NumPy array, then I will execute the following lines of code.
numpy_array = tensor.numpy()
print(numpy_array)
Output

Now if you use the type() method then you will see it is a NumPy array object.
print(type(numpy_array))
Output

Method 2: Using the eval() method.
This method will be used when you have installed the TensorFlow version 1.0. And if you have already installed the Tensortflow v2.0 then you have to first disable V2 behavior. Then you are able to do the conversion. I am using the same tensor as I used in the above method 1. Use the following lines of code to convert the TensorFlow tensor to a NumPy array.
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
tensor = tf.constant([[10,20,30],[40,50,60],[70,80,90]])
tensor.eval(session=tf.Session())
Output

You can clearly see in the above figure the converted tensor is a NumPy array.
Conclusion
These are the methods to convert the TensorFlow tensor to NumPy array. Which method do you want to use.? The answer is clear in the future method 2 will be deprecated. Thus use method 1 if you want. And if you have not installed TensorFlow 2 then use method 2. Here you can explore other modules for tensorflow numpy.

I hope you have liked and understood this article. Even if you have any queries then you can contact us for more solutions.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.