Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

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

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

question from:https://stackoverflow.com/questions/66065570/how-to-create-a-1-d-range-tensor-when-dimension-is-unknown

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...