【问题标题】:How to create a 1-D range tensor when dimension is Unknown?维度未知时如何创建一维范围张量?
【发布时间】:2021-02-05 15:01:03
【问题描述】:

我有一个 n 维数组。我需要根据维度创建一维范围张量。

举个例子:

x = tf.placeholder(tf.float32, shape=[None,4]) 
  
r = tf.range(start=0, limit=, delta=x.shape[0],dtype=tf.int32, name='range')

sess = tf.Session()

result = sess.run(r, feed_dict={x: raw_lidar})
print(r)

问题是,x.shape[0] 在构建计算图时是 none。所以我不能使用范围来构建张量。它给出了一个错误。

ValueError: Cannot convert an unknown Dimension to a Tensor: ?

对问题的任何建议或帮助。

提前致谢

【问题讨论】:

    标签: python tensorflow computation-graph


    【解决方案1】:

    x.shape[0] 在图形模式下运行此代码时可能还不存在。如果你想要一个值,你需要使用tf.shape(x)[0]

    documentation for tf.Tensor.get_shape 中有关该行为的更多信息。摘录(强调是我的):

    tf.Tensor.get_shape() 等价于 tf.Tensor.shape。

    在 tf.function 中执行或使用 tf.keras.Input 构建模型时,Tensor.shape 可能会返回部分形状(包括未知尺寸的 None)。 请参阅 tf.TensorShape 了解更多信息详情。

    >>> inputs = tf.keras.Input(shape = [10])
    >>> # Unknown batch size
    >>> print(inputs.shape)
    (None, 10)
    

    使用为每个 tf.Operation 注册的形状推断函数计算形状。 返回的 tf.TensorShape 在构建时确定,无需执行底层内核。它不是 tf.Tensor。 如果您需要形状张量,请将 tf.TensorShape 转换为 tf.constant,或使用 tf.shape(tensor) 函数,该函数在执行时返回张量的形状。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-19
      • 1970-01-01
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多