在 Tensorflow 中将张量转换为 numpy 数组?

新手上路,请多包涵

使用带有 Python 绑定的 Tensorflow 时如何将张量转换为 numpy 数组?

原文由 mathetes 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 533
2 个回答

张量流 2.x

默认情况下启用 Eager Execution ,因此只需在 Tensor 对象上调用 .numpy()

 import tensorflow as tf

a = tf.constant([[1, 2], [3, 4]])
b = tf.add(a, 1)

a.numpy()
# array([[1, 2],
#        [3, 4]], dtype=int32)

b.numpy()
# array([[2, 3],
#        [4, 5]], dtype=int32)

tf.multiply(a, b).numpy()
# array([[ 2,  6],
#        [12, 20]], dtype=int32)

有关更多信息,请参阅 NumPy 兼容性。值得注意的是(来自文档),

Numpy 数组可能与 Tensor 对象共享内存。 对一个的任何更改都可能反映在另一个中。

大胆强调我的。可能会或可能不会返回副本,这是一个基于数据是在 CPU 还是 GPU 中的实现细节(在后一种情况下,必须从 GPU 到主机内存进行复制)。

但为什么我得到 AttributeError: 'Tensor' object has no attribute 'numpy' .

很多人都评论过这个问题,有几个可能的原因:

  • TF 2.0 未正确安装(在这种情况下,请尝试重新安装),或
  • TF 2.0 已安装,但由于某种原因禁用了急切执行。在这种情况下,请调用 tf.compat.v1.enable_eager_execution() 启用它,或参见下文。

如果 Eager Execution 被禁用,您可以构建一个图形,然后通过 tf.compat.v1.Session 运行它:

 a = tf.constant([[1, 2], [3, 4]])
b = tf.add(a, 1)
out = tf.multiply(a, b)

out.eval(session=tf.compat.v1.Session())
# array([[ 2,  6],
#        [12, 20]], dtype=int32)

另请参阅 TF 2.0 Symbols Map ,了解旧 API 到新 API 的映射。

原文由 cs95 发布,翻译遵循 CC BY-SA 4.0 许可协议

Session.runeval 返回的任何张量都是 NumPy 数组。

 >>> print(type(tf.Session().run(tf.constant([1,2,3]))))
<class 'numpy.ndarray'>

要么:

 >>> sess = tf.InteractiveSession()
>>> print(type(tf.constant([1,2,3]).eval()))
<class 'numpy.ndarray'>

或者,等效地:

 >>> sess = tf.Session()
>>> with sess.as_default():
>>>    print(type(tf.constant([1,2,3]).eval()))
<class 'numpy.ndarray'>

编辑: Session.runeval() 返回的 任何 张量都不是 NumPy 数组。例如,稀疏张量作为 SparseTensorValue 返回:

 >>> print(type(tf.Session().run(tf.SparseTensor([[0, 0]],[1],[1,2]))))
<class 'tensorflow.python.framework.sparse_tensor.SparseTensorValue'>

原文由 Lenar Hoyt 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题