[python] Convert a tensor to numpy array in Tensorflow?

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

This question is related to python numpy tensorflow

The answer is


You can use keras backend function.

import tensorflow as tf
from tensorflow.python.keras import backend 

sess = backend.get_session()
array = sess.run(< Tensor >)

print(type(array))

<class 'numpy.ndarray'>

I hope it helps!


You can convert a tensor in tensorflow to numpy array in the following ways.

First: Use np.array(your_tensor)

Second: Use your_tensor.numpy


If you see there is a method _numpy(), e.g for an EagerTensor simply call the above method and you will get an ndarray.


I have faced and solved the tensor->ndarray conversion in the specific case of tensors representing (adversarial) images, obtained with cleverhans library/tutorials.

I think that my question/answer (here) may be an helpful example also for other cases.

I'm new with TensorFlow, mine is an empirical conclusion:

It seems that tensor.eval() method may need, in order to succeed, also the value for input placeholders. Tensor may work like a function that needs its input values (provided into feed_dict) in order to return an output value, e.g.

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

Please note that the placeholder name is x in my case, but I suppose you should find out the right name for the input placeholder. x_input is a scalar value or array containing input data.

In my case also providing sess was mandatory.

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


I was searching for days for this command.

This worked for me outside any session or somthing like this.

# you get an array = your tensor.eval(session=tf.compat.v1.Session())
an_array = a_tensor.eval(session=tf.compat.v1.Session())

https://kite.com/python/answers/how-to-convert-a-tensorflow-tensor-to-a-numpy-array-in-python


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 any tensor returned by Session.run or eval() is a NumPy array. Sparse Tensors for example are returned as SparseTensorValue:

>>> print(type(tf.Session().run(tf.SparseTensor([[0, 0]],[1],[1,2]))))
<class 'tensorflow.python.framework.sparse_tensor.SparseTensorValue'>

You need to:

  1. encode the image tensor in some format (jpeg, png) to binary tensor
  2. evaluate (run) the binary tensor in a session
  3. turn the binary to stream
  4. feed to PIL image
  5. (optional) displaythe image with matplotlib

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)

This worked for me. You can try it in a ipython notebook. Just don't forget to add the following line:

%matplotlib inline

Maybe 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)

A simple example could 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 a to be converted into a numpy array

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

As simple as that!


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


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to numpy

Unable to allocate array with shape and data type How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function? Numpy, multiply array with scalar TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'" Pytorch tensor to numpy array Numpy Resize/Rescale Image what does numpy ndarray shape do? How to round a numpy array? numpy array TypeError: only integer scalar arrays can be converted to a scalar index

Examples related to tensorflow

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Module 'tensorflow' has no attribute 'contrib' Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session' Could not install packages due to an EnvironmentError: [WinError 5] Access is denied: How do I use TensorFlow GPU? Which TensorFlow and CUDA version combinations are compatible? Could not find a version that satisfies the requirement tensorflow pip3: command not found How to import keras from tf.keras in Tensorflow? Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2