如何在TensorFlow中将张量转换为ndarray?


问题内容

我的目标是将张量转换为ndarray而不使用“ run”或“ eval”。我想执行与示例相同的操作。

A = tf.constant(5)
B = tf.constant([[A, 1], [0,0]])

但是,ndarray可以在tf.constant内部,但张量不能。因此,我尝试使用以下示例执行该操作,但tf.make_ndarray不起作用。

A = tf.constant(5)
C = tf.make_ndarray(A)
B = tf.constant([[C, 1], [0,0]])

https://github.com/tensorflow/tensorflow/issues/28840#issuecomment-509551333

如上面的github链接中所述,tf.make_ndarray不起作用。确切地说,发生错误是因为tensorflow需要不存在的’tensor_shape’而不是存在的’shape’。

在这种情况下如何运行代码?


问题答案:

tf.make_ndarray用于将TensorProto值转换为NumPy数组。这些值通常是图形中使用的常数。例如,当您使用时tf.constant,您将创建一个Const具有属性的操作,该属性value包含该操作将产生的常数值。该属性存储为TensorProto。因此,您可以Const像这样将操作的值“提取”为NumPy数组:

import tensorflow as tf

A = tf.constant(5)
C = tf.make_ndarray(A.op.get_attr('value'))
print(C, type(C))
# 5 <class 'numpy.ndarray'>

但是,通常来说,您无法将任意张量转换为NumPy数组,因为它们的值将取决于变量的值以及特定会话中的馈入输入。