While

注意:该API仅支持【静态图】模式

  • class paddle.fluid.layers.While(cond, is_test=False, name=None)[源代码]

该类用于实现while循环控制功能,只要循环条件cond为True,就循环执行while循环体中的语句,直到cond为False为止。

注解

如果参数 cond 的形状为[1],强烈建议您使用新的OP while_loop 而不是 While。 OP while_loop 的使用方式更简单,并且调用该OP所用的代码更少且功能与 While 一样。

  • 参数:
    • cond (Variable) – 用于判断循环继续进行的条件,为数据类型bool型的Tensor,其shape必须为[1]。
    • is_test (bool,可选) – 用于表明是否在测试阶段执行,默认值为False。
    • name (str,可选) - 具体用法请参见 Name ,一般无需设置,默认值为None。

代码示例

  1. # 该示例代码展示整数循环+1,循环10次,输出计数结果
  2. import paddle.fluid as fluid
  3. import numpy as np
  4.  
  5. i = fluid.layers.fill_constant(shape=[1], dtype='int64', value=0) # 循环计数器
  6.  
  7. loop_len = fluid.layers.fill_constant(shape=[1],dtype='int64', value=10) # 循环次数
  8.  
  9. cond = fluid.layers.less_than(x=i, y=loop_len) # 循环条件
  10. while_op = fluid.layers.While(cond=cond)
  11. with while_op.block(): # 循环体
  12. i = fluid.layers.increment(x=i, value=1, in_place=True)
  13. fluid.layers.less_than(x=i, y=loop_len, cond=cond) # 更新循环条件
  14.  
  15. exe = fluid.Executor(fluid.CPUPlace())
  16. exe.run(fluid.default_startup_program())
  17.  
  18. res = exe.run(fluid.default_main_program(), feed={}, fetch_list=[i])
  19. print(res) # [array([10])]