Python 如何在 TensorFlow 中将张量转换为 numpy 数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34097281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert a tensor into a numpy array in TensorFlow?
提问by mathetes
How to convert a tensor into a numpy array when using Tensorflow with Python bindings?
将 Tensorflow 与 Python 绑定一起使用时,如何将张量转换为 numpy 数组?
采纳答案by Lenar Hoyt
Any tensor returned by Session.run
or eval
is a NumPy 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'>
Or, equivalently:
或者,等效地:
>>> sess = tf.Session()
>>> with sess.as_default():
>>> print(type(tf.constant([1,2,3]).eval()))
<class 'numpy.ndarray'>
EDIT:Not anytensor returned by Session.run
or eval()
is a NumPy array. Sparse Tensors for example are returned as SparseTensorValue:
编辑:不是任何由NumPy 数组返回的张量Session.run
或者eval()
是 NumPy 数组。例如,稀疏张量作为 SparseTensorValue 返回:
>>> print(type(tf.Session().run(tf.SparseTensor([[0, 0]],[1],[1,2]))))
<class 'tensorflow.python.framework.sparse_tensor.SparseTensorValue'>
回答by Rafa? Józefowicz
To convert back from tensor to numpy array you can simply run .eval()
on the transformed tensor.
要将张量转换回 numpy 数组,您只需.eval()
在转换后的张量上运行即可。
回答by Gooshan
You need to:
你需要:
- encode the image tensor in some format (jpeg, png) to binary tensor
- evaluate (run) the binary tensor in a session
- turn the binary to stream
- feed to PIL image
- (optional) displaythe image with matplotlib
- 以某种格式(jpeg、png)将图像张量编码为二进制张量
- 在会话中评估(运行)二进制张量
- 将二进制文件转为流
- 馈送至 PIL 图像
- (可选)用 matplotlib 显示图像
Code:
代码:
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)
This worked for me. You can try it in a ipython notebook. Just don't forget to add the following line:
这对我有用。你可以在 ipython notebook 中尝试。只是不要忘记添加以下行:
%matplotlib inline
回答by lovychen
Maybe you can try,this method:
也许你可以试试,这个方法:
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)
回答by Fabiano Tarlao
I have faced and solved the tensor->ndarrayconversion in the specific case of tensors representing (adversarial) images, obtained with cleverhanslibrary/tutorials.
在使用cleverhans库/教程获得的表示(对抗性)图像的张量的特定情况下,我已经面对并解决了张量- > ndarray转换。
I think that my question/answer (here) may be an helpful example also for other cases.
我认为我的问题/答案(这里)对于其他情况也可能是一个有用的例子。
I'm new with TensorFlow, mine is an empirical conclusion:
我是 TensorFlow 的新手,我的经验结论是:
It seems that tensor.eval() method may need, in order to succeed, also the value for input placeholders.
Tensor may work like a function that needs its input values (provided into feed_dict
) in order to return an output value, e.g.
似乎 tensor.eval() 方法可能需要,为了成功,输入占位符的值。张量可能像一个需要输入值(提供给feed_dict
)以返回输出值的函数一样工作,例如
array_out = tensor.eval(session=sess, feed_dict={x: x_input})
Please note that the placeholder name is xin my case, but I suppose you should find out the right name for the input placeholder.
x_input
is a scalar value or array containing input data.
请注意,在我的情况下,占位符名称是x,但我想您应该找出输入占位符的正确名称。
x_input
是包含输入数据的标量值或数组。
In my case also providing sess
was mandatory.
在我的情况下,提供sess
也是强制性的。
My example also covers the matplotlibimage visualization part, but this is OT.
我的示例还涵盖了matplotlib图像可视化部分,但这是 OT。
回答by Saurabh Kumar
A simple example could be,
一个简单的例子可能是,
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 now if we want this tensor a to be converted into a numpy array
n 现在如果我们想要这个张量 a 被转换成一个 numpy 数组
a_np=a.eval()
print(type(a_np))
#<class 'numpy.ndarray'>
As simple as that!
就如此容易!
回答by cs95
TensorFlow 2.x
TensorFlow 2.x
Eager Executionis enabled by default, so just call .numpy()
on the Tensor object.
默认情况下启用Eager Execution,因此只需调用.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)
It is worth noting (from the docs),
值得注意的是(来自文档),
Numpy array may share memory with the Tensor object. Any changes to one may be reflected in the other.
Numpy 数组可以与 Tensor 对象共享内存。对一个的任何更改都可能反映在另一个中。
Bold emphasis mine. A copy may or may not be returned, and this is an implementation detail.
大胆强调我的。副本可能会也可能不会返回,这是一个实现细节。
If Eager Execution is disabled, you can build a graph and then run it through tf.compat.v1.Session
:
如果 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=tf.compat.v1.Session())
# array([[ 2, 6],
# [12, 20]], dtype=int32)
See also TF 2.0 Symbols Mapfor a mapping of the old API to the new one.
另请参阅TF 2.0 符号映射,了解旧 API 到新 API 的映射。
回答by Lorenz
I was searching for days for this command.
我为这个命令搜索了好几天。
This worked for me outside any session or somthing like this.
这在任何会议或类似的事情之外对我有用。
# 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
https://kite.com/python/answers/how-to-convert-a-tensorflow-tensor-to-a-numpy-array-in-python