While

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 一样。

注意:

While 中创建的局部变量类似于C++中的while,无法被外部引用,因此无法通过 Executor 中的 fetch_list 来获取。 若想实现该功能,PaddlePaddle提供了 assign 接口将局部变量赋值到外部,请参考示例代码2 或参考 issue#22724

参数:

  • cond (Variable) – 用于判断循环继续进行的条件,为数据类型bool型的Tensor,其shape必须为[1]。

  • is_test (bool,可选) – 用于表明是否在测试阶段执行,默认值为False。

  • name (str,可选) - 具体用法请参见 Name ,一般无需设置,默认值为None。

代码示例 1

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

代码示例 2

  1. import paddle.fluid as fluid
  2. import numpy as np
  3. i = fluid.layers.fill_constant(shape=[1], dtype='int64', value=0)
  4. loop_len = fluid.layers.fill_constant(shape=[1], dtype='int64', value=10)
  5. one = fluid.layers.fill_constant(shape=[1], dtype='float32', value=1)
  6. data = fluid.data(name='data', shape=[1], dtype='float32')
  7. sums = fluid.layers.fill_constant(shape=[1], dtype='float32', value=0) # 在 While 外先定义要获取的变量,需和要获取的 While 内部的变量名称不同
  8. cond = fluid.layers.less_than(x=i, y=loop_len)
  9. while_op = fluid.layers.While(cond=cond)
  10. with while_op.block():
  11. sums_tensor = fluid.layers.elementwise_add(x=data, y=data)
  12. fluid.layers.assign(input=sums_tensor, output=sums) # 将 While 内定义的变量 sums_tenosr 通过 layers.assign 更新至 While 外的变量 sums 中
  13. i = fluid.layers.increment(x=i, value=1, in_place=True)
  14. data = fluid.layers.elementwise_add(x=data, y=one)
  15. fluid.layers.less_than(x=i, y=loop_len, cond=cond)
  16. feed_data = np.ones([1]).astype('float32')
  17. exe = fluid.Executor(fluid.CPUPlace())
  18. exe.run(fluid.default_startup_program())
  19. res = exe.run(fluid.default_main_program(), feed={'data': feed_data}, fetch_list=sums)
  20. print(res[0]) # [2.] # 因 While 内的 data 没有将值更新到 While 外,故循环过后此处 sums 的值为 [2.]