使用带有 Python 绑定的 Tensorflow 时如何将张量转换为 numpy 数组?
原文由 mathetes 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用带有 Python 绑定的 Tensorflow 时如何将张量转换为 numpy 数组?
原文由 mathetes 发布,翻译遵循 CC BY-SA 4.0 许可协议
Session.run
或 eval
返回的任何张量都是 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.run
或 eval()
返回的 任何 张量都不是 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 许可协议
2 回答5.1k 阅读✓ 已解决
2 回答1.1k 阅读✓ 已解决
4 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
3 回答1.2k 阅读✓ 已解决
1 回答1.7k 阅读✓ 已解决
1 回答1.2k 阅读✓ 已解决
张量流 2.x
默认情况下启用 Eager Execution ,因此只需在 Tensor 对象上调用
.numpy()
。有关更多信息,请参阅 NumPy 兼容性。值得注意的是(来自文档),
大胆强调我的。可能会或可能不会返回副本,这是一个基于数据是在 CPU 还是 GPU 中的实现细节(在后一种情况下,必须从 GPU 到主机内存进行复制)。
但为什么我得到
AttributeError: 'Tensor' object has no attribute 'numpy'
? .很多人都评论过这个问题,有几个可能的原因:
tf.compat.v1.enable_eager_execution()
启用它,或参见下文。如果 Eager Execution 被禁用,您可以构建一个图形,然后通过
tf.compat.v1.Session
运行它:另请参阅 TF 2.0 Symbols Map ,了解旧 API 到新 API 的映射。