xavier.py 5.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#   Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 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.

from ...fluid.initializer import XavierInitializer

17 18
__all__ = []

19 20

class XavierNormal(XavierInitializer):
21
    r"""
22 23 24
    This class implements the Xavier weight initializer from the paper
    `Understanding the difficulty of training deep feedforward neural
    networks <http://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf>`_
25
    by Xavier Glorot and Yoshua Bengio, using a normal distribution whose mean is :math:`0` and standard deviation is
26 27 28

    .. math::

29
        \sqrt{\frac{2.0}{fan\_in + fan\_out}}.
30 31 32


    Args:
33 34 35 36 37
        fan_in (float, optional): fan_in for Xavier initialization, which is
                inferred from the Tensor. The default value is None.
        fan_out (float, optional): fan_out for Xavier initialization, which is
                 inferred from the Tensor. The default value is None.
        name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
38 39 40 41 42 43

    Returns:
        A parameter initialized by Xavier weight, using a normal distribution.

    Examples:
        .. code-block:: python
44
            :name: initializer_XavierNormal-example
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

            import paddle

            data = paddle.ones(shape=[3, 1, 2], dtype='float32')
            weight_attr = paddle.framework.ParamAttr(
                name="linear_weight",
                initializer=paddle.nn.initializer.XavierNormal())
            bias_attr = paddle.framework.ParamAttr(
                name="linear_bias",
                initializer=paddle.nn.initializer.XavierNormal())
            linear = paddle.nn.Linear(2, 2, weight_attr=weight_attr, bias_attr=bias_attr)
            # inear.weight:  [[ 0.06910077 -0.18103665]
            #                 [-0.02546741 -1.0402188 ]]
            # linear.bias:  [-0.5012929   0.12418364]

            res = linear(data)
            # res:  [[[-0.4576595 -1.0970719]]
            #        [[-0.4576595 -1.0970719]]
            #        [[-0.4576595 -1.0970719]]]
    """

    def __init__(self, fan_in=None, fan_out=None, name=None):
67 68 69 70
        super(XavierNormal, self).__init__(uniform=False,
                                           fan_in=fan_in,
                                           fan_out=fan_out,
                                           seed=0)
71 72 73


class XavierUniform(XavierInitializer):
74
    r"""
75 76 77 78 79 80 81
    This class implements the Xavier weight initializer from the paper
    `Understanding the difficulty of training deep feedforward neural
    networks <http://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf>`_
    by Xavier Glorot and Yoshua Bengio.

    This initializer is designed to keep the scale of the gradients
    approximately same in all the layers. In case of Uniform distribution,
82
    the range is :math:`[-x,x]`, where
83 84 85

    .. math::

86
        x = \sqrt{\frac{6.0}{fan\_in + fan\_out}}.
87 88

    Args:
89 90 91 92 93
        fan_in (float, optional): fan_in for Xavier initialization, which is
                inferred from the Tensor. The default value is None.
        fan_out (float, optional): fan_out for Xavier initialization, which is
                 inferred from the Tensor. The default value is None.
        name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
94 95 96 97 98 99

    Returns:
        A parameter initialized by Xavier weight, using a uniform distribution.

    Examples:
        .. code-block:: python
100
            :name: initializer_XavierUniform-example
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122

            import paddle

            data = paddle.ones(shape=[3, 1, 2], dtype='float32')
            weight_attr = paddle.framework.ParamAttr(
                name="linear_weight",
                initializer=paddle.nn.initializer.XavierUniform())
            bias_attr = paddle.framework.ParamAttr(
                name="linear_bias",
                initializer=paddle.nn.initializer.XavierUniform())
            linear = paddle.nn.Linear(2, 2, weight_attr=weight_attr, bias_attr=bias_attr)
            # linear.weight:  [[-0.04229349 -1.1248565 ]
            #                  [-0.10789523 -0.5938053 ]]
            # linear.bias:  [ 1.1983747  -0.40201235]

            res = linear(data)
            # res:  [[[ 1.0481861 -2.1206741]]
            #        [[ 1.0481861 -2.1206741]]
            #        [[ 1.0481861 -2.1206741]]]
    """

    def __init__(self, fan_in=None, fan_out=None, name=None):
123 124 125 126
        super(XavierUniform, self).__init__(uniform=True,
                                            fan_in=fan_in,
                                            fan_out=fan_out,
                                            seed=0)