在 Tensorflow 中将张量转换为 numpy 数组?
- 2025-01-07 08:44:00
- admin 原创
- 112
问题描述:
当使用带有 Python 绑定的 Tensorflow 时,如何将张量转换为 numpy 数组?
解决方案 1:
TensorFlow 2.x
默认情况下启用Eager Execution.numpy()
,因此只需调用 Tensor 对象即可。
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,但由于某种原因,eager execution 被禁用。在这种情况下,请调用
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 符号映射,了解旧 API 到新 API 的映射。
解决方案 2:
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'>
解决方案 3:
要将张量转换回 numpy 数组,您只需.eval()
在转换后的张量上运行即可。
解决方案 4:
关于 Tensorflow 2.x
以下方法通常有效,因为默认情况下激活了 Eager Execution:
import tensorflow as tf
a = tf.constant([[1, 2], [3, 4]])
b = tf.add(a, 1)
print(a.numpy())
# [[1 2]
# [3 4]]
但是,由于很多人似乎都发布了错误:
AttributeError: 'Tensor' object has no attribute 'numpy'
我认为公平地说,tensor.numpy()
在图形模式下调用不起作用。这就是您看到此错误的原因。这是一个简单的例子:
import tensorflow as tf
@tf.function
def add():
a = tf.constant([[1, 2], [3, 4]])
b = tf.add(a, 1)
tf.print(a.numpy()) # throws an error!
return a
add()
这里可以找到一个简单的解释:
从根本上讲,无法将图张量转换为 NumPy 数组,因为图不在 Python 中执行 - 因此图执行时没有 NumPy。[...]
TF文档也值得一看。
关于使用 Tensorflow 2.x 的 Keras 模型
这也适用于默认情况下Keras
包装在中的模型tf.function
。如果您确实需要运行,您可以在中tensor.numpy()
设置参数,但这会影响模型的性能。run_eagerly=True
`model.compile(*)`
解决方案 5:
您需要:
将某种格式(jpeg、png)的图像张量编码为二进制张量
在会话中评估(运行)二进制张量
将二进制文件转换为流
馈送到 PIL 图像
(可选)使用 matplotlib 显示图像
代码:
import tensorflow as tf
import matplotlib.pyplot as plt
import PIL
...
image_tensor = <your decoded image tensor>
jpeg_bin_tensor = tf.image.encode_jpeg(image_tensor)
with tf.Session() as sess:
# display encoded back to image data
jpeg_bin = sess.run(jpeg_bin_tensor)
jpeg_str = StringIO.StringIO(jpeg_bin)
jpeg_image = PIL.Image.open(jpeg_str)
plt.imshow(jpeg_image)
这对我来说很有效。你可以在 ipython 笔记本中尝试一下。只是不要忘记添加以下行:
%matplotlib inline
解决方案 6:
也许你可以尝试这个方法:
import tensorflow as tf
W1 = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
array = W1.eval(sess)
print (array)
解决方案 7:
我曾经遇到并解决了在张量表示(对抗性)图像的特定情况下的张量->ndarray转换问题,该问题通过cleverhans库/教程获得。
我认为我的问题/答案(这里)对于其他情况也可能是一个有用的例子。
我是 TensorFlow 的新手,我有一个经验结论:
似乎 tensor.eval() 方法可能还需要输入占位符的值才能成功。Tensor 的工作方式可能类似于需要其输入值(提供给feed_dict
)才能返回输出值的函数,例如
array_out = tensor.eval(session=sess, feed_dict={x: x_input})
请注意,在我的情况下,占位符名称是x,但我想您应该找到输入占位符的正确名称。 x_input
是一个包含输入数据的标量值或数组。
就我而言,提供也是sess
强制性的。
我的示例还涵盖了matplotlib图像可视化部分,但这是 OT。
解决方案 8:
我花了好几天的时间寻找这个命令。
这对我来说在任何会话或类似的东西之外都有效。
# you get an array = your tensor.eval(session=tf.compat.v1.Session())
an_array = a_tensor.eval(session=tf.compat.v1.Session())
https://kite.com/python/answers/how-to-convert-a-tensorflow-tensor-to-a-numpy-array-in-python
解决方案 9:
您可以使用 keras 后端函数。
import tensorflow as tf
from tensorflow.python.keras import backend
sess = backend.get_session()
array = sess.run(< Tensor >)
print(type(array))
<class 'numpy.ndarray'>
希望对您有帮助!
解决方案 10:
一个简单的例子是,
import tensorflow as tf
import numpy as np
a=tf.random_normal([2,3],0.0,1.0,dtype=tf.float32) #sampling from a std normal
print(type(a))
#<class 'tensorflow.python.framework.ops.Tensor'>
tf.InteractiveSession() # run an interactive session in Tf.
n 现在如果我们想把这个张量 a 转换成一个 numpy 数组
a_np=a.eval()
print(type(a_np))
#<class 'numpy.ndarray'>
就这么简单!
解决方案 11:
如果您看到有一个方法_numpy(),例如对于 EagerTensor,只需调用上述方法,您就会得到一个 ndarray。
解决方案 12:
我设法使用以下命令将 TensorGPU 转换为 np.array:
np.array(tensor_gpu.as_cpu())
(直接使用 TensorGPU 只会导致包含 TensorGPU 的单元素数组)。
解决方案 13:
TensorFlow 1.x
文件夹tf.1
,只需使用以下命令:
a = tf.constant([[1, 2], [3, 4]])
b = tf.add(a, 1)
out = tf.multiply(a, b)
out.eval(session=tf.Session())
输出结果为:
# array([[ 2, 6],
# [12, 20]], dtype=int32)