In this Python tutorial, we will learn how to convert the Tensorflow Tensor to NumPy array. Also, we will cover the following topics.
- TensorFlow tensor to numpy array without session
- TensorFlow eager tensor to numpy
- TensorFlow 2 tensor to numpy
- Tensorflow transform tensor to numpy array
- Tensorflow sparse tensor to numpy
- Tensorflow tensor vs numpy array
Tensorflow Tensor to numpy
- In this section, we will learn the conversion of Tensor to numpy array in TensorFlow Python.
- In Tensorflow 2.0, tf.session() module has been removed and instead of session, we are going to use the tf.compat.v1.disable_eager_execution() for running the session. To convert the tensor into a numpy array first we will import the eager_execution function along with the TensorFlow library.
- Next, we will create the constant values by using the tf.constant() function and, then we are going to run the session by using the syntax session=tf.compat.v1.Session() in eval() function.
Example:
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
new_val = tf.constant([[15,78,24],[17,27,39]])
new_result = new_val.eval(session=tf.compat.v1.Session())
new_result
Here is the implementation of the following given code
Read: Python TensorFlow reduce_sum
TensorFlow tensor to numpy array without session
- In this section, we will learn how to convert the tensor with numpy array in Tensorflow Python without session.
- To do this task first we are going to use the .numpy() function in tensor and this is an in-built method and it will help the user to convert the tensor into a numpy array.
- Now to create a tensor first, we will import the TensorFlow library and then declare a variable. Next, we will use the tf.constant() function for creating a tensor of constant values. By using the new_tens_val.numpy() function you can easily get the numpy array values.
Syntax:
Let’s have a look at the Syntax and understand the working of the tf.constant() function
tf.constant
(
value,
dtype=None,
shape=None,
name='const'
)
Example:
Let’s, take an example and check how to convert the tensor to a numpy array in Tensorflow Python without session
Source Code:
import tensorflow as tf
new_tens_val=tf.constant([[24,56,78],
[16,18,29],
[23,46,78]])
result=new_tens_val.numpy()
result
Here is the Screenshot of the following given code
As you can see in the Screenshot the output displays the NumPy array.
Read: TensorFlow get shape
TensorFlow eager tensor to numpy
- Here we are going to discuss how to convert the tensor to numpy array in TensorFlow by using eager_execution() function.
- This function is not used for graphs it basically calculates the values of tensors and it supports both TPU and GPU. If you are using TensorFlow 2.0 version then it can easily work on the Program.
- To create the session we will used the session=tf.compat.v1.Session() syntax and it will help the user to convert the tensor values into numpy array but first you have to import tf.compat.v1.disable_eager_execution() function.
Source Code:
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
values = tf.constant([[23,34,96],[27,99,89]])
output = values.eval(session=tf.compat.v1.Session())
output
Here is the execution of the following given code
Read: Python TensorFlow reduce_mean
TensorFlow 2 tensor to numpy
- In this example we are going to learn how to convert tensor with numpy in TensorFlow 2.0 version.
- To perform this particular task we are going to use the tf.make_tensor_proto() method. This method will help the user to get the numpy array from the tensor and this method is available in Tensorflow 2.0. If you are using the old version of TensorFlow 1.x then you can easily use the eval() or session() function.
- In this example, we have created the tensorproto and it is an object that has certain types and shapes and it will check the condition if the shape value is none then it specifies the numpy array.
Syntax:
Let’s have a look at the Syntax and understand the working of the tf.make_tensor_proto() method
tf.make_tensor_proto
(
values,
dtype=None,
shape=None,
verify_shape=False,
allow_broadcast=False
)
- It consists of a few parameters
- values: This parameter indicates the values we have to insert in this method.
- dtype: By default it takes none value and it is an optional parameter and it represents with tensor_pb2.
- shape:This parameter specifies the dimension of tensor.
- verify_shape: By default, it takes ‘False’ value and it verify the shape of values.
Example:
import tensorflow as tf
new_val = tf.constant([[25,37,89],[56,14,90]])
result = tf.make_tensor_proto(new_val)
d=tf.make_ndarray(result)
d
In the following given code, we have used the tf.constant() function for the constant values and then we have declared a variable named ‘result’ and assigned the tf.make_tensor_proto() function. Once you will execute this code the output displays the conversion of the tensor into a numpy array.
Here is the Output of the following given code
Read: Import error no module named TensorFlow
Tensorflow transform tensor to numpy array
- Here we are going to learn how to transform the tensor with a numpy array in TensorFlow Python.
- To perform this particular task we are going to use the .numpy() function and this method is available in the TensorFlow module package. In this example, we will create a Tensor Object, and then we are going to apply the tensor.numpy() function.
Example:
import tensorflow as tf
cons_values=tf.constant([[14,28,48],
[67,92,189],
[45,98,178]]) #tensor object
new_output=cons_values.numpy()
new_output
In the above example, the cons_values represent the tensor object in which we have assigned the tf.constant() function and within this function, we have passed the integer values.
After that, we declared a variable named ‘new_output’ and assigned the tensor.numpy() function. Once you will print ‘new_output’ then the result displays the NumPy array.
Here is the implementation of the following given code
As you can see in the Screenshot, the tensor values have been transformed into a numpy array.
Read: Python TensorFlow one_hot
Tensorflow sparse tensor to numpy
- In this Program, we will learn how to convert the sparse tensor to a numpy array in TensorFlow Python.
- In Python spare tensors stores lots of zeros elements and to contain the zero values in the tensor we have to store them in a storage manner this method is used when we are working in Natural language processing. In this function, we will not encode the non-zero values.
- While in the case of dense tensors the maximum values are nonzeros and it is faster in indices as compared to sparse.
- In this example, we will discuss how to convert sparse tensor values to numpy. To do this task we are going to use the eager_execution() function for running the session.
Syntax:
Let’s have a look at the Syntax and understand the working of tf.sparse.SparseTensor() function in Python.
tf.sparse.SparseTensor
(
indices,
values,
dense_shape
)
- It consists of a few parameter
- indices: This parameter indicates the indices of non-zero values and it takes only a 2-dimensional array shape.
- values: These are the actual values and it can be only a 1-dimensional array that passes the values for each element in indices.
- dense_shape: This parameter specifies the dimension and it can be only a 1-dimensional array int64.
Example:
Let’s take an example and check how to convert the sparse tensor to a numpy array in TensorFlow Python.
Source Code:
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
with tf.compat.v1.Session() as val:
new_output = val.run(tf.SparseTensor([[0,16],[24,56]],[15,25],[3,4]))
print(new_output)
Here is the Screenshot of the following given code
As you can see in the Screenshot the output displays the NumPy array.
Read: Convert list to tensor TensorFlow
Tensorflow tensor vs numpy array
- In this section, we will learn the comparison between tensor and numpy array in Python.
Numpy array | Tensor |
---|---|
It is a collection of values of the same data type and it is a library that is available on Python and is mostly used in linear algebra or numerical computation problems. | In Python tensors are immutable and a tensor has a rank tensor that indicates it has only one input. If the function has two inputs then the function will be a second rank tensor. |
NumPy library has many functions like np.sum, np.diff, etc that perform some operation and it always returns as ndarray. | Tensors have a memory like GPU and it takes both scaler and vector values.Tensors are a multidimensional array and to perform some operations on tensor object we can easily use the tf.constant() function,tf,variable(),tf.placeholder. |
You can easily convert the numpy array to tensor by using the tf.convert_to_tensor() method. | While in the case of tensor you can easily convert the tensor into a numpy array by using the tensor.numpy() function. |
In Python NumPy, you can do indexing to use numpy.where() function or slicing method. | In Python TensorFlow, you can use the colon: for slices indices. |
In Python to get the shape of an array, we can easily use the numpy.reshape() function. | In Python TensorFlow, you can use the colon : for slices indices. To get the new shape of the tensor we can easily use the tf.reshape() function. |
Example:
Let’s take an example and we will see the difference between the numpy array and tensor in Python
Source Code:
#Tensor
import tensorflow as tf
tensor_value = tf.constant([1,2,34,5,6])
tensor_value
#numpy array
import numpy as np
new_val = np.array([34,5,7,8,9])
new_val
#if you are using other software then use print statement
#print(new_val)
In the above code, we have just simply created a tensor by importing the TensorFlow library and then using the tf.constant() function in which we have assigned the constant values.
Now, if you are using the Jupyter notebook then, just simply write the variable name it will display the output as well as a datatype. After that, we have created an array by using the np.array() function.
Here is the execution of the following given code
You may also like to read the following TensorFlow tutorials.
- Python TensorFlow truncated normal
- Tensorflow iterates over tensor
- Python TensorFlow random uniform
- Tensorflow custom loss function
- TensorFlow next_batch + Examples
So, in this tutorial, we have learned how to convert the Tensorflow Tensor to NumPy and, we have covered these topics.
- TensorFlow tensor to numpy array without session
- TensorFlow tensor to numpy keras
- TensorFlow eager tensor to numpy
- TensorFlow 2 tensor to numpy
- Tensorflow transform tensor to numpy array
- Tensorflow sparse tensor to numpy
- Tensorflow tensor vs numpy array
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.