python - 当维度未知时如何创建一维范围张量?

标签 python tensorflow computation-graph

我有一个 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] 不存在。所以我无法使用范围构建张量。它给出了一个错误。

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

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

提前致谢

最佳答案

在图形模式下运行此代码时,

x.shape[0] 可能尚不存在。如果您想要一个值,则需要使用tf.shape(x)[0]

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

tf.Tensor.get_shape() is equivalent to tf.Tensor.shape.

When executing in a tf.function or building a model using tf.keras.Input, Tensor.shape may return a partial shape (including None for unknown dimensions). See tf.TensorShape for more details.

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

The shape is computed using shape inference functions that are registered for each tf.Operation. The returned tf.TensorShape is determined at build time, without executing the underlying kernel. It is not a tf.Tensor. If you need a shape tensor, either convert the tf.TensorShape to a tf.constant, or use the tf.shape(tensor) function, which returns the tensor's shape at execution time.

关于python - 当维度未知时如何创建一维范围张量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66065570/

相关文章:

python-3.x - 安装 Tensorflow GPU - 找不到 libcublas.so.9.0,即使它存在且在路径中

python - 如何在没有固定 batch_size 的情况下设置 Tensorflow dynamic_rnn、zero_state?

python - 值错误: The number of classes has to be greater than one; got 1

python - 匹配字典列表最有效的方法是什么?

python - matplotlib 的 xkcd() 不工作

python - 在单独的子图中显示 displot - Seaborn

python - 在 Tensorflow 图中查找所需的占位符