如何在 TensorFlow 中将张量转换为 ndarray? [英] How can I convert a tensor into a ndarray in TensorFlow?
问题描述
我的目标是将张量转换为没有 'run' 或 'eval' 的 ndarray.我想执行与示例相同的操作.
My goal is to convert a tensor into a ndarray without 'run' or 'eval'. I wanted to perform the same operation as the example.
A = tf.constant(5)
B = tf.constant([[A, 1], [0,0]])
然而,ndarray 可以在 tf.constant 中,但 tensor 不能.因此,我尝试使用以下示例执行操作,但 tf.make_ndarray 不起作用.
However, ndarray can be inside tf.constant but tensor cannot. Therefore, I tried to perform the operation using the following example, but tf.make_ndarray does not work.
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'.
As mentioned in the github link above, tf.make_ndarray does not work. To be precise, an error occurs because tensorflow requires a 'tensor_shape' that does not exist, instead of a 'shape' that exists.
在这种情况下如何运行代码?
How can I run the code in this situation?
推荐答案
tf.make_ndarray
用于转换TensorProto
值转换为 NumPy 数组.这些值通常是图形中使用的常量.例如,当您使用 tf.constant
时,您创建一个 Const
操作,其属性 value
保存操作将产生的常量值.该属性存储为 TensorProto代码>
.因此,您可以像这样将 Const
操作的值提取"为 NumPy 数组:
tf.make_ndarray
is used to convert TensorProto
values into NumPy arrays. These values are generally the constants used in a graph. For example, when you use tf.constant
, you create a Const
operation with an attribute value
holding the constant value that the operation will produce. That attribute is stored as a TensorProto
. Hence, you can "extract" the value of a Const
operation as a NumPy array like this:
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 数组,因为它们的值将取决于变量的值和特定会话中的馈送输入.
In general, though, you cannot convert arbitrary tensors into NumPy arrays, as their values will depend on the values of the variables and the fed inputs within a particular session.
这篇关于如何在 TensorFlow 中将张量转换为 ndarray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!