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


当前回答

一个简单的例子是,

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

就这么简单!

其他回答

一个简单的例子是,

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

就这么简单!

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

我希望这能有所帮助!

任何由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'>

为了这个命令,我找了好几天。

这对我来说在任何会议之外或类似的事情都很有效。

# 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

TensorFlow 1.倍

文件夹特遣部队。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)