Search code examples
tensorflowkeras

Why doesn't Tensorflow have if conditions?


Recently I was implementing a custom loss function in Tensorflow and I realized, Tensorflow doesn't have if conditions. I feel like if conditions are such an inherent programming feature why would Tensorflow developers not have such a fundamental feature in such a big project?


Solution

  • TensorFlow is not thought to be eagerly executed as python is. So the framework provides extra functions to kind o simulate eager functionalities.

    Some examples are:

    • tf.cond(condition, true_fn, flase_fn): In case the condition is false it will execute the false_fn, otherwise the true_fn
    z = tf.multiply(a, b)
    result = tf.cond(x < y, lambda: tf.add(x, z), lambda: tf.square(y))
    
    • tf.while
    i = tf.constant(0)
    c = lambda i: tf.less(i, 10)
    b = lambda i: tf.add(i, 1)
    r = tf.while_loop(c, b, [i])
    

    Source: https://www.tensorflow.org/api_docs/python/