cond
API属性:声明式编程(静态图)专用API
( pred, true_fn=None, false_fn=None, name=None ) [源代码]
true_fn
和 false_fn
需要返回同样嵌套结构(nest structure)的Tensor,如果不想返回任何值也可都返回 None
。 PaddlePaddle里Tensor的嵌套结构是指一个Tensor,或者Tensor的元组(tuple),或者Tensor的列表(list)。
注解
不论运行哪个分支,在
true_fn
和false_fn
外创建的Tensor和Op都会被运行,即PaddlePaddle并不是惰性语法(lazy semantics)。例如不管
a < b
是否成立,c = a * b
都会被运行。
Variable|list(Variable)|tuple(Variable)
import paddle.fluid as fluid
import paddle.fluid.layers as layers
from paddle.fluid.executor import Executor
#
# pseudocode:
# if 0.1 < 0.23:
# return 1, True
# else:
# return 3, 2
#
return layers.fill_constant(
shape=[1, 2], dtype='int32', value=1), layers.fill_constant(
shape=[2, 3], dtype='bool', value=True)
def false_func():
return layers.fill_constant(
shape=[4, 5], dtype='int64', value=2)
main_program = Program()
startup_program = Program()
with program_guard(main_program, startup_program):
x = layers.fill_constant(shape=[1], dtype='float32', value=0.1)
y = layers.fill_constant(shape=[1], dtype='float32', value=0.23)
pred = layers.less_than(x, y)
out = layers.cond(pred, true_func, false_func)
# out is a tuple containing 2 tensors
place = fluid.CUDAPlace(0) if fluid.core.is_compiled_with_cuda(
) else fluid.CPUPlace()
exe = fluid.Executor(place)
ret = exe.run(main_program, fetch_list=out)
# ret[0] = [[1 1]]
# [ True True True]]