SGDOptimizer

class paddle.fluid.optimizer. SGDOptimizer ( learning_rate, parameter_list=None, regularization=None, grad_clip=None, name=None ) [源代码]

该接口实现随机梯度下降算法的优化器

SGDOptimizer - 图1

参数:

  • learning_rate (float|Variable) - 用于更新参数的学习率。可以是浮点值,也可以是具有一个浮点值作为数据元素的变量。

  • parameter_list (list, 可选) - 指定优化器需要优化的参数。在动态图模式下必须提供该参数;在静态图模式下默认值为None,这时所有的参数都将被优化。

  • regularization (WeightDecayRegularizer,可选) - 正则化方法。支持两种正则化策略: cn_api_fluid_regularizer_L1Decay 、 cn_api_fluid_regularizer_L2Decay 。如果一个参数已经在 ParamAttr 中设置了正则化,这里的正则化设置将被忽略; 如果没有在 ParamAttr 中设置正则化,这里的设置才会生效。默认值为None,表示没有正则化。

  • grad_clip (GradientClipBase, 可选) – 梯度裁剪的策略,支持三种裁剪策略: cn_api_fluid_clip_GradientClipByGlobalNorm 、 cn_api_fluid_clip_GradientClipByNorm 、 cn_api_fluid_clip_GradientClipByValue 。 默认值为None,此时将不进行梯度裁剪。

  • name (str, 可选) - 可选的名称前缀,一般无需设置,默认值为None。

代码示例

  1. import paddle
  2. import paddle.fluid as fluid
  3. import numpy as np
  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. sgd_optimizer = fluid.optimizer.SGD(learning_rate=0.001)
  13. sgd_optimizer.minimize(avg_cost)
  14. fetch_list = [avg_cost]
  15. train_reader = paddle.batch(
  16. paddle.dataset.uci_housing.train(), batch_size=1)
  17. feeder = fluid.DataFeeder(place=place, feed_list=[x, y])
  18. exe = fluid.Executor(place)
  19. exe.run(fluid.default_startup_program())
  20. for data in train_reader():
  21. exe.run(main, feed=feeder.feed(data), fetch_list=fetch_list)

minimize ( loss, startup_program=None, parameter_list=None, no_grad_set=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

返回: tuple(optimize_ops, params_grads),其中optimize_ops为参数优化OP列表;param_grads为由(param, param_grad)组成的列表,其中param和param_grad分别为参数和参数的梯度。该返回值可以加入到 Executor.run() 接口的 fetch_list 参数中,若加入,则会重写 use_prune 参数为True,并根据 feedfetch_list 进行剪枝,详见 Executor 的文档。 返回类型: tuple

代码示例

  1. import paddle
  2. import paddle.fluid as fluid
  3. import numpy as np
  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. sgd_optimizer = fluid.optimizer.SGD(learning_rate=0.001)
  13. sgd_optimizer.minimize(avg_cost)
  14. fetch_list = [avg_cost]
  15. train_reader = paddle.batch(
  16. paddle.dataset.uci_housing.train(), batch_size=1)
  17. feeder = fluid.DataFeeder(place=place, feed_list=[x, y])
  18. exe = fluid.Executor(place)
  19. exe.run(fluid.default_startup_program())
  20. for data in train_reader():
  21. 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. with fluid.dygraph.guard():
  4. value = np.arange(26).reshape(2, 13).astype("float32")
  5. a = fluid.dygraph.to_variable(value)
  6. linear = fluid.Linear(13, 5, dtype="float32")
  7. optimizer = fluid.optimizer.SGDOptimizer(learning_rate=0.01,
  8. parameter_list=linear.parameters())
  9. out = linear(a)
  10. out.backward()
  11. optimizer.minimize(out)
  12. optimizer.clear_gradients()

set_lr ( )

注意:

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

手动设置当前 optimizer 的学习率。当使用LearningRateDecay时,无法使用该API手动设置学习率,因为这将导致冲突。

参数:

value (float|Variable) - 需要设置的学习率的值。

返回:无

代码示例

  1. import paddle.fluid as fluid
  2. with fluid.dygraph.guard():
  3. linear = fluid.dygraph.nn.Linear(10, 10)
  4. adam = fluid.optimizer.Adam(0.1, parameter_list=linear.parameters())
  5. # 通过Python float数值手动设置学习率
  6. lr_list = [0.2, 0.3, 0.4, 0.5, 0.6]
  7. for i in range(5):
  8. adam.set_lr(lr_list[i])
  9. print("current lr is {}".format(adam.current_step_lr()))
  10. # 打印结果:
  11. # current lr is 0.2
  12. # current lr is 0.3
  13. # current lr is 0.4
  14. # current lr is 0.5
  15. # current lr is 0.6
  16. # 通过 框架的Variable 设置学习率
  17. lr_var = fluid.layers.create_global_var(shape=[1], value=0.7, dtype='float32')
  18. adam.set_lr(lr_var)
  19. print("current lr is {}".format(adam.current_step_lr()))
  20. # 打印结果:
  21. # current lr is 0.7

current_step_lr ( )

注意:

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

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

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

返回类型:float

代码示例

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