[英]How can I convert a tensor into a ndarray in TensorFlow?
我的目标是将张量转换为没有 'run' 或 'eval' 的 ndarray。 我想执行与示例相同的操作。
A = tf.constant(5)
B = tf.constant([[A, 1], [0,0]])
但是, ndarray 可以在 tf.constant 内部,但 tensor 不能。 因此,我尝试使用以下示例执行操作,但 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 数组,因为它们的值将取决于变量的值和特定会话中的馈送输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.