Tensorflow: How do I convert a EagerTensor into a numpy array?
Asked Answered
D

2

75

With standard Tensorflow:

import tensorflow as tf

x = tf.convert_to_tensor([0,1,2,3,4], dtype=tf.int64)
y = x + 10

sess = tf.InteractiveSession()
sess.run([
    tf.local_variables_initializer(),
    tf.global_variables_initializer(),
])
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)

z = y.eval(feed_dict={x:[0,1,2,3,4]})
print(z)          # [10 11 12 13 14]
print(type(z))    # <class 'numpy.ndarray'>

coord.request_stop()
coord.join(threads)
sess.close()

With eager execution:

import tensorflow as tf

tf.enable_eager_execution() # requires r1.7

x = tf.convert_to_tensor([0,1,2,3,4], dtype=tf.int64)
y = x + 10

print(y)        # tf.Tensor([10 11 12 13 14], shape=(5,), dtype=int64)
print(type(y))  # <class 'EagerTensor'>

If I try y.eval(), I get NotImplementedError: eval not supported for Eager Tensors. Is there no way to convert this? This makes Eager Tensorflow completely worthless.

There's a function tf.make_ndarray that should convert a tensor to a numpy array but it causes AttributeError: 'EagerTensor' object has no attribute 'tensor_shape'.

Diploblastic answered 30/3, 2018 at 3:36 Comment(0)
F
101

There is a .numpy() function which you can use, alternatively you could also do numpy.array(y). For example:

import tensorflow as tf
import numpy as np

tf.enable_eager_execution()

x = tf.constant([1., 2.])
print(type(x))            # <type 'EagerTensor'>
print(type(x.numpy()))    # <type 'numpy.ndarray'>
print(type(np.array(x)))  # <type 'numpy.ndarray'>

See the section in the eager execution guide.

Forzando answered 31/3, 2018 at 16:2 Comment(1)
Can this be done without eager execution enabled ?Marchall
S
0

It's also possible to get the numpy view of an EagerTensor by calling ._numpy() method. Under the hood, .numpy() creates a copy of this view.

import tensorflow as tf

x = tf.constant([1., 2.])

print(type(x))           # <class 'tensorflow.python.framework.ops.EagerTensor'>

x_np_view = x._numpy()
print(type(x_np_view))   # <class 'numpy.ndarray'>

x_np_view[1] = 100
print(x)                 # tf.Tensor([  1. 100.], shape=(2,), dtype=float32)
Shoring answered 19/6, 2023 at 1:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.