# FtrlOptimizer¶

class paddle.fluid.optimizer.FtrlOptimizer(learning_rate, l1=0.0, l2=0.0, lr_power=-0.5, parameter_list=None, regularization=None, grad_clip=None, name=None)[source]

\begin{align}\begin{aligned}&new\_accum = squared\_accum + grad^2\\&if (lr\_power == -0.5):\\&\quad linear\_accum += grad - \frac{\sqrt{new\_accum} - \sqrt{squared\_accum}}{learning\_rate * param}\\&else:\\&\quad linear\_accum += grad - \frac{new\_accum^{-lr\_power} - accum^{-lr\_power}}{learning\_rate * param}\\ &x = l1 * sign(linear\_accum) - linear\_accum\\&if (lr\_power == -0.5):\\&\quad y = \frac{\sqrt{new\_accum}}{learning\_rate} + (2 * l2)\\&\quad pre\_shrink = \frac{x}{y}\\&\quad param = (abs(linear\_accum) > l1).select(pre\_shrink, 0.0)\\&else:\\&\quad y = \frac{new\_accum^{-lr\_power}}{learning\_rate} + (2 * l2)\\&\quad pre\_shrink = \frac{x}{y}\\&\quad param = (abs(linear\_accum) > l1).select(pre\_shrink, 0.0)\\&squared\_accum += grad^2\end{aligned}\end{align}
Parameters
• learning_rate (float|Variable) – Global learning rate.

• l1 (float) – L1 regularization strength, default is 0.0.

• l2 (float) – L2 regularization strength, default is 0.0.

• lr_power (float) – Learning Rate Power, default is -0.5.

• parameter_list (list, optional) – List of Variable names to update to minimize loss. This parameter is required in dygraph mode. The default value is None in static mode, at this time all parameters will be updated.

• regularization (WeightDecayRegularizer, optional) – The strategy of regularization. There are two method: L1Decay , L2Decay . If a parameter has set regularizer using ParamAttr already, the regularization setting here in optimizer will be ignored for this parameter. Otherwise, the regularization setting here in optimizer will take effect. Default None, meaning there is no regularization.

• grad_clip (GradientClipBase, optional) – Gradient cliping strategy, it’s an instance of some derived class of GradientClipBase . There are three cliping strategies ( GradientClipByGlobalNorm , GradientClipByNorm , GradientClipByValue ). Default None, meaning there is no gradient clipping.

• name (str, optional) – This parameter is used by developers to print debugging information. For details, please refer to Name. Default is None.

Raises

ValueError – If learning_rate, rho, epsilon, momentum are None.

Examples

import paddle
import numpy as np

place = fluid.CPUPlace()
main = fluid.Program()
with fluid.program_guard(main):
x = fluid.layers.data(name='x', shape=[13], dtype='float32')
y = fluid.layers.data(name='y', shape=[1], dtype='float32')
y_predict = fluid.layers.fc(input=x, size=1, act=None)
cost = fluid.layers.square_error_cost(input=y_predict, label=y)
avg_cost = fluid.layers.mean(cost)

ftrl_optimizer = fluid.optimizer.Ftrl(learning_rate=0.1)
ftrl_optimizer.minimize(avg_cost)

fetch_list = [avg_cost]
feeder = fluid.DataFeeder(place=place, feed_list=[x, y])
exe = fluid.Executor(place)
exe.run(fluid.default_startup_program())
exe.run(main, feed=feeder.feed(data), fetch_list=fetch_list)


Note

Currently, FtrlOptimizer doesn’t support sparse parameter optimization.

clear_gradients()

Clear the gradients of all optimized parameters for model.

Returns

None

Examples

import paddle.fluid as fluid
import numpy as np

with fluid.dygraph.guard():
value = np.arange(26).reshape(2, 13).astype("float32")
a = fluid.dygraph.to_variable(value)
linear = fluid.Linear(13, 5, dtype="float32")
# This can be any optimizer supported by dygraph.
parameter_list = linear.parameters())
out = linear(a)
out.backward()

current_step_lr()

Note

This API is ONLY available in Dygraph mode

Get current step learning rate. The return value is all the same When LearningRateDecay is not used, otherwise return the step learning rate.

Returns

The learning rate of the current step.

Return type

float

Examples

import paddle.fluid as fluid
import numpy as np

# example1: LearningRateDecay is not used, return value is all the same
with fluid.dygraph.guard():
emb = fluid.dygraph.Embedding([10, 10])
print(lr) # 0.001

# example2: PiecewiseDecay is used, return the step learning rate
with fluid.dygraph.guard():
inp = np.random.uniform(-0.1, 0.1, [10, 10]).astype("float32")
linear = fluid.dygraph.nn.Linear(10, 10)
inp = fluid.dygraph.to_variable(inp)
out = linear(inp)
loss = fluid.layers.reduce_mean(out)

bd = [2, 4, 6, 8]
value = [0.2, 0.4, 0.6, 0.8, 1.0]
parameter_list=linear.parameters())

# first step: learning rate is 0.2
np.allclose(adam.current_step_lr(), 0.2, rtol=1e-06, atol=0.0) # True

# learning rate for different steps
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]
for i in range(12):
np.allclose(lr, ret[i], rtol=1e-06, atol=0.0) # True

minimize(loss, startup_program=None, parameter_list=None, no_grad_set=None)

Add operations to minimize loss by updating parameter_list.

Parameters
• loss (Variable) – A Variable containing the value to minimize.

• startup_program (Program, optional) – Program for initializing parameters in parameter_list. The default value is None, at this time default_startup_program will be used.

• parameter_list (list, optional) – List of Variable or Variable.name to update to minimize loss. The default value is None, at this time all parameters will be updated.

• no_grad_set (set, optional) – Set of Variable or Variable.name that don’t need to be updated. The default value is None.

Returns

tuple (optimize_ops, params_grads), A list of operators appended by minimize and a list of (param, grad) variable pairs, param is Parameter, grad is the gradient value corresponding to the parameter. The returned tuple can be passed to fetch_list in Executor.run() to indicate program pruning. If so, the program will be pruned by feed and fetch_list before run, see details in Executor.

Return type

tuple

Examples

Please refer to the example of current Optimizer.

set_dict(state_dict)

Load optimizer state dict. For Adam optimizer, contains beta1, beta2, momentum etc. If LearningRateDecay have been used, global_step will be changed.

Parameters

state_dict (dict) – Dict contains all the Variable needed by optimizer

Returns

None

Examples

with fluid.dygraph.guard():
emb = fluid.dygraph.Embedding([10, 10])

state_dict = emb.state_dict()

parameter_list=emb.parameters())


state_dict()

Get state dict information from optimizer. It contain all the variable used by optimizer. For Adam optimizer, contains beta1, beta2, momentum etc. If LearningRateDecay have been used, global_step will be include in state dict. If the optimizer never be called(minimize function), the state_dict is empty.

Args: None :returns: dict contains all the variable used by optimizer :rtype: state_dict(dict)

Examples

import paddle.fluid as fluid

with fluid.dygraph.guard():
emb = fluid.dygraph.Embedding([10, 10])