【问题标题】:How to get tensorflow to evaluate shape at runtime?如何让张量流在运行时评估形状?
【发布时间】:2017-12-29 16:37:57
【问题描述】:

我想在运行时评估张量的形状。我正在计算两组之间的交集。交点的数量是张量x 的维度。在定义图形时,张量的形状设置为[Dimension(None)]。因此,通常的x.get_shape() 方法只会返回None。有没有办法在运行时评估形状None?我可以做sess.run(x) 并获得 numpy 数组的形状,但我希望这是一个已编译的操作,以便只返回形状。谢谢!

【问题讨论】:

  • 我不明白,很清楚。您的意思是,您想要已经在占位符中定义的图形变量的形状,并且必须在会话运行时返回它的形状?
  • 不,张量x 没有定义为占位符,而是x=tf.sets.set_intersection(a,b) 的结果。这个张量的形状是根据函数的输出选择的,不是硬编码的,也不是由占位符提供的。

标签: python tensorflow linear-algebra tensorflow-xla


【解决方案1】:

这个问题已经有一年的历史了,所以我相信您可能已经找到了您正在寻找的答案。但是以防万一其他人会寻找它,我会在这里发布。

答案非常简单 - 使用 tf.shape 方法 (see documentation) 在会话运行时评估输入张量形状。

例子:

import numpy as np
import tensorflow as tf


input_data = np.zeros((4, 1, 2, 3), np.float32)

with tf.Graph().as_default():
    input_tensor = tf.placeholder(tf.float32, (None, None, None, 3))
    input_tensor_shape = tf.shape(input_tensor)

    with tf.Session() as session:
        shape = input_tensor_shape.eval({input_tensor: input_data}, session)
        print(shape)

输出:
[4 1 2 3]

【讨论】:

  • 谢谢!我不记得我当时使用的是哪个版本的 tf,但当时 tf.shape 不可用。现在容易多了。
猜你喜欢
  • 2019-08-02
  • 1970-01-01
  • 1970-01-01
  • 2018-12-13
  • 1970-01-01
  • 1970-01-01
  • 2017-09-17
  • 2017-09-09
  • 2022-10-18
相关资源
最近更新 更多