How to convert tensor to numpy array in TensorFlow?

How to convert tensor to numpy array when using Tensorflow with Python bindings?

+136
python numpy tensorflow
Dec 04 '15 at 20:55
source share
7 answers

Any tensor returned by Session.run or eval is a NumPy array.

 >>> print(type(tf.Session().run(tf.constant([1,2,3])))) <class 'numpy.ndarray'> 

Or:

 >>> sess = tf.InteractiveSession() >>> print(type(tf.constant([1,2,3]).eval())) <class 'numpy.ndarray'> 

Or, equivalently:

 >>> sess = tf.Session() >>> with sess.as_default(): >>> print(type(tf.constant([1,2,3]).eval())) <class 'numpy.ndarray'> 

EDIT: not every tensor returned by Session.run or eval() is a NumPy array. For example, Sparse Tensors return as SparseTensorValue:

 >>> print(type(tf.Session().run(tf.SparseTensor([[0, 0]],[1],[1,2])))) <class 'tensorflow.python.framework.sparse_tensor.SparseTensorValue'> 
+119
Jun 19 '16 at 23:37
source share
โ€” -

To convert back from a tensor to a numpy array, you can simply run .eval() on the converted tensor.

+72
Dec 04 '15 at 20:59 on
source share

TensorFlow 2.0

Swift execution is enabled by default, so just call .numpy() on the Tensor object.

 import tensorflow as tf a = tf.constant([[1, 2], [3, 4]]) b = tf.add(a, 1) tf.multiply(a, b). numpy() # array([[ 2, 6], # [12, 20]], dtype=int32) 

Itโ€™s worth noting (from the documents),

A Numpy array can share memory with a Tensor object. Any changes in one can be reflected in another.

Bold accent mine. A copy may or may not be returned, and this is an implementation detail.




If Eager Execution is disabled, you can plot it and then run it through tf.compat.v1.Session :

 a = tf.constant([[1, 2], [3, 4]]) b = tf.add(a, 1) out = tf.multiply(a, b) out.eval(session=tf.compat.v1.Session()) # array([[ 2, 6], # [12, 20]], dtype=int32) 

See Also TF 2.0 Character Map for mapping the old API to the new.

+8
Jun 12 '19 at 4:50
source share

You need:

  • encode the image tensor in some format (jpeg, png) to a binary tensor
  • evaluate (run) a binary tensor in a session
  • turn binary into stream
  • submit to PIL image
  • (optional) displays the image using matplotlib

the code:

 import tensorflow as tf import matplotlib.pyplot as plt import PIL ... image_tensor = <your decoded image tensor> jpeg_bin_tensor = tf.image.encode_jpeg(image_tensor) with tf.Session() as sess: # display encoded back to image data jpeg_bin = sess.run(jpeg_bin_tensor) jpeg_str = StringIO.StringIO(jpeg_bin) jpeg_image = PIL.Image.open(jpeg_str) plt.imshow(jpeg_image) 

It worked for me. You can try it on ipython laptop. Remember to add the following line:

 %matplotlib inline 
+5
Apr 17 '16 at 2:59
source share

Perhaps you can try this method:

 import tensorflow as tf W1 = tf.Variable(tf.random_uniform([1], -1.0, 1.0)) init = tf.global_variables_initializer() sess = tf.Session() sess.run(init) array = W1.eval(sess) print (array) 
+3
Mar 21 '17 at 11:32
source share

I encountered and decided to convert tensor-> ndarray in a particular case of tensors representing (competitive) images obtained using cleverhans library / tutorials.

I think my question / answer ( here ) may be a useful example for other cases.

I am new to TensorFlow, my empirical conclusion is:

It looks like the tenor.eval () method might also need a value for input placeholders. A tensor can work as a function that needs input values โ€‹โ€‹(provided in feed_dict ) to return an output value, for example

 array_out = tensor.eval(session=sess, feed_dict={x: x_input}) 

Note that the placeholder name in my case is x , but I suppose you should find the correct name for the input placeholder. x_input is a scalar value or an array containing input.

In my case, also providing sess was mandatory.

My example also covers the matplotlib image rendering part, but this is OT.

+2
Sep 22 '18 at 7:41
source share

A simple example might be

  import tensorflow as tf import numpy as np a=tf.random_normal([2,3],0.0,1.0,dtype=tf.float32) #sampling from a std normal print(type(a)) #<class 'tensorflow.python.framework.ops.Tensor'> tf.InteractiveSession() # run an interactive session in Tf. 

n now if we want this tensor to be converted to a NumPy array

  a_np=a.eval() print(type(a_np)) #<class 'numpy.ndarray'> 

So simple!

+1
Mar 17 '19 at 10:07
source share



All Articles