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

Convert a tensor to numpy array in Tensorflow?

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

要从张量转换回 numpy 数组,您只需在转换后的张量上 运行 .eval()

您需要:

  1. 将某种格式(jpeg、png)的图像张量编码为二进制张量
  2. 在一个会话中评估 (运行) 二元张量
  3. 将二进制转为流
  4. 提供给 PIL 图片
  5. (可选)用 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

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'>

也许你可以试试,这个方法:

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)

我已经面对并解决了 tensor->ndarray 在表示(对抗)图像的张量的特定情况下的转换,用 cleverhans[=35= 获得] library/tutorials.

我认为我的 question/answer () 对于其他情况也可能是一个有用的例子。

我是 TensorFlow 的新手,我的是一个经验结论:

为了成功,tensor.eval() 方法似乎还需要输入 placeholders 的值。 张量可能像函数一样工作,需要其输入值(提供给 feed_dict)以便 return 输出值,例如

array_out = tensor.eval(session=sess, feed_dict={x: x_input})

请注意,占位符名称在我的例子中是 x,但我想您应该为输入找到正确的名称 placeholder. x_input 是标量值或包含输入数据的数组。

就我而言,还必须提供 sess

我的示例还涵盖了 matplotlib 图像可视化部分,但这是 OT。

一个简单的例子可以是,

    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'>

就这么简单!

TensorFlow 2.x

Eager Execution is enabled by default, so just call .numpy() 在 Tensor 对象上。

import tensorflow as tf

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

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

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

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

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

Numpy array may share a memory with the Tensor object. Any changes to one may be reflected in the other.

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

但为什么我得到 AttributeError: 'Tensor' object has no attribute 'numpy'?.
很多人都评论过这个问题,有几个可能的原因:

  • TF 2.0 未正确安装(在这种情况下,请尝试 re-installing),或
  • 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=<b>tf.compat.v1.Session()</b>)    
# array([[ 2,  6],
#        [12, 20]], dtype=int32)

另请参阅 TF 2.0 Symbols Map,了解旧 API 到新

的映射。

我为这个命令搜索了好几天。

这对我有用 session 或类似的东西。

# 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

可以使用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'>

希望对您有所帮助!

如果你看到有一个方法 _numpy(), 例如,对于 EagerTensor,只需调用上述方法,您将获得一个 ndarray。

您可以通过以下方式将tensorflow中的张量转换为numpy数组。

第一个: 使用 np.array(your_tensor)

第二个: 使用 your_tensor.numpy

关于 Tensorflow 2.x

以下通常有效,因为默认情况下会激活急切执行:

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()

可以找到一个简单的解释here:

Fundamentally, one cannot convert a graph tensor to numpy array because the graph does not execute in Python - so there is no NumPy at graph execution. [...]

TFdocs.

也值得一看

关于使用 Tensorflow 的 Keras 模型 2.x

这也适用于 Keras 模型,默认情况下它们被包裹在 tf.function 中。如果确实需要运行tensor.numpy(),可以在model.compile(*)中设置参数run_eagerly=True,但这会影响模型的性能