当使用Tensorflow与Python绑定时,如何将一个张量转换为numpy数组?
当前回答
你可以用以下方法将tensorflow中的张量转换为numpy数组。
第一: 使用np.array (your_tensor)
第二: 使用your_tensor.numpy
其他回答
要将张量转换回numpy数组,只需在转换后的张量上运行.eval()。
你可以用以下方法将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'>
就这么简单!
为了这个命令,我找了好几天。
这对我来说在任何会议之外或类似的事情都很有效。
# 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
如果你看到有一个方法_numpy(), 例如,对于一个EagerTensor,简单地调用上面的方法,你将得到一个ndarray。