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


当前回答

如果你看到有一个方法_numpy(), 例如,对于一个EagerTensor,简单地调用上面的方法,你将得到一个ndarray。

其他回答

你需要:

将图像张量以某种格式(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)

这对我很管用。你可以在ippython笔记本上试试。别忘了加上下面这行:

%matplotlib inline

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

我成功地把TensorGPU变成了np。数组使用以下 :

np.array(tensor_gpu.as_cpu())

(直接使用TensorGPU只会导致包含TensorGPU的单元素数组)。

你可以用以下方法将tensorflow中的张量转换为numpy数组。

第一: 使用np.array (your_tensor)

第二: 使用your_tensor.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'>

就这么简单!