mariya
mariya

Reputation: 127

How to convert 1D tensor into a scalar value inside the graph?

I need to convert 1d tensor of shape (1,) into scalar 1 or () in tensorflow to use in tf.cond.

But the problem is in tf.cond(number <T,treu_fn=..,false_fn=.. number is of shape (1,) and T is () just a scalar.

Sample code snippet:

number = tf.gather_nd(number_buffer,indices)
number = tf.cast(number,dtype=tf.int32)  #T is const of type int32
result = tf.cond(number < T,lambda: tf.add(i,1),lambda: tf.add(P,0))
     
       
     

When I run the session, I am getting below error.

ValueError: Shape must be rank 0 but is rank 1 for '{{node while/cond/Switch}} = Switch[T=DT_BOOL](while/Less_1, while/Less_1)' with input shapes: [1], [1].

I know the reason, but I do not know how to fix this error.

one can consider it as reducing the rank of a tensor as well.

Could someone help me with this!

Thanks in advance

Upvotes: 1

Views: 2909

Answers (1)

Ilango Rajagopal
Ilango Rajagopal

Reputation: 316

If the number tensor is of shape (1,), which you can just squeeze or reshape to make it a scalar:

number = tf.squeeze(number)

Make sure the tf.gather_nd returns only one element, meaning indices must be an array of length 1.

Upvotes: 2

Related Questions