Tensorflow:如何将 EagerTensor 转换为 numpy 数组? [英] Tensorflow: How do I convert a EagerTensor into a numpy array?
问题描述
使用标准 Tensorflow:
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()
输出:
[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 完全没有价值.
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.
有一个函数 tf.make_ndarray
应该将张量转换为 numpy 数组,但它会导致 AttributeError: 'EagerTensor' object has no attribute 'tensor_shape'
.>
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'
.
推荐答案
有一个 .numpy()
函数你可以使用,或者你也可以做 numpy.array(y)
.例如:
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'>
请参阅急切执行指南中的部分.
希望有所帮助.
这篇关于Tensorflow:如何将 EagerTensor 转换为 numpy 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!