MomentumOptimizer

  • class paddle.fluid.optimizer.MomentumOptimizer(learning_rate, momentum, parameter_list=None, use_nesterov=False, regularization=None, name=None)[源代码]

该接口实现含有速度状态的Simple Momentum 优化器

该优化器含有牛顿动量标志,公式更新如下:

MomentumOptimizer - 图1

  • 参数:
    • learning_rate (float|Variable) - 学习率,用于参数更新。作为数据参数,可以是浮点型值或含有一个浮点型值的变量。
    • momentum (float) - 动量因子。
    • parameter_list (list, 可选) - 指定优化器需要优化的参数。在动态图模式下必须提供该参数;在静态图模式下默认值为None,这时所有的参数都将被优化。
    • use_nesterov (bool,可选) - 赋能牛顿动量,默认值False。
    • regularization - 正则化函数,,例如 fluid.regularizer.L2DecayRegularizer,默认值None。
    • name (str, 可选) - 可选的名称前缀,一般无需设置,默认值为None。

代码示例

  1. import paddle
  2. import paddle.fluid as fluid
  3. import numpy as np
  4.  
  5. place = fluid.CPUPlace()
  6. main = fluid.Program()
  7. with fluid.program_guard(main):
  8. x = fluid.layers.data(name='x', shape=[13], dtype='float32')
  9. y = fluid.layers.data(name='y', shape=[1], dtype='float32')
  10. y_predict = fluid.layers.fc(input=x, size=1, act=None)
  11. cost = fluid.layers.square_error_cost(input=y_predict, label=y)
  12. avg_cost = fluid.layers.mean(cost)
  13.  
  14. moment_optimizer = fluid.optimizer.MomentumOptimizer(learning_rate=0.001, momentum=0.9)
  15. moment_optimizer.minimize(avg_cost)
  16.  
  17. fetch_list = [avg_cost]
  18. train_reader = paddle.batch(
  19. paddle.dataset.uci_housing.train(), batch_size=1)
  20. feeder = fluid.DataFeeder(place=place, feed_list=[x, y])
  21. exe = fluid.Executor(place)
  22. exe.run(fluid.default_startup_program())
  23. for data in train_reader():
  24. exe.run(main, feed=feeder.feed(data), fetch_list=fetch_list)
  • minimize(loss, startup_program=None, parameter_list=None, no_grad_set=None, grad_clip=None)

为网络添加反向计算过程,并根据反向计算所得的梯度,更新parameter_list中的Parameters,最小化网络损失值loss。

  • 参数:
    • loss (Variable) – 需要最小化的损失值变量
    • startup_program (Program, 可选) – 用于初始化parameter_list中参数的 Program , 默认值为None,此时将使用 default_startup_program
    • parameter_list (list, 可选) – 待更新的Parameter或者Parameter.name组成的列表, 默认值为None,此时将更新所有的Parameter
    • no_grad_set (set, 可选) – 不需要更新的Parameter或者Parameter.name组成的集合,默认值为None
    • grad_clip (GradClipBase, 可选) – 梯度裁剪的策略,静态图模式不需要使用本参数,当前本参数只支持在dygraph模式下的梯度裁剪,未来本参数可能会调整,默认值为None

返回: (optimize_ops, params_grads),数据类型为(list, list),其中optimize_ops是minimize接口为网络添加的OP列表,params_grads是一个由(param, grad)变量对组成的列表,param是Parameter,grad是该Parameter对应的梯度值

返回类型: tuple

代码示例

  1. import paddle
  2. import paddle.fluid as fluid
  3. import numpy as np
  4.  
  5. place = fluid.CPUPlace()
  6. main = fluid.Program()
  7. with fluid.program_guard(main):
  8. x = fluid.layers.data(name='x', shape=[13], dtype='float32')
  9. y = fluid.layers.data(name='y', shape=[1], dtype='float32')
  10. y_predict = fluid.layers.fc(input=x, size=1, act=None)
  11. cost = fluid.layers.square_error_cost(input=y_predict, label=y)
  12. avg_cost = fluid.layers.mean(cost)
  13.  
  14. moment_optimizer = fluid.optimizer.MomentumOptimizer(learning_rate=0.001, momentum=0.9)
  15. moment_optimizer.minimize(avg_cost)
  16.  
  17. fetch_list = [avg_cost]
  18. train_reader = paddle.batch(
  19. paddle.dataset.uci_housing.train(), batch_size=1)
  20. feeder = fluid.DataFeeder(place=place, feed_list=[x, y])
  21. exe = fluid.Executor(place)
  22. exe.run(fluid.default_startup_program())
  23. for data in train_reader():
  24. exe.run(main, feed=feeder.feed(data), fetch_list=fetch_list)
  • clear_gradients()

注意:

1. 该API只在 Dygraph 模式下生效

清除需要优化的参数的梯度。

代码示例

  1. import paddle.fluid as fluid
  2. import numpy as np
  3.  
  4. with fluid.dygraph.guard():
  5. value = np.arange(26).reshape(2, 13).astype("float32")
  6. a = fluid.dygraph.to_variable(value)
  7. linear = fluid.Linear(13, 5, dtype="float32")
  8. optimizer = fluid.optimizer.MomentumOptimizer(learning_rate=0.001, momentum=0.9,
  9. parameter_list=linear.parameters())
  10. out = linear(a)
  11. out.backward()
  12. optimizer.minimize(out)
  13. optimizer.clear_gradients()
  • current_step_lr()

注意:

1. 该API只在 Dygraph 模式下生效

获取当前步骤的学习率。当不使用LearningRateDecay时,每次调用的返回值都相同,否则返回当前步骤的学习率。

返回:当前步骤的学习率。

返回类型:float

代码示例

  1. import paddle.fluid as fluid
  2. import numpy as np
  3.  
  4. # example1: LearningRateDecay is not used, return value is all the same
  5. with fluid.dygraph.guard():
  6. emb = fluid.dygraph.Embedding([10, 10])
  7. adam = fluid.optimizer.Adam(0.001, parameter_list = emb.parameters())
  8. lr = adam.current_step_lr()
  9. print(lr) # 0.001
  10.  
  11. # example2: PiecewiseDecay is used, return the step learning rate
  12. with fluid.dygraph.guard():
  13. inp = np.random.uniform(-0.1, 0.1, [10, 10]).astype("float32")
  14. linear = fluid.dygraph.nn.Linear(10, 10)
  15. inp = fluid.dygraph.to_variable(inp)
  16. out = linear(inp)
  17. loss = fluid.layers.reduce_mean(out)
  18.  
  19. bd = [2, 4, 6, 8]
  20. value = [0.2, 0.4, 0.6, 0.8, 1.0]
  21. adam = fluid.optimizer.Adam(fluid.dygraph.PiecewiseDecay(bd, value, 0),
  22. parameter_list=linear.parameters())
  23.  
  24. # first step: learning rate is 0.2
  25. np.allclose(adam.current_step_lr(), 0.2, rtol=1e-06, atol=0.0) # True
  26.  
  27. # learning rate for different steps
  28. ret = [0.2, 0.2, 0.4, 0.4, 0.6, 0.6, 0.8, 0.8, 1.0, 1.0, 1.0, 1.0]
  29. for i in range(12):
  30. adam.minimize(loss)
  31. lr = adam.current_step_lr()
  32. np.allclose(lr, ret[i], rtol=1e-06, atol=0.0) # True