How to convert a tensor into a numpy array when using Tensorflow with Python bindings?
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'>