TensorFlow – How to create a numpy ndarray from a tensor

• Last Updated : 01 Aug, 2020

TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks.

To create a numpy array from Tensor, Tensor is converted to a proto tensor first.

Method Used:

• make_ndarray: This method accepts a TensorProto as input and returns a numpy array with same content as TensorProto.

Example 1:

Python3

 # importing the libraryimport tensorflow as tf  # Initializing Inputvalue = tf.constant([1, 15, 10], dtype = tf.float64)  # Printing the Inputprint("Value: ", value)  # Converting Tensor to TensorProtoproto = tf.make_tensor_proto(value)  # Generating numpy arrayres = tf.make_ndarray(proto)  # Printing the resulting numpy arrayprint("Result: ", res)

Output:

Value:  tf.Tensor([ 1. 15. 10.], shape=(3, ), dtype=float64)
Result:  [ 1. 15. 10.]

Example 2: This example uses a Tensor with shape (2, 2) so the shape of resulting array will be (2, 2).

Python3

 # importing the libraryimport tensorflow as tf  # Initializing Inputvalue = tf.constant([[1, 2], [3, 4]], dtype = tf.float64)  # Printing the Inputprint("Value: ", value)  # Converting Tensor to TensorProtoproto = tf.make_tensor_proto(value)  # Generating numpy arrayres = tf.make_ndarray(proto)  # Printing the resulting numpy arrayprint("Result: ", res)

Output:

Value:  tf.Tensor(
[[1. 2.]
[3. 4.]], shape=(2, 2), dtype=float64)
Result:  [[1. 2.]
[3. 4.]]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

My Personal Notes arrow_drop_up