I want to have an if statement in tensorflow; and if the condition is not fulfilled nothing should happen.
I tried to use both tf.case and tf.cond but both require a specification of a function it the statement evaluates False.
op = tf.cond(tf.equal(x, y), true_fn=f1(), false_fn=lambda: None)
gives me an error: ValueError: false_fn must have a return value.
On TF 1.x, I would use tf.no_op to specify a dummy OP that does nothing:
ops = tf.cond(tf.equal(x, y), true_fn=f, false_fn=lambda: tf.no_op())
On TF 2.x, you can just pass lambda: None to false_fn, thanks to eager execution.
Minimal Code Sample
import tensorflow as tf
x, y, z = tf.constant(1), tf.constant(1), tf.constant(2)
op1 = tf.cond(
tf.equal(x, y), true_fn=lambda: tf.print(x), false_fn=lambda: tf.no_op())
op2 = tf.cond(
tf.equal(x, z), true_fn=lambda: tf.print(x), false_fn=lambda: tf.no_op())
with tf.Session() as sess:
sess.run(op1) # 1
sess.run(op2) # does nothing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With