Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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.

 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

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 library
import tensorflow as tf
  
# Initializing Input
value = tf.constant([1, 15, 10], dtype = tf.float64)
  
# Printing the Input
print("Value: ", value)
  
# Converting Tensor to TensorProto
proto = tf.make_tensor_proto(value)
  
# Generating numpy array
res = tf.make_ndarray(proto)
  
# Printing the resulting numpy array
print("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 library
import tensorflow as tf
  
# Initializing Input
value = tf.constant([[1, 2], [3, 4]], dtype = tf.float64)
  
# Printing the Input
print("Value: ", value)
  
# Converting Tensor to TensorProto
proto = tf.make_tensor_proto(value)
  
# Generating numpy array
res = tf.make_ndarray(proto)
  
# Printing the resulting numpy array
print("Result: ", res)

Output:

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





My Personal Notes arrow_drop_up
Recommended Articles
Page :