当使用Tensorflow与Python绑定时,如何将一个张量转换为numpy数组?


当前回答

TensorFlow 2.倍

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'对象没有属性'numpy'? 很多人都对这个问题发表了评论,有几个可能的原因:

TF 2.0没有正确安装(在这种情况下,请尝试重新安装),或者 已经安装了TF 2.0,但是由于某种原因禁用了快速执行。在这种情况下,调用tf. compatat .v1.enable_eager_execution()来启用它,或参见下文。


如果禁用了Eager Execution,你可以构建一个图,然后通过tf. compatat .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的映射。

其他回答

TensorFlow 2.倍

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'对象没有属性'numpy'? 很多人都对这个问题发表了评论,有几个可能的原因:

TF 2.0没有正确安装(在这种情况下,请尝试重新安装),或者 已经安装了TF 2.0,但是由于某种原因禁用了快速执行。在这种情况下,调用tf. compatat .v1.enable_eager_execution()来启用它,或参见下文。


如果禁用了Eager Execution,你可以构建一个图,然后通过tf. compatat .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的映射。

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

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)

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

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

Or:

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

EDIT: Session.run或eval()返回的张量不是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
    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'>

就这么简单!

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