Tensorflow: 如何将EagerTensor转换为numpy数组?

75

使用标准的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()

输出:

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

使用急切执行:

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))

输出:

tf.Tensor([10 11 12 13 14], shape=(5,), dtype=int64)
<class 'EagerTensor'>
如果我尝试y.eval(),我会得到NotImplementedError: eval not supported for Eager Tensors。难道没有办法转换吗?这使得Eager Tensorflow完全没有用。
编辑:
有一个函数tf.make_ndarray应该将张量转换为numpy数组,但它会导致AttributeError:'EagerTensor'对象没有属性'tensor_shape'
2个回答

101

你可以使用.numpy()函数,或者你也可以使用numpy.array(y)。例如:

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

请参阅即时执行指南中的此部分


这可以在未启用急切执行的情况下完成吗? - The Doctor

0
通过调用._numpy()方法,也可以获得EagerTensor的numpy视图。在内部,.numpy()会创建此视图的副本。
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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接