While

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

    注解

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

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

    参数:

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

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

    代码示例 1

    代码示例 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. data = fluid.data(name='data', shape=[1], dtype='float32')
    6. sums = fluid.layers.fill_constant(shape=[1], dtype='float32', value=0) # 在 While 外先定义要获取的变量,需和要获取的 While 内部的变量名称不同
    7. cond = fluid.layers.less_than(x=i, y=loop_len)
    8. while_op = fluid.layers.While(cond=cond)
    9. with while_op.block():
    10. fluid.layers.assign(input=sums_tensor, output=sums) # 将 While 内定义的变量 sums_tenosr 通过 layers.assign 更新至 While 外的变量 sums 中
    11. data = fluid.layers.elementwise_add(x=data, y=one)
    12. fluid.layers.less_than(x=i, y=loop_len, cond=cond)
    13. feed_data = np.ones([1]).astype('float32')
    14. exe = fluid.Executor(fluid.CPUPlace())
    15. exe.run(fluid.default_startup_program())
    16. res = exe.run(fluid.default_main_program(), feed={'data': feed_data}, fetch_list=sums)