当使用Tensorflow与Python绑定时,如何将一个张量转换为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
其他回答
也许你可以试试这个方法:
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)
为了这个命令,我找了好几天。
这对我来说在任何会议之外或类似的事情都很有效。
# 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 2.x
以下通常工作,因为默认情况下立即执行是激活的:
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()
这里可以找到一个简单的解释:
从根本上讲,不能将图张量转换为numpy数组,因为图不在Python中执行——因此在图执行时没有numpy。[…]
TF文档也值得一看。
关于使用Tensorflow 2.x的Keras模型
这也适用于Keras模型,它被封装在tf中。默认为。如果你真的需要运行tensor.numpy(),你可以在model.compile(*)中设置参数run_eager =True,但这将影响模型的性能。
任何由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'>
你需要:
将图像张量以某种格式(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
推荐文章
- 如何构建和使用谷歌TensorFlow c++ api
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID