How to create a 1-D range tensor when dimension is Unknown?

458 views Asked by At

I have a n-D array. I need to create a 1-D range tensor based on dimensions.

for an example:

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)

The problem is, x.shape[0] is none at the time of building computational graph. So I can not build the tensor using range. It gives an error.

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

Any suggestion or help for the problem.

Thanks in advance

1

There are 1 answers

0
Lescurel On BEST ANSWER

x.shape[0] might not exist yet when running this code is graph mode. If you want a value, you need to use tf.shape(x)[0].

More information about that behaviour in the documentation for tf.Tensor.get_shape. An excerpt (emphasis is mine):

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.