user2996213
user2996213

Reputation: 9

Multiple if-else conditions in tensorflow

I have a float tensor with shape (1) whose value lies between 0.0 and 1.0. I want to 'bin' the range in this tensor, as in:

if 0.0 < x < 0.2: 
  return tf.Constant([0])
if 0.2 < x < 0.4: 
  return tf.Constant([1])
if 0.4 < x < 0.6: 
  return tf.Constant([2])
if 0.6 < x: 
  return tf.Constant([3])

No idea how to do it!

Upvotes: 0

Views: 1796

Answers (2)

drsbhattac
drsbhattac

Reputation: 119

try tg.logical_and the following example might help

b = tf.constant([5,2,-3,1])
c1 = tf.greater(b,0) # b>0
c2 = tf.less(b,5) # b<5
c_f = tf.logical_and(c1, c2) # 0 < b < 5
sess=tf.Session()
sess.run(c_f)

Upvotes: 0

Salvador Dali
Salvador Dali

Reputation: 222471

You have not explained what will happen in the border points (0.2, 0.4, ...) and have not shown what do you want to output for x > 0.6, so my assumptions are:

  • closed open interval; a < x <= b
  • the same bin procedure continues till 1 with a step 0.2

For such a simple case you do not need if else condition (also it will be slow). You can achieve it with math and casting:

import tensorflow as tf

x = tf.constant(0.25)
res = tf.cast(5 * x, tf.int32)
with tf.Session() as sess:
    print sess.run(res)

Upvotes: 1

Related Questions