AdamOptimizer

  • class paddle.fluid.optimizer.AdamOptimizer(learning_rate=0.001, beta1=0.9, beta2=0.999, epsilon=1e-08, parameter_list=None, regularization=None, name=None, lazy_mode=False)[源代码]

Adam优化器出自 Adam论文 的第二节,能够利用梯度的一阶矩估计和二阶矩估计动态调整每个参数的学习率。

其参数更新的计算公式如下:

AdamOptimizer - 图1

AdamOptimizer - 图2

AdamOptimizer - 图3

AdamOptimizer - 图4

AdamOptimizer - 图5

相关论文:Adam: A Method for Stochastic Optimization

  • 参数:
    • learning_rate (float|Variable,可选) - 学习率,用于参数更新的计算。可以是一个浮点型值或者一个值为浮点型的Variable,默认值为0.001
    • parameter_list (list, 可选) - 指定优化器需要优化的参数。在动态图模式下必须提供该参数;在静态图模式下默认值为None,这时所有的参数都将被优化。
    • beta1 (float|Variable, 可选) - 一阶矩估计的指数衰减率,是一个float类型或者一个shape为[1],数据类型为float32的Variable类型。默认值为0.9
    • beta2 (float|Variable, 可选) - 二阶矩估计的指数衰减率,是一个float类型或者一个shape为[1],数据类型为float32的Variable类型。默认值为0.999
    • epsilon (float, 可选) - 保持数值稳定性的短浮点类型值,默认值为1e-08
    • regularization (WeightDecayRegularizer, 可选) - 正则化函数,用于减少泛化误差。例如可以是 L2DecayRegularizer ,默认值为None
    • name (str, 可选)- 该参数供开发人员打印调试信息时使用,具体用法请参见 Name ,默认值为None
    • lazy_mode (bool, 可选) - 设为True时,仅更新当前具有梯度的元素。官方Adam算法有两个移动平均累加器(moving-average accumulators)。累加器在每一步都会更新。在密集模式和稀疏模式下,两条移动平均线的每个元素都会更新。如果参数非常大,那么更新可能很慢。 lazy mode仅更新当前具有梯度的元素,所以它会更快。但是这种模式与原始的算法有不同的描述,可能会导致不同的结果,默认为False

代码示例

  1. import paddle
  2. import paddle.fluid as fluid
  3.  
  4. place = fluid.CPUPlace()
  5. main = fluid.Program()
  6. with fluid.program_guard(main):
  7. x = fluid.layers.data(name='x', shape=[13], dtype='float32')
  8. y = fluid.layers.data(name='y', shape=[1], dtype='float32')
  9. y_predict = fluid.layers.fc(input=x, size=1, act=None)
  10. cost = fluid.layers.square_error_cost(input=y_predict, label=y)
  11. avg_cost = fluid.layers.mean(cost)
  12. adam_optimizer = fluid.optimizer.AdamOptimizer(0.01)
  13. adam_optimizer.minimize(avg_cost)
  14.  
  15. fetch_list = [avg_cost]
  16. train_reader = paddle.batch(
  17. paddle.dataset.uci_housing.train(), batch_size=1)
  18. feeder = fluid.DataFeeder(place=place, feed_list=[x, y])
  19. exe = fluid.Executor(place)
  20. exe.run(fluid.default_startup_program())
  21. for data in train_reader():
  22. exe.run(main, feed=feeder.feed(data), fetch_list=fetch_list)
  1. # Adam with beta1/beta2 as Variable
  2. import paddle
  3. import paddle.fluid as fluid
  4. import paddle.fluid.layers.learning_rate_scheduler as lr_scheduler
  5.  
  6. place = fluid.CPUPlace()
  7. main = fluid.Program()
  8. with fluid.program_guard(main):
  9. x = fluid.data(name='x', shape=[None, 13], dtype='float32')
  10. y = fluid.data(name='y', shape=[None, 1], dtype='float32')
  11. y_predict = fluid.layers.fc(input=x, size=1, act=None)
  12. cost = fluid.layers.square_error_cost(input=y_predict, label=y)
  13. avg_cost = fluid.layers.mean(cost)
  14.  
  15. # define beta decay variable
  16. def get_decayed_betas(beta1_init, beta2_init, decay_steps, decay_rate)
  17. global_step = lr_scheduler._decay_step_counter()
  18.  
  19. beta1 = fluid.layers.create_global_var(
  20. shape=[1],
  21. value=float(beta1_init),
  22. dtype='float32',
  23. # set persistable for save checkpoints and resume
  24. persistable=True,
  25. name="beta1")
  26. beta2 = fluid.layers.create_global_var(
  27. shape=[1],
  28. value=float(beta2_init),
  29. dtype='float32',
  30. # set persistable for save checkpoints and resume
  31. persistable=True,
  32. name="beta2")
  33.  
  34. div_res = global_step / decay_steps
  35. decayed_beta1 = beta1_init * (decay_rate**div_res)
  36. decayed_beta2 = beta2_init * (decay_rate**div_res)
  37. fluid.layers.assign(decayed_beta1, beta1)
  38. fluid.layers.assign(decayed_beta2, beta2)
  39.  
  40. return beta1, beta2
  41.  
  42. beta1, beta2 = get_decayed_betas(0.9, 0.99, 1e5, 0.9)
  43. adam_optimizer = fluid.optimizer.AdamOptimizer(
  44. learning_rate=0.01,
  45. beta1=beta1
  46. beta2=beta2)
  47. adam_optimizer.minimize(avg_cost)
  48.  
  49. fetch_list = [avg_cost]
  50. train_reader = paddle.batch(
  51. paddle.dataset.uci_housing.train(), batch_size=1)
  52. feeder = fluid.DataFeeder(place=place, feed_list=[x, y])
  53. exe = fluid.Executor(place)
  54. exe.run(fluid.default_startup_program())
  55. for data in train_reader():
  56. 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 numpy
  2. import paddle.fluid as fluid
  3.  
  4. x = fluid.layers.data(name='X', shape=[13], dtype='float32')
  5. y = fluid.layers.data(name='Y', shape=[1], dtype='float32')
  6. y_predict = fluid.layers.fc(input=x, size=1, act=None)
  7. cost = fluid.layers.square_error_cost(input=y_predict, label=y)
  8. loss = fluid.layers.mean(cost)
  9. adam = fluid.optimizer.AdamOptimizer(learning_rate=0.2)
  10. adam.minimize(loss)
  11.  
  12. place = fluid.CPUPlace() # fluid.CUDAPlace(0)
  13. exe = fluid.Executor(place)
  14.  
  15. x = numpy.random.random(size=(10, 13)).astype('float32')
  16. y = numpy.random.random(size=(10, 1)).astype('float32')
  17. exe.run(fluid.default_startup_program())
  18. outs = exe.run(program=fluid.default_main_program(),
  19. feed={'X': x, 'Y': y},
  20. fetch_list=[loss.name])
  • 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.Adam(learning_rate=0.02,
  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