Reputation: 5366
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()
?
Upvotes: 0
Views: 527
Reputation: 853
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
Upvotes: 1