当使用Tensorflow与Python绑定时,如何将一个张量转换为numpy数组?
当前回答
您可以使用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数组,只需在转换后的张量上运行.eval()。
一个简单的例子是,
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'>
就这么简单!
我已经面对并解决了张量->ndarray转换在张量表示(对抗)图像的特定情况下,通过cleverhans库/教程获得。
我认为我的问题/答案(在这里)也可能是一个有用的例子,对其他情况。
我是TensorFlow的新手,我的结论是经验的:
看起来为了成功,tensor.eval()方法可能还需要输入占位符的值。 Tensor可以像一个函数一样工作,需要它的输入值(提供给feed_dict)来返回一个输出值,例如:
array_out = tensor.eval(session=sess, feed_dict={x: x_input})
请注意,在我的例子中,占位符的名称是x,但我认为您应该为输入占位符找出正确的名称。 X_input是一个包含输入数据的标量值或数组。
在我的案例中,提供sess也是强制性的。
我的示例还包括matplotlib图像可视化部分,但这是OT。
关于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,但这将影响模型的性能。
如果你看到有一个方法_numpy(), 例如,对于一个EagerTensor,简单地调用上面的方法,你将得到一个ndarray。
推荐文章
- 如何在Flask-SQLAlchemy中按id删除记录
- 在Python中插入列表的第一个位置
- Python Pandas只合并某些列
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?
- 为什么出现这个UnboundLocalError(闭包)?
- 使用Python请求的异步请求
- 如何检查一个对象是否是python中的生成器对象?
- 如何从Python包内读取(静态)文件?
- 如何计算一个逻辑sigmoid函数在Python?
- python: SyntaxError: EOL扫描字符串文字