346

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

cs95's user avatar
cs95
406k106 gold badges744 silver badges797 bronze badges
askedDec 4, 2015 at 20:55
mathetes's user avatar
0

13 Answers13

249

TensorFlow 2.x

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

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

SeeNumPy Compatibility for more. It is worth noting (from the docs),

Numpy array may share a memory with the Tensor object.Any changes to one may be reflected in the other.

Bold emphasis mine. A copy may or may not be returned, and this is an implementation detail based on whether the data is in CPU or GPU (in the latter case, a copy has to be made from GPU to host memory).

But why am I getting theAttributeError: 'Tensor' object has no attribute 'numpy'?.
A lot of folks have commented about this issue, there are a couple of possible reasons:

  • TF 2.0 is not correctly installed (in which case, try re-installing), or
  • TF 2.0 is installed, but eager execution is disabled for some reason. In such cases, calltf.compat.v1.enable_eager_execution() to enable it, or see below.

If Eager Execution is disabled, you can build a graph and then run it throughtf.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 alsoTF 2.0 Symbols Map for a mapping of the old API to the new one.

Innat's user avatar
Innat
17.3k6 gold badges60 silver badges115 bronze badges
answeredJun 12, 2019 at 4:50
cs95's user avatar
Sign up to request clarification or add additional context in comments.

12 Comments

How to do this INSIDE a tf.function?
I get the following error in TF 2.0: "'Tensor' object has no attribute 'numpy'"
No I did not disable eager execution. Still get AttributeError: 'Tensor' object has no attribute 'numpy'
why do I get an AttributeError: 'Tensor' object has no attribute 'numpy'
I use Tensorflow 2.x, eager execution is enabled and still my tensor is a Tensor and not an EagerTensor and .numpy() does not work.
|
146

Any tensor returned bySession.run oreval 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: Notany tensor returned bySession.run oreval() 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'>
dopexxx's user avatar
dopexxx
2,7061 gold badge24 silver badges30 bronze badges
answeredJun 19, 2016 at 23:37
Lenar Hoyt's user avatar

3 Comments

AttributeError: module 'tensorflow' has no attribute 'Session'
If eval alone suffices, what is the reason for having Session.run or InteractiveSession in all of these options?
@Ceph If you run without a session, you get the following error:ValueError: Cannot evaluate tensor using 'eval()': No default session is registered. Use 'with sess.as_default()' or pass an explicit session to 'eval(session=sess)'
83

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

answeredDec 4, 2015 at 20:59
Rafał Józefowicz's user avatar

6 Comments

to clarify: yourtensor.eval()
I getValueError: Cannot evaluate tensor using 'eval()': No default session is registered. Use 'with sess.as_default()' or pass an explicit session to 'eval(session=sess)' Is this usable only during a tensoflow session?
@EduardoPignatelli It works for me in Theano with no extra work. Not sure about tf.
@EduardoPignatelli you need to run the.eval() method call from inside a session:sess = tf.Session(); with sess.as_default(): print(my_tensor.eval())
I have the same issue!
|
20

Regarding Tensorflow 2.x

The following generally works, since eager execution is activated by default:

import tensorflow as tfa = tf.constant([[1, 2], [3, 4]])                 b = tf.add(a, 1)print(a.numpy())# [[1 2]#  [3 4]]

However, since a lot of people seem to be posting the error:

AttributeError: 'Tensor' object has no attribute 'numpy'

I think it is fair to mention that callingtensor.numpy() in graph mode willnot work. That is why you are seeing this error. Here is a simple example:

import tensorflow as tf@tf.functiondef add():  a = tf.constant([[1, 2], [3, 4]])                   b = tf.add(a, 1)  tf.print(a.numpy()) # throws an error!  return aadd()

A simple explanation can be foundhere:

Fundamentally, one cannot convert a graph tensor to numpy array because the graph does not execute in Python - so there is no NumPy at graph execution. [...]

It is also worth taking a look at the TFdocs.

Regarding Keras models with Tensorflow 2.x

This also applies toKeras models, which are wrapped in atf.function by default. If you really need to runtensor.numpy(), you can set the parameterrun_eagerly=True inmodel.compile(*), but this will influence the performance of your model.

answeredJan 20, 2022 at 8:05
AloneTogether's user avatar

Comments

9

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 tfimport matplotlib.pyplot as pltimport 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
answeredApr 17, 2016 at 14:59
Gooshan's user avatar

Comments

8

Maybe you can try,this method:

import tensorflow as tfW1 = 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)
answeredMar 21, 2017 at 11:32
lovychen's user avatar

Comments

4

I have faced and solved thetensor->ndarray conversion in the specific case of tensors representing (adversarial) images, obtained withcleverhans 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 inputplaceholders. Tensor may work like a function that needs its input values (provided intofeed_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 isx in my case, but I suppose you should find out the right name for the inputplaceholder.x_input is a scalar value or array containing input data.

In my case also providingsess was mandatory.

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

answeredSep 22, 2018 at 7:41
Fabiano Tarlao's user avatar

Comments

4

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

answeredMay 5, 2020 at 5:44
Lorenz's user avatar

Comments

3

You can use keras backend function.

import tensorflow as tffrom tensorflow.python.keras import backend sess = backend.get_session()array = sess.run(< Tensor >)print(type(array))<class 'numpy.ndarray'>

I hope it helps!

answeredJun 9, 2020 at 12:43
Ebin Zacharias's user avatar

Comments

2

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.

nnow 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!

answeredMar 17, 2019 at 10:07
Saurabh Kumar's user avatar

1 Comment

// is not for commenting in python. Please edit your answer.
2

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

answeredSep 9, 2020 at 2:13
Dhnesh Dhingra's user avatar

Comments

1

I managed to transform a TensorGPU into an np.array using the following :

np.array(tensor_gpu.as_cpu())

(using the TensorGPU directly would only lead to a single-element array containing the TensorGPU).

answeredDec 12, 2022 at 18:45
Skippy le Grand Gourou's user avatar

Comments

0

TensorFlow 1.x

Foldertf.1, just use the following commands:

a = tf.constant([[1, 2], [3, 4]])                 b = tf.add(a, 1)out = tf.multiply(a, b)out.eval(session=tf.Session())

And the output would be:

# array([[ 2,  6],#       [12, 20]], dtype=int32)
answeredJan 9, 2023 at 16:06
Hadij's user avatar

Comments

Protected question. To answer this question, you need to have at least 10 reputation on this site (not counting theassociation bonus). The reputation requirement helps protect this question from spam and non-answer activity.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.