【问题标题】:Tensorflow: How do I convert a EagerTensor into a numpy array?Tensorflow:如何将 EagerTensor 转换为 numpy 数组?
【发布时间】:2018-09-09 02:50:17
【问题描述】:

使用标准 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'。

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    您可以使用.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 section in the eager execution guide。

    希望对您有所帮助。

    【讨论】:

    • 可以在不启用急切执行的情况下完成吗?
    猜你喜欢
    • 2021-08-08
    • 1970-01-01
    • 2022-06-13
    • 2020-12-31
    • 1970-01-01
    • 2018-07-21
    • 2016-08-23
    • 2021-10-13
    • 1970-01-01
    相关资源
    最近更新 更多