0

I'm trying to check if the tensorflow tensor rand_int=0 in an if statement. In the below code, the if statement is not executed when rand_int=0.

rand_int = tf.random.uniform((), 0, 2, dtype=tf.int32)
if rand_int == 0:
    # Lots of lines of code
    ...

However, in the below code, the if statement is executed.

rand_int = tf.random.uniform((), 0, 2, dtype=tf.int32)
rand_int = tf.Session().run(rand_int)
if rand_int == 0:
    ...

How would I execute the if statement in the first block without tf.Session()?

3
  • In the first snippet, rand_int is a Tensor type object which will not equal 0 or 1. That's probably why the contents of the if's true branch are not executed. In the second snippet, rand_int is redefined as the output of session.run() and will either be 0 or 1. So, the contents of the if's true branch may execute with 50% probability. Commented Jan 16, 2021 at 1:32
  • Yes, that is true. But I would like to know if there is a way to do an if statement in tensorflow that allows for the first snippet. Commented Jan 16, 2021 at 1:45
  • Interesting. I've not come across this use case yet. I think defining tensorflow constants like one = tf.constant(1, dtype=tf.int32) and zero = tf.constant(0, dtype=tf.int32) may be useful. Since one and zero are also tensors, is_zero = rand_int == zero will also be a tensor. However, we may still not be able to execute if is_zero as expected. We will need something like tf.cond here stackoverflow.com/questions/35833011/… Commented Jan 16, 2021 at 1:55

1 Answer 1

1

You can avoid using session if you switch to TensorFlow (TF) 2.X version. TF 2 uses eager execution by default therefore you don't need Session to execute your graph. Moreover the contents of tensor are evaluated at runtime and can be accessed. Following code is tested with recent stable TF 2.4.0 version.

import tensorflow as tf 
rand_int = tf.random.uniform((), 0, 2, dtype=tf.int32)
#rand_int = tf.compat.v1.Session().run(rand_int)
if rand_int == 0:
    print('Inside If Block')

#Output:
Inside If Block
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.