【发布时间】:2016-03-09 21:55:41
【问题描述】:
在使用带有 Python 绑定的 Tensorflow 时如何将张量转换为 numpy 数组?
【问题讨论】:
标签: python numpy tensorflow
在使用带有 Python 绑定的 Tensorflow 时如何将张量转换为 numpy 数组?
【问题讨论】:
标签: python numpy tensorflow
要将张量转换回 numpy 数组,您只需在转换后的张量上运行 .eval()。
【讨论】:
ValueError: Cannot evaluate tensor using 'eval()': No default session is registered. Use 'with sess.as_default()' or pass an explicit session to 'eval(session=sess)' 这是否仅在 tensoflow 会话期间可用?
.eval() 方法调用:sess = tf.Session(); with sess.as_default(): print(my_tensor.eval())
你需要:
代码:
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)
这对我有用。您可以在 ipython 笔记本中尝试。只是不要忘记添加以下行:
%matplotlib inline
【讨论】:
Session.run 或 eval 返回的任何张量都是 NumPy 数组。
>>> print(type(tf.Session().run(tf.constant([1,2,3]))))
<class 'numpy.ndarray'>
或者:
>>> 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'>
编辑:不是任何由Session.run 或eval() 返回的张量是一个NumPy 数组。例如,稀疏张量作为 SparseTensorValue 返回:
>>> print(type(tf.Session().run(tf.SparseTensor([[0, 0]],[1],[1,2]))))
<class 'tensorflow.python.framework.sparse_tensor.SparseTensorValue'>
【讨论】:
ValueError: Cannot evaluate tensor using 'eval()': No default session is registered. Use 'with sess.as_default()' or pass an explicit session to 'eval(session=sess)'
也许你可以试试,这个方法:
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)
【讨论】:
我已经面对并解决了 tensor->ndarray 转换在张量表示(对抗性)图像的特定情况下,通过 cleverhans 库/教程获得。
我认为我的问题/答案 (here) 对于其他情况也可能是一个有用的示例。
我是 TensorFlow 新手,我的结论是经验性的:
似乎 tensor.eval() 方法可能需要输入 placeholders 的值才能成功。
张量可能像函数一样工作,需要其输入值(提供给feed_dict)才能返回输出值,例如
array_out = tensor.eval(session=sess, feed_dict={x: x_input})
请注意,在我的例子中,占位符名称是 x,但我想您应该找出输入 placeholder 的正确名称。
x_input 是一个标量值或包含输入数据的数组。
就我而言,还必须提供sess。
我的示例还涵盖了 matplotlib 图像可视化部分,但这是 OT。
【讨论】:
一个简单的例子可以是,
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'>
就这么简单!
【讨论】:
// 不适用于在 python 中进行评论。请编辑您的答案。
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 Compatibility 了解更多信息。值得注意的是(来自文档),
Numpy 数组可以与 Tensor 对象共享内存。 对其中一项的任何更改都可能反映在另一项中。
我的大胆强调。可能会或可能不会返回副本,这是基于数据是在 CPU 中还是在 GPU 中的实现细节(在后一种情况下,必须从 GPU 复制到主机内存)。
但为什么我会收到AttributeError: 'Tensor' object has no attribute 'numpy'?。
很多人对这个问题发表了评论,有几个可能的原因:
tf.compat.v1.enable_eager_execution() 启用它,或参见下文。如果 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)
另请参阅TF 2.0 Symbols Map,了解旧 API 到新 API 的映射。
【讨论】:
mytensor.detach().numpy()。
我一直在寻找这个命令的日子。
这对我来说在任何会话或类似的事情之外都有效。
# 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
【讨论】:
你可以使用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'>
希望对你有帮助!
【讨论】:
如果你看到有一个方法_numpy(), 例如,对于 EagerTensor,只需调用上述方法,您就会得到一个 ndarray。
【讨论】:
您可以通过以下方式将tensorflow 中的张量转换为numpy 数组。
第一:
使用np.array(your_tensor)
第二:
使用your_tensor.numpy
【讨论】:
以下通常有效,因为默认情况下激活了急切执行:
import tensorflow as tf
a = tf.constant([[1, 2], [3, 4]])
b = tf.add(a, 1)
print(a.numpy())
# [[1 2]
# [3 4]]
但是,由于很多人似乎都在发布错误:
AttributeError: 'Tensor' object has no attribute 'numpy'
我认为公平地说,在图形模式下调用 tensor.numpy() 将不起作用。这是一个简单的例子:
import tensorflow as tf
@tf.function
def add():
a = tf.constant([[1, 2], [3, 4]])
b = tf.add(a, 1)
tf.print(a.numpy()) # throws an error!
return a
add()
简单的解释可以找here:
从根本上说,不能将图张量转换为 numpy 数组,因为该图不在 Python 中执行 - 因此在图执行时没有 NumPy。 [...]
TFdocs也值得一看。
这也适用于Keras 模型,默认情况下它们被包裹在tf.function 中。如果确实需要运行tensor.numpy(),可以在model.compile(*)中设置参数run_eagerly=True,但这会影响模型的性能。
【讨论】: