python - 如何在 TensorFlow 中将张量转换为 ndarray?
问题描述
我的目标是将张量转换为没有“运行”或“评估”的 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 数组,因为它们的值将取决于变量的值和特定会话中的馈送输入。
推荐阅读
- r - R:无法将 .rda 文件加载到 R Studio -> 无法打开压缩文件“ESL.mixture.rda”,可能的原因“没有这样的文件或目录”
- routing - Ionic 4 路由不起作用 url 更改但视图没有出现
- c# - 如何发送超过 70 个字符的短信
- bash - Perl 在 Shell 脚本中搜索和替换
- php - IPS4 php获取当前成员的ID
- javascript - '{}' 类型的参数不能分配给 Angular 8 中的类型参数
- python-3.x - 如何计算两行特定列之间的最大值
- python - 像素着色器中的 Mandelbrot
- docker - Docker-in-Docker 连接到内部容器网络(锚引擎)的问题
- reactjs - 从猫鼬模式文件中提取模式