How to convert a tensor into a numpy array when using Tensorflow with Python bindings?
To convert back from tensor to numpy array you can simply run . eval() on the transformed tensor.
To convert a tensor t to a NumPy array in TensorFlow version 2.0 and above, use the t. numpy() built-in method. The resulting object is a NumPy array of type numpy. ndarray .
The difference between a NumPy array and a tensor is that the tensors are backed by the accelerator memory like GPU and they are immutable, unlike NumPy arrays.
Eager 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) 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)
See NumPy Compatibility for more. It is worth noting (from the docs),
Numpy array may share 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 AttributeError: 'Tensor' object has no attribute 'numpy'
?.
A lot of folks have commented about this issue, there are a couple of possible reasons:
tf.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 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 Symbols Map for a mapping of the old API to the new one.
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'>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With