optimizer.py 4.9 KB
Newer Older
W
WuHaobo 已提交
1
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
W
WuHaobo 已提交
2
#
W
WuHaobo 已提交
3 4 5
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
W
WuHaobo 已提交
6 7 8
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
W
WuHaobo 已提交
9 10 11 12 13
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
W
WuHaobo 已提交
14 15 16 17 18

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

littletomatodonkey's avatar
littletomatodonkey 已提交
19 20
import sys

21
import paddle
W
WuHaobo 已提交
22 23 24 25

__all__ = ['OptimizerBuilder']


littletomatodonkey's avatar
littletomatodonkey 已提交
26 27 28 29 30 31 32 33 34 35
class L1Decay(object):
    """
    L1 Weight Decay Regularization, which encourages the weights to be sparse.

    Args:
        factor(float): regularization coeff. Default:0.0.
    """

    def __init__(self, factor=0.0):
        super(L1Decay, self).__init__()
36
        self.factor = factor
littletomatodonkey's avatar
littletomatodonkey 已提交
37 38

    def __call__(self):
39
        reg = paddle.regularizer.L1Decay(self.factor)
littletomatodonkey's avatar
littletomatodonkey 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52
        return reg


class L2Decay(object):
    """
    L2 Weight Decay Regularization, which encourages the weights to be sparse.

    Args:
        factor(float): regularization coeff. Default:0.0.
    """

    def __init__(self, factor=0.0):
        super(L2Decay, self).__init__()
53
        self.factor = factor
littletomatodonkey's avatar
littletomatodonkey 已提交
54 55

    def __call__(self):
56
        reg = paddle.regularizer.L2Decay(self.factor)
littletomatodonkey's avatar
littletomatodonkey 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
        return reg


class Momentum(object):
    """
    Simple Momentum optimizer with velocity state.

    Args:
        learning_rate (float|Variable) - The learning rate used to update parameters.
            Can be a float value or a Variable with one float value as data element.
        momentum (float) - Momentum factor.
        regularization (WeightDecayRegularizer, optional) - The strategy of regularization.
    """

    def __init__(self,
                 learning_rate,
                 momentum,
                 parameter_list=None,
                 regularization=None,
                 **args):
        super(Momentum, self).__init__()
        self.learning_rate = learning_rate
        self.momentum = momentum
        self.parameter_list = parameter_list
        self.regularization = regularization

    def __call__(self):
84
        opt = paddle.optimizer.Momentum(
littletomatodonkey's avatar
littletomatodonkey 已提交
85 86
            learning_rate=self.learning_rate,
            momentum=self.momentum,
87 88
            parameters=self.parameter_list,
            weight_decay=self.regularization)
littletomatodonkey's avatar
littletomatodonkey 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
        return opt


class RMSProp(object):
    """
    Root Mean Squared Propagation (RMSProp) is an unpublished, adaptive learning rate method.

    Args:
        learning_rate (float|Variable) - The learning rate used to update parameters.
            Can be a float value or a Variable with one float value as data element.
        momentum (float) - Momentum factor.
        rho (float) - rho value in equation.
        epsilon (float) - avoid division by zero, default is 1e-6.
        regularization (WeightDecayRegularizer, optional) - The strategy of regularization.
    """

    def __init__(self,
                 learning_rate,
                 momentum,
                 rho=0.95,
                 epsilon=1e-6,
                 parameter_list=None,
                 regularization=None,
                 **args):
        super(RMSProp, self).__init__()
        self.learning_rate = learning_rate
        self.momentum = momentum
        self.rho = rho
        self.epsilon = epsilon
        self.parameter_list = parameter_list
        self.regularization = regularization

    def __call__(self):
122
        opt = paddle.optimizer.RMSProp(
littletomatodonkey's avatar
littletomatodonkey 已提交
123 124 125 126
            learning_rate=self.learning_rate,
            momentum=self.momentum,
            rho=self.rho,
            epsilon=self.epsilon,
127 128
            parameters=self.parameter_list,
            weight_decay=self.regularization)
littletomatodonkey's avatar
littletomatodonkey 已提交
129 130 131
        return opt


W
WuHaobo 已提交
132 133
class OptimizerBuilder(object):
    """
littletomatodonkey's avatar
littletomatodonkey 已提交
134
    Build optimizer
W
WuHaobo 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149

    Args:
        function(str): optimizer name of learning rate
        params(dict): parameters used for init the class
        regularizer (dict): parameters used for create regularization
    """

    def __init__(self,
                 function='Momentum',
                 params={'momentum': 0.9},
                 regularizer=None):
        self.function = function
        self.params = params
        # create regularizer
        if regularizer is not None:
littletomatodonkey's avatar
littletomatodonkey 已提交
150
            mod = sys.modules[__name__]
W
WuHaobo 已提交
151
            reg_func = regularizer['function'] + 'Decay'
littletomatodonkey's avatar
littletomatodonkey 已提交
152 153
            del regularizer['function']
            reg = getattr(mod, reg_func)(**regularizer)()
W
WuHaobo 已提交
154 155
            self.params['regularization'] = reg

W
WuHaobo 已提交
156
    def __call__(self, learning_rate, parameter_list):
littletomatodonkey's avatar
littletomatodonkey 已提交
157 158
        mod = sys.modules[__name__]
        opt = getattr(mod, self.function)
W
WuHaobo 已提交
159 160
        return opt(learning_rate=learning_rate,
                   parameter_list=parameter_list,
littletomatodonkey's avatar
littletomatodonkey 已提交
161
                   **self.params)()