我在 tensorflow 中创建了一个 OP,为了进行某些处理,我需要将我的数据从张量对象转换为 numpy 数组。我知道我们可以使用 tf.eval()
或 sess.run
来评估任何张量对象。我真正想知道的是,有没有什么方法可以在不运行任何 session 的情况下将张量转换为数组,因此我们又避免使用 .eval()
或 .run()
.
非常感谢任何帮助!
def tensor_to_array(tensor1):
'''Convert tensor object to numpy array'''
array1 = SESS.run(tensor1) **#====== need to bypass this line**
return array1.astype("uint8")
def array_to_tensor(array):
'''Convert numpy array to tensor object'''
tensor_data = tf.convert_to_tensor(array, dtype=tf.float32)
return tensor_data
最佳答案
已更新
# must under eagar mode
def tensor_to_array(tensor1):
return tensor1.numpy()
示例
>>> import tensorflow as tf
>>> tf.enable_eager_execution()
>>> def tensor_to_array(tensor1):
... return tensor1.numpy()
...
>>> x = tf.constant([1,2,3,4])
>>> tensor_to_array(x)
array([1, 2, 3, 4], dtype=int32)
我相信您可以在没有 tf.eval()
或 sess.run
的情况下通过使用 tf.enable_eager_execution()
来完成它
示例
import tensorflow as tf
import numpy as np
tf.enable_eager_execution()
x = np.array([1,2,3,4])
c = tf.constant([4,3,2,1])
c+x
<tf.Tensor: id=5, shape=(4,), dtype=int32, numpy=array([5, 5, 5, 5], dtype=int32)>
有关 tensorflow eager 模式的更多详细信息,请在此处查看:Tensorflow eager
如果没有tf.enable_eager_execution()
:
import tensorflow as tf
import numpy as np
c = tf.constant([4,3,2,1])
x = np.array([1,2,3,4])
c+x
<tf.Tensor 'add:0' shape=(4,) dtype=int32>
关于python - Tensorflow:在不运行任何 session 的情况下将 Tensor 转换为 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52215711/