如何在TensorFlow中将张量转换为numpy数组?

mat*_*tes 144 python numpy tensorflow

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

Len*_*oyt 121

Session.run或返回的任何张量eval是NumPy数组.

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

要么:

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

或者,等效地:

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

编辑:没有任何张量返回Session.run或是eval()NumPy数组.例如,稀疏张量作为SparseTensorValue返回:

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

  • AttributeError:模块“tensorflow”没有属性“Session” (4认同)

Raf*_*icz 74

要从张量转换回numpy数组,您可以简单地运行.eval()转换张量.

  • 我得到`ValueError:无法使用'eval()'评估张量:没有注册默认会话.使用'with sess.as_default()'或将显式会话传递给'eval(session = sess)'`这是否仅在tenoflow会话期间可用? (10认同)
  • @EduardoPignatelli你需要在会​​话中运行`.eval()`方法调用:`sess = tf.Session(); 与sess.as_default():print(my_tensor.eval())` (4认同)
  • 澄清:yourtensor.eval() (3认同)

cs9*_*s95 22

TensorFlow 2.0

急切执行默认情况下.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)
Run Code Online (Sandbox Code Playgroud)

值得注意的是(来自文档),

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

大胆强调我的。副本可能会也可能不会返回,这是实现的详细信息。


如果禁用了“急切执行”,则可以构建一个图形,然后通过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)
Run Code Online (Sandbox Code Playgroud)

另请参见TF 2.0符号映射,以获取旧API到新API的映射。

  • 我在 TF 2.0 中收到以下错误:“‘Tensor’对象没有属性‘numpy’” (28认同)
  • 不,我没有禁用急切执行。仍然得到 AttributeError: 'Tensor' object has no attribute 'numpy' (12认同)
  • 如何在 tf.function 内部执行此操作? (8认同)
  • 为什么我会收到 AttributeError: 'Tensor' object has no attribute 'numpy' (5认同)
  • 我使用 Tensorflow 2.x,启用了 eagerexecution,但我的张量仍然是 Tensor,而不是 EagerTensor,并且 .numpy() 不起作用。 (4认同)

Alo*_*her 18

关于 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]]
Run Code Online (Sandbox Code Playgroud)

然而,由于很多人似乎都发布了错误:

AttributeError: 'Tensor' object has no attribute 'numpy'
Run Code Online (Sandbox Code Playgroud)

我认为公平地说,tensor.numpy()在图形模式下调用是行不通的。这就是您看到此错误的原因。这是一个简单的例子:

AttributeError: 'Tensor' object has no attribute 'numpy'
Run Code Online (Sandbox Code Playgroud)

可以在这里找到一个简单的解释:

从根本上来说,无法将图张量转换为 numpy 数组,因为该图不在 Python 中执行 - 因此在图执行时没有 NumPy。[...]

TF文档也值得一看。

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

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


lov*_*hen 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)
Run Code Online (Sandbox Code Playgroud)


Goo*_*han 5

你需要:

  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)
Run Code Online (Sandbox Code Playgroud)

这对我有用。您可以在ipython笔记本中尝试。只是不要忘记添加以下行:

%matplotlib inline
Run Code Online (Sandbox Code Playgroud)