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

时间:2018-03-30 03:36:32

标签: python tensorflow

使用标准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' object has no attribute 'tensor_shape'

1 个答案:

答案 0 :(得分:11)

您可以使用{'request_token': 'p87tOTSXRSp4O20TGr870n2JiXFKISIh', 'action': 'login', 'status': 'success'} p87tOTSXRSp4O20TGr870n2JiXFKISIh 功能,也可以执行.numpy()。例如:

numpy.array(y)

请参阅the section in the eager execution guide

希望有所帮助。