cond

    API属性:声明式编程(静态图)专用API

    ( pred, true_fn=None, false_fn=None, name=None ) [源代码]

    true_fnfalse_fn 需要返回同样嵌套结构(nest structure)的Tensor,如果不想返回任何值也可都返回 None 。 PaddlePaddle里Tensor的嵌套结构是指一个Tensor,或者Tensor的元组(tuple),或者Tensor的列表(list)。

    注解

    1. 不论运行哪个分支,在 true_fnfalse_fn 外创建的Tensor和Op都会被运行,即PaddlePaddle并不是惰性语法(lazy semantics)。例如

      不管 a < b 是否成立, c = a * b 都会被运行。

    Variable|list(Variable)|tuple(Variable)

    1. import paddle.fluid as fluid
    2. import paddle.fluid.layers as layers
    3. from paddle.fluid.executor import Executor
    4. #
    5. # pseudocode:
    6. # if 0.1 < 0.23:
    7. # return 1, True
    8. # else:
    9. # return 3, 2
    10. #
    11. return layers.fill_constant(
    12. shape=[1, 2], dtype='int32', value=1), layers.fill_constant(
    13. shape=[2, 3], dtype='bool', value=True)
    14. def false_func():
    15. return layers.fill_constant(
    16. shape=[4, 5], dtype='int64', value=2)
    17. main_program = Program()
    18. startup_program = Program()
    19. with program_guard(main_program, startup_program):
    20. x = layers.fill_constant(shape=[1], dtype='float32', value=0.1)
    21. y = layers.fill_constant(shape=[1], dtype='float32', value=0.23)
    22. pred = layers.less_than(x, y)
    23. out = layers.cond(pred, true_func, false_func)
    24. # out is a tuple containing 2 tensors
    25. place = fluid.CUDAPlace(0) if fluid.core.is_compiled_with_cuda(
    26. ) else fluid.CPUPlace()
    27. exe = fluid.Executor(place)
    28. ret = exe.run(main_program, fetch_list=out)
    29. # ret[0] = [[1 1]]
    30. # [ True True True]]