python - Tensorflow:在不运行任何 session 的情况下将 Tensor 转换为 numpy 数组

标签 python tensorflow

我在 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/

相关文章:

python - 使用Python解析包含 "&"的html数据

tensorflow - 如何通过 tf.image_summary 查看多张图片

python - 为包含深度嵌套 numpy 数组的 Python 对象实现 __eq__

python - 从数据框中随机选择数据但不重复

python - 使用 Flask Rest API 上传和处理文件

python - TypeError : Cannot interpret feed_dict key as Tensor,需要了解 session 和图表

python - 元组索引超出范围,Tensorflow

tensorflow - 用于多个输入和基于图像的目标输出的 Keras ImageDataGenerator

python - 如何解释 Tensorflow DNNRegressor Estimator 模型中的损失函数?

python - 如何对每个组的条目进行计数和求和?