Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

python - Tensorflow: How do I convert a EagerTensor into a numpy array?

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)
print(type(z))

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

Output:

[10 11 12 13 14]
<class 'numpy.ndarray'>

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)
print(type(y))

Output:

tf.Tensor([10 11 12 13 14], shape=(5,), dtype=int64)
<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.

Edit:

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'.

question from:https://stackoverflow.com/questions/49568041/tensorflow-how-do-i-convert-a-eagertensor-into-a-numpy-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

Hope that helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...