|View source on GitHub|
true_fn() if the predicate
pred is true else
tf.cond( pred, true_fn=None, false_fn=None, name=None )
false_fn both return lists of output tensors.
false_fn must have the same non-zero number and type of outputs.
Although this behavior is consistent with the dataflow model of TensorFlow, it has frequently surprised users who expected a lazier semantics. Consider the following simple program:
z = tf.multiply(a, b) result = tf.cond(x < y, lambda: tf.add(x, z), lambda: tf.square(y))
x < y, the
tf.add operation will be executed and
tf.square operation will not be executed. Since
z is needed for at least one branch of the
tf.multiply operation is always executed, unconditionally.
false_fn exactly once (inside the call to
cond, and not at all during
cond stitches together the graph fragments created during the
false_fn calls with some additional graph nodes to ensure that the right branch gets executed depending on the value of
tf.cond supports nested structures as implemented in
false_fn must return the same (possibly nested) value structure of lists, tuples, and/or named tuples. Singleton lists and tuples form the only exceptions to this: when returned by
false_fn, they are implicitly unpacked to single values.
Note: It is illegal to "directly" use tensors created inside a cond branch outside it, e.g. by storing a reference to a branch tensor in the python state. If you need to use a tensor created in a branch function you should return it as an output of the branch function and use the output from
| || A scalar determining whether to return the result of |
| ||The callable to be performed if pred is true.|
| ||The callable to be performed if pred is false.|
| ||Optional name prefix for the returned tensors.|
| Tensors returned by the call to either |
| || if |
| || if |
x = tf.constant(2) y = tf.constant(5) def f1(): return tf.multiply(x, 17) def f2(): return tf.add(y, 23) r = tf.cond(tf.less(x, y), f1, f2) # r is set to f1(). # Operations in f2 (e.g., tf.add) are not executed.
© 2020 The TensorFlow Authors. All rights reserved.
Licensed under the Creative Commons Attribution License 3.0.
Code samples licensed under the Apache 2.0 License.