activation.py 44.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   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.

15
# TODO: define activation functions of neural network
16

Z
zhiboniu 已提交
17
from ..initializer import Constant
Q
Qi Li 已提交
18
from paddle.framework import get_default_dtype
19
from .. import functional as F
Z
zhiboniu 已提交
20
from paddle.nn import Layer
21

22 23
__all__ = []

24

25 26 27 28 29
class CELU(Layer):
    r"""
    CELU Activation.

    .. math::
30

31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
        CELU(x) = max(0, x) + min(0, \alpha * (e^{x/\alpha}-1))

    Parameters:
        alpha (float, optional): The 'alpha' value of the CELU formulation. Default is 1.0.
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.

    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.

    Examples:
        .. code-block:: python

            import paddle
46

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
            x = paddle.to_tensor([[-1. ,6.], [1., 15.6]])
            m = paddle.nn.CELU(0.2)
            out = m(x)
            # [[-0.19865242,  6.        ],
            #  [ 1.        , 15.60000038]]
    """

    def __init__(self, alpha=1.0, name=None):
        super(CELU, self).__init__()
        self._alpha = alpha
        self._name = name

    def forward(self, x):
        return F.celu(x, self._alpha, self._name)

    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'alpha={}{}'.format(self._alpha, name_str)


Z
zhiboniu 已提交
67
class ELU(Layer):
68
    r"""
69 70
    ELU Activation.

71
    .. math::
72

Z
zhupengyang 已提交
73 74 75 76 77 78 79
        ELU(x)=
            \left\{
                \begin{array}{lcl}
                x,& &\text{if } \ x > 0 \\
                alpha * (e^{x} - 1),& &\text{if } \ x <= 0
                \end{array}
            \right.
80 81 82 83 84

    Parameters:
        alpha (float, optional): The 'alpha' value of the ELU formulation. Default is 1.0.
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.
85

86 87 88
    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.
89

90 91 92
    Examples:
        .. code-block:: python

93
            import paddle
94

Z
zhupengyang 已提交
95
            x = paddle.to_tensor([[-1. ,6.], [1., 15.6]])
96 97 98 99
            m = paddle.nn.ELU(0.2)
            out = m(x)
            # [[-0.12642411  6.        ]
            #  [ 1.          15.6      ]]
100 101 102 103 104 105 106 107 108 109
    """

    def __init__(self, alpha=1.0, name=None):
        super(ELU, self).__init__()
        self._alpha = alpha
        self._name = name

    def forward(self, x):
        return F.elu(x, self._alpha, self._name)

110 111 112 113
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'alpha={}{}'.format(self._alpha, name_str)

114

Z
zhiboniu 已提交
115
class GELU(Layer):
116
    r"""
117 118 119 120
    GELU Activation.

    If approximate is True

121
    .. math::
122

123
        GELU(x) = 0.5 * x * (1 + tanh(\sqrt{\frac{2}{\pi}} * (x + 0.044715x^{3})))
124 125 126

    else

127
    .. math::
128

129
        GELU(x) = 0.5 * x * (1 + erf(\frac{x}{\sqrt{2}}))
130 131 132 133 134

    Parameters:
        approximate (bool, optional): Wether to enable approximation. Default is False.
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.
135

136 137 138
    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.
139

140 141
    Examples:
        .. code-block:: python
142

143
            import paddle
144

145
            x = paddle.to_tensor([[-1, 0.5],[1, 1.5]])
146

147 148
            m = paddle.nn.GELU()
            out = m(x) # [-0.158655 0.345731 0.841345 1.39979]
149

150 151
            m = paddle.nn.GELU(True)
            out = m(x) # [-0.158808 0.345714 0.841192 1.39957]
152 153 154 155 156 157 158 159 160 161
    """

    def __init__(self, approximate=False, name=None):
        super(GELU, self).__init__()
        self._approximate = approximate
        self._name = name

    def forward(self, x):
        return F.gelu(x, self._approximate, self._name)

162 163 164 165
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'approximate={}{}'.format(self._approximate, name_str)

166

Z
zhiboniu 已提交
167
class Hardshrink(Layer):
168
    r"""
169 170 171 172 173
    Hardshrink Activation

    .. math::

        hardshrink(x)=
174 175 176 177 178 179 180
            \left\{
                \begin{array}{rcl}
                    x, & & if \ x > threshold \\
                    x, & & if \ x < -threshold \\
                    0, & & if \ others
            \end{array}
            \right.
181 182 183 184 185 186 187 188 189 190 191 192 193 194

    Parameters:
        threshold (float, optional): The value of threshold for hardthrink. Default is 0.5
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.

    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.

    Examples:

        .. code-block:: python

195
            import paddle
196

Z
zhupengyang 已提交
197
            x = paddle.to_tensor([-1, 0.3, 2.5])
198 199
            m = paddle.nn.Hardshrink()
            out = m(x) # [-1., 0., 2.5]
200 201 202 203 204 205 206 207
    """

    def __init__(self, threshold=0.5, name=None):
        super(Hardshrink, self).__init__()
        self._threshold = threshold
        self._name = name

    def forward(self, x):
208
        return F.hardshrink(x, self._threshold, self._name)
209

210 211 212 213
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'threshold={}{}'.format(self._threshold, name_str)

214

Z
zhiboniu 已提交
215
class Hardswish(Layer):
216
    r"""
217 218
    Hardswish activation. Create a callable object of `Hardswish`. Hardswish
    is proposed in MobileNetV3, and performs better in computational stability
219 220 221 222 223 224
    and efficiency compared to swish function. For more details please refer
    to: https://arxiv.org/pdf/1905.02244.pdf

    .. math::

        Hardswish(x)=
225 226 227 228 229 230 231
            \left\{
                \begin{array}{cll}
                0 &, & \text{if } x \leq -3 \\
                x &, & \text{if } x \geq 3 \\
                \frac{x(x+3)}{6} &, & \text{otherwise}
                \end{array}
            \right.
232

233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259

    Parameters:
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.

    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.

    Examples:

        .. code-block:: python

            import paddle

            x = paddle.to_tensor([-4., 5., 1.])
            m = paddle.nn.Hardswish()
            out = m(x) # [0., 5., 0.666667]
    """

    def __init__(self, name=None):
        super(Hardswish, self).__init__()
        self._name = name

    def forward(self, x):
        return F.hardswish(x, self._name)

260 261 262 263
    def extra_repr(self):
        name_str = 'name={}'.format(self._name) if self._name else ''
        return name_str

264

Z
zhiboniu 已提交
265
class Tanh(Layer):
266
    r"""
W
WangXi 已提交
267 268 269
    Tanh Activation.

    .. math::
270
        Tanh(x) = \frac{e^{x} - e^{-x}}{e^{x} + e^{-x}}
W
WangXi 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285

    Parameters:
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.

    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.

    Examples:

        .. code-block:: python

            import paddle

286
            x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3])
W
WangXi 已提交
287 288
            m = paddle.nn.Tanh()
            out = m(x)
W
WangXi 已提交
289
            print(out)
290 291
            # Tensor(shape=[4], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [-0.37994894, -0.19737533,  0.09966800,  0.29131261])
W
WangXi 已提交
292 293 294 295 296 297 298 299 300
    """

    def __init__(self, name=None):
        super(Tanh, self).__init__()
        self._name = name

    def forward(self, x):
        return F.tanh(x, self._name)

301 302 303 304
    def extra_repr(self):
        name_str = 'name={}'.format(self._name) if self._name else ''
        return name_str

W
WangXi 已提交
305

Z
zhiboniu 已提交
306
class Hardtanh(Layer):
307
    r"""
308
    Hardtanh Activation. Create a callable object of `Hardtanh`.
309 310 311

    .. math::

312 313 314 315 316 317 318 319 320
        Hardtanh(x)=
            \left\{
                \begin{array}{cll}
                    max,& & \text{if } x > max \\
                    min,& & \text{if } x < min \\
                    x,& & \text{otherwise}
                \end{array}
            \right.

321 322 323 324 325 326

    Parameters:
        min (float, optional): The value of min for Hardtanh. Default is -1.
        max (float, optional): The value of max for Hardtanh. Default is 1.
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.
327

328 329 330
    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.
331

332 333 334 335 336
    Examples:
        .. code-block:: python

            import paddle

Z
zhupengyang 已提交
337
            x = paddle.to_tensor([-1.5, 0.3, 2.5])
338
            m = paddle.nn.Hardtanh()
Z
zhupengyang 已提交
339
            out = m(x) # [-1., 0.3, 1.]
340 341 342 343 344 345 346 347 348 349 350
    """

    def __init__(self, min=-1.0, max=1.0, name=None):
        super(Hardtanh, self).__init__()
        self._min = min
        self._max = max
        self._name = name

    def forward(self, x):
        return F.hardtanh(x, self._min, self._max, self._name)

351 352 353 354
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'min={}, max={}{}'.format(self._min, self._max, name_str)

355

Z
zhiboniu 已提交
356
class PReLU(Layer):
357 358 359 360 361 362 363 364 365
    """
    PReLU Activation.

    .. math::

        PReLU(x) = max(0, x) + weight * min(0, x)

    Parameters:
        num_parameters (int, optional): Number of `weight` to learn. The supported values are:
366
            1 - a single parameter `alpha` is used for all input channels;
367
            Number of channels - a separate `alpha` is used for each input channel.
368 369
            Default is 1.
        init (float, optional): Init value of learnable `weight`. Default is 0.25.
370
        weight_attr(ParamAttr, optional): The parameter attribute for the learnable `weight`.
371
            Default is None. For more information, please refer to :ref:`api_paddle_ParamAttr`.
372 373
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.
374 375
        data_format(str, optional): Data format that specifies the layout of input.
            It may be "NC", "NCL", "NCHW", "NCDHW", "NLC", "NHWC" or "NDHWC". Default: "NCHW".
376

377
    Shape:
Q
Qi Li 已提交
378
        - input: Tensor with any shape. Default dtype is float32.
379
        - output: Tensor with the same shape as input.
380

381 382 383 384
    Examples:
        .. code-block:: python

            import paddle
Q
Qi Li 已提交
385
            paddle.set_default_dtype("float64")
386

387 388 389 390 391 392 393
            data = paddle.to_tensor([[[[-2.0,  3.0, -4.0,  5.0],
                                    [ 3.0, -4.0,  5.0, -6.0],
                                    [-7.0, -8.0,  8.0,  9.0]],
                                    [[ 1.0, -2.0, -3.0,  4.0],
                                    [-5.0,  6.0,  7.0, -8.0],
                                    [ 6.0,  7.0,  8.0,  9.0]]]])

394
            m = paddle.nn.PReLU(1, 0.25)
395 396
            out = m(data)
            print(out)
397 398 399 400 401 402 403 404
            # [[[[-0.5 ,  3.  , -1.  ,  5.  ],
            #    [ 3.  , -1.  ,  5.  , -1.5 ],
            #    [-1.75, -2.  ,  8.  ,  9.  ]],
            #   [[ 1.  , -0.5 , -0.75,  4.  ],
            #    [-1.25,  6.  ,  7.  , -2.  ],
            #    [ 6.  ,  7.  ,  8.  ,  9.  ]]]]
    """

405 406 407 408 409 410 411 412
    def __init__(
        self,
        num_parameters=1,
        init=0.25,
        weight_attr=None,
        data_format="NCHW",
        name=None,
    ):
413 414 415 416 417
        super(PReLU, self).__init__()
        self._num_parameters = num_parameters
        self._init = init
        self._weight_attr = weight_attr
        self._name = name
418
        self._data_format = data_format
419

420 421 422 423 424 425 426
        self._weight = self.create_parameter(
            attr=self._weight_attr,
            shape=[self._num_parameters],
            dtype=get_default_dtype(),
            is_bias=False,
            default_initializer=Constant(self._init),
        )
427 428

    def forward(self, x):
429
        return F.prelu(x, self._weight, data_format=self._data_format)
430

431 432
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
433
        return 'num_parameters={}, data_format={}, init={}, dtype={}{}'.format(
434 435 436 437 438 439
            self._num_parameters,
            self._data_format,
            self._init,
            self._dtype,
            name_str,
        )
440

441

442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
class RReLU(Layer):
    r"""
    RReLU activation layer.

    Applies the randomized leaky rectified liner unit function to improve generalization performance,
    as described in the paper:
    `Empirical Evaluation of Rectified Activations in Convolutional Network <https://arxiv.org/abs/1505.00853>`_

    During training, randomly samples the negative slope for activation values as described below:

    .. math::

        RReLU(x)=
            \left\{
                \begin{array}{rcl}
                    x, & & if \ x >= 0 \\
                    a * x, & & otherwise \\
                \end{array}
            \right.

    where :math:`x` is the input tensor,
    :math:`a` is randomly sampled from uniform distribution in range (:math:`lower`, :math:`upper`),

    In the test phase, the negative slope will take the average value of :math:`lower` and :math:`upper`:

    .. math::

        RReLU(x)=
            \left\{
                \begin{array}{rcl}
                    x, & & if \ x >= 0 \\
                    (lower + upper) * 0.5 * x, & & otherwise \\
                \end{array}
            \right.

    where :math:`x` is the input tensor,
    :math:`lower` and :math:`upper` are the bounds of uniform distribution.

    Parameters:
        lower (float, optional): The lower bound of uniform distribution. Default: 0.125.
        upper (float, optional): The upper bound of uniform distribution. Default: 0.333.
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.

    Shape:
        - input: Tensor with any shape. Default dtype is float32.
        - output: Tensor with the same shape as input.

    Examples:
        .. code-block:: python

            import paddle

            input_tensor = paddle.to_tensor([[[[-2.0,  3.0, -4.0,  5.0],
                                            [ 3.0, -4.0,  5.0, -6.0],
                                            [-7.0, -8.0,  8.0,  9.0]],
                                            [[ 1.0, -2.0, -3.0,  4.0],
                                            [-5.0,  6.0,  7.0, -8.0],
                                            [ 6.0,  7.0,  8.0,  9.0]]]], dtype='float32')

            rrelu_layer = paddle.nn.RReLU(0.1, 0.3)
503 504
            out = rrelu_layer(input_tensor)
            print(out)
505 506 507 508 509 510 511 512
            #[[[[-0.20000899  3.         -0.88108218  5.        ]
            #   [ 3.         -0.55175185  5.         -1.07761011]
            #   [-1.06806871 -1.98962009  8.          9.        ]]
            #  [[ 1.         -0.52382672 -0.65515128  4.        ]
            #   [-1.37663394  6.          7.         -2.34657836]
            #   [ 6.          7.          8.          9.        ]]]]
    """

513
    def __init__(self, lower=1.0 / 8.0, upper=1.0 / 3.0, name=None):
514 515 516 517 518 519
        super(RReLU, self).__init__()
        self._lower = lower
        self._upper = upper
        self._name = name

    def forward(self, x):
520 521 522
        return F.rrelu(
            x, lower=self._lower, upper=self._upper, training=self.training
        )
523 524 525 526

    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'lower={}, upper={}, training={}, dtype={}{}'.format(
527 528
            self._lower, self._upper, self.training, self._dtype, name_str
        )
529 530


Z
zhiboniu 已提交
531
class ReLU(Layer):
532 533 534
    """
    ReLU Activation.

535
    .. math::
536

537
        ReLU(x) = max(x, 0)
538 539

    Parameters:
540 541 542 543 544 545
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.

    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.
546

547 548 549
    Examples:
        .. code-block:: python

550
            import paddle
551

Z
zhupengyang 已提交
552
            x = paddle.to_tensor([-2., 0., 1.])
553
            m = paddle.nn.ReLU()
554 555 556
            out = m(x)
            print(out)
            # [0., 0., 1.]
557 558
    """

559
    def __init__(self, name=None):
560
        super(ReLU, self).__init__()
561
        self._name = name
562

563 564
    def forward(self, x):
        return F.relu(x, self._name)
565

566 567 568 569
    def extra_repr(self):
        name_str = 'name={}'.format(self._name) if self._name else ''
        return name_str

570

Z
zhiboniu 已提交
571
class ReLU6(Layer):
572 573 574 575 576
    """
    ReLU6 Activation

    .. math::

577
        ReLU6(x) = min(max(0,x), 6)
578 579 580 581 582 583 584 585 586 587 588 589

    Parameters:
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.

    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.

    Examples:
        .. code-block:: python

590
            import paddle
591

592
            x = paddle.to_tensor([-1., 0.3, 6.5])
593
            m = paddle.nn.ReLU6()
594 595 596
            out = m(x)
            print(out)
            # [0, 0.3, 6]
597 598 599 600 601 602 603 604 605
    """

    def __init__(self, name=None):
        super(ReLU6, self).__init__()
        self._name = name

    def forward(self, x):
        return F.relu6(x, self._name)

606 607 608 609
    def extra_repr(self):
        name_str = 'name={}'.format(self._name) if self._name else ''
        return name_str

610

Z
zhiboniu 已提交
611
class SELU(Layer):
612
    r"""
613 614 615 616
    SELU Activation

    .. math::

617
        SELU(x)= scale *
618 619 620 621 622 623
            \left\{
                \begin{array}{lcl}
                x,& &\text{if } \ x > 0 \\
                alpha * e^{x} - alpha,& &\text{if } \ x <= 0
                \end{array}
            \right.
624 625

    Parameters:
626 627
        scale (float, optional): The value of scale(must be greater than 1.0) for SELU. Default is 1.0507009873554804934193349852946
        alpha (float, optional): The value of alpha(must be no less than zero) for SELU. Default is 1.6732632423543772848170429916717
628 629 630 631 632 633 634 635 636 637
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.

    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.

    Examples:
        .. code-block:: python

638
            import paddle
639

640
            x = paddle.to_tensor([[0.0, 1.0],[2.0, 3.0]])
641
            m = paddle.nn.SELU()
642 643 644
            out = m(x)
            print(out)
            # [[0, 1.050701],[2.101402, 3.152103]]
645 646
    """

647 648 649 650 651 652
    def __init__(
        self,
        scale=1.0507009873554804934193349852946,
        alpha=1.6732632423543772848170429916717,
        name=None,
    ):
653 654 655 656 657 658 659 660
        super(SELU, self).__init__()
        self._scale = scale
        self._alpha = alpha
        self._name = name

    def forward(self, x):
        return F.selu(x, self._scale, self._alpha, self._name)

661 662
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
663 664 665
        return 'scale={:.16f}, alpha={:.16f}{}'.format(
            self._scale, self._alpha, name_str
        )
666

667

Z
zhiboniu 已提交
668
class LeakyReLU(Layer):
669
    r"""
670 671
    Leaky ReLU Activation. Create a callable object of `LeakyReLU` to calculate
    the `LeakyReLU` of input `x`.
C
ceci3 已提交
672

673
    .. math::
C
ceci3 已提交
674

675
        LeakyReLU(x)=
676 677 678 679 680 681 682
            \left\{
                \begin{array}{rcl}
                    x, & & if \ x >= 0 \\
                    negative\_slope * x, & & otherwise \\
                \end{array}
            \right.

C
ceci3 已提交
683 684

    Parameters:
685 686
        negative_slope (float, optional): Slope of the activation function at
            :math:`x < 0` . Default is 0.01.
687 688
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.
689

690 691 692
    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.
693

C
ceci3 已提交
694 695 696
    Examples:
        .. code-block:: python

697
            import paddle
698

699
            m = paddle.nn.LeakyReLU()
700
            x = paddle.to_tensor([-2.0, 0, 1])
701
            out = m(x)  # [-0.02, 0., 1.]
C
ceci3 已提交
702 703
    """

704
    def __init__(self, negative_slope=0.01, name=None):
C
ceci3 已提交
705
        super(LeakyReLU, self).__init__()
706
        self._negative_slope = negative_slope
707
        self._name = name
C
ceci3 已提交
708

709
    def forward(self, x):
710
        return F.leaky_relu(x, self._negative_slope, self._name)
C
ceci3 已提交
711

712 713 714 715
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'negative_slope={}{}'.format(self._negative_slope, name_str)

C
ceci3 已提交
716

Z
zhiboniu 已提交
717
class Sigmoid(Layer):
718
    r"""
719
    this interface is used to construct a callable object of the ``Sigmoid`` class. This layer calcluate the `sigmoid` of input x.
720

721
    .. math::
S
swtkiwi 已提交
722

723
        sigmoid(x) = \frac{1}{1 + e^{-x}}
724

725
    Parameters:
726
        name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
727

728 729
    Shape:
        x: N-D tensor, available dtype is float16, float32, float64.
730 731

    Returns:
732
        A callable object of Sigmoid.
733

734
    Examples:
735

736 737
        .. code-block:: python

738
            import paddle
739

740 741 742
            m = paddle.nn.Sigmoid()
            x = paddle.to_tensor([1.0, 2.0, 3.0, 4.0])
            out = m(x) # [0.7310586, 0.880797, 0.95257413, 0.98201376]
743 744
    """

745
    def __init__(self, name=None):
746
        super(Sigmoid, self).__init__()
747
        self.name = name
748

749 750
    def forward(self, x):
        return F.sigmoid(x, self.name)
751

752 753 754 755
    def extra_repr(self):
        name_str = 'name={}'.format(self.name) if self.name else ''
        return name_str

756

Z
zhiboniu 已提交
757
class Hardsigmoid(Layer):
758
    r"""
759 760
    ``Hardsigmoid`` Activiation Layers, Construct a callable object of
    the ``Hardsigmoid`` class. This layer calcluate the `hardsigmoid` of input x.
761 762 763 764 765 766 767

    A 3-part piecewise linear approximation of sigmoid(https://arxiv.org/abs/1603.00391),
    which is much faster than sigmoid.

    .. math::

        Hardsigmoid(x)=
768 769 770 771 772 773 774 775
            \left\{
                \begin{array}{rcl}
            0, & & \text{if } \ x \leq -3 \\
            1, & & \text{if } \ x \geq 3 \\
            x/6 + 1/2, & & \text{otherwise}
                \end{array}
            \right.

776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
    Parameters:
        name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.

    Shape:
        x: N-D tensor, available dtype is float32, float64.

    Returns:
        A callable object of Hardsigmoid.

    Examples:

        .. code-block:: python

          import paddle

Z
zhupengyang 已提交
791
          m = paddle.nn.Hardsigmoid()
792 793 794 795 796 797 798 799 800
          x = paddle.to_tensor([-4., 5., 1.])
          out = m(x) # [0., 1, 0.666667]
    """

    def __init__(self, name=None):
        super(Hardsigmoid, self).__init__()
        self.name = name

    def forward(self, x):
801
        return F.hardsigmoid(x, name=self.name)
802

803 804 805 806
    def extra_repr(self):
        name_str = 'name={}'.format(self.name) if self.name else ''
        return name_str

807

Z
zhiboniu 已提交
808
class Softplus(Layer):
809
    r"""
810 811 812
    Softplus Activation

    .. math::
813 814 815 816
        softplus(x)=\begin{cases}
                \frac{1}{\beta} * \log(1 + e^{\beta * x}),&x\leqslant\frac{\varepsilon}{\beta};\\
                x,&x>\frac{\varepsilon}{\beta}.
            \end{cases}
817 818

    Parameters:
819 820 821
        beta (float, optional): The value of :math:`\beta` for Softplus. Default is 1
        threshold (float, optional): The value of :math:`\varepsilon` for Softplus. Default is 20
        name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
822 823 824 825 826 827 828 829

    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.

    Examples:
        .. code-block:: python

830
            import paddle
831

832
            x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3], dtype='float32')
833 834
            m = paddle.nn.Softplus()
            out = m(x) # [0.513015, 0.598139, 0.744397, 0.854355]
835 836 837 838 839 840 841 842 843 844 845
    """

    def __init__(self, beta=1, threshold=20, name=None):
        super(Softplus, self).__init__()
        self._beta = beta
        self._threshold = threshold
        self._name = name

    def forward(self, x):
        return F.softplus(x, self._beta, self._threshold, self._name)

846 847
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
848 849 850
        return 'beta={}, threshold={}{}'.format(
            self._beta, self._threshold, name_str
        )
851

852

Z
zhiboniu 已提交
853
class Softshrink(Layer):
854
    r"""
855 856 857 858
    Softshrink Activation

    .. math::

859 860 861 862 863 864 865 866 867
        Softshrink(x)=
            \left\{
                \begin{array}{rcl}
                x - threshold,& & \text{if } x > threshold \\
                x + threshold,& & \text{if } x < -threshold \\
                0,& &  \text{otherwise}
            \end{array}
            \right.

868 869

    Parameters:
870
        threshold (float, optional): The value of threshold(must be no less than zero) for softplus. Default is 0.5
871 872 873 874 875 876 877 878 879 880
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.

    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.

    Examples:
        .. code-block:: python

881
            import paddle
882

883
            x = paddle.to_tensor([-0.9, -0.2, 0.1, 0.8])
884
            m = paddle.nn.Softshrink()
885 886 887 888
            out = m(x)
            print(out)
            # Tensor(shape=[4], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [-0.39999998,  0.        ,  0.        ,  0.30000001])
889 890 891 892 893 894 895 896 897 898
    """

    def __init__(self, threshold=0.5, name=None):
        super(Softshrink, self).__init__()
        self._threshold = threshold
        self._name = name

    def forward(self, x):
        return F.softshrink(x, self._threshold, self._name)

899 900 901 902
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'threshold={}{}'.format(self._threshold, name_str)

903

Z
zhiboniu 已提交
904
class Softsign(Layer):
905
    r"""
906 907 908 909
    Softsign Activation

    .. math::

910
        Softsign(x) = \frac{x}{1 + |x|}
911 912 913 914 915 916 917 918 919 920 921 922

    Parameters:
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.

    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.

    Examples:
        .. code-block:: python

923
            import paddle
924

925
            x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3])
926
            m = paddle.nn.Softsign()
927 928 929 930
            out = m(x)
            print(out)
            # Tensor(shape=[4], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [-0.28571430, -0.16666666,  0.09090909,  0.23076925])
931 932 933 934 935 936 937 938 939
    """

    def __init__(self, name=None):
        super(Softsign, self).__init__()
        self._name = name

    def forward(self, x):
        return F.softsign(x, self._name)

940 941 942 943
    def extra_repr(self):
        name_str = 'name={}'.format(self._name) if self._name else ''
        return name_str

944

Z
zhiboniu 已提交
945
class Swish(Layer):
946
    r"""
947 948 949 950
    Swish Activation.

    .. math::

951
        Swish(x) = \frac{x}{1 + e^{-x}}
952 953 954 955 956 957 958 959 960 961 962 963 964 965

    Parameters:
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.

    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.

    Examples:
        .. code-block:: python

            import paddle

966
            x = paddle.to_tensor([-2., 0., 1.])
967
            m = paddle.nn.Swish()
968 969 970 971
            out = m(x)
            print(out)
            # Tensor(shape=[3], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [-0.23840584,  0.        ,  0.73105854])
972 973 974 975 976 977 978 979 980
    """

    def __init__(self, name=None):
        super(Swish, self).__init__()
        self._name = name

    def forward(self, x):
        return F.swish(x, self._name)

981 982 983 984
    def extra_repr(self):
        name_str = 'name={}'.format(self._name) if self._name else ''
        return name_str

985

986 987 988 989 990 991 992 993 994 995 996 997
class Mish(Layer):
    r"""
    Mish Activation.

    ..  math::

        softplus(x) = \begin{cases}
                x, \text{if } x > \text{threshold} \\
                \ln(1 + e^{x}),  \text{otherwise}
            \end{cases}

        Mish(x) = x * \tanh(softplus(x))
998

999 1000 1001 1002 1003 1004 1005
    Parameters:
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.

    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.
1006

1007 1008 1009 1010 1011 1012
    Examples:

        .. code-block:: python

            import paddle

W
wangxinxin08 已提交
1013
            x = paddle.to_tensor([-5., 0., 5.])
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
            m = paddle.nn.Mish()
            out = m(x) # [-0.03357624, 0., 4.99955208]

    """

    def __init__(self, name=None):
        super(Mish, self).__init__()
        self._name = name

    def forward(self, x):
        return F.mish(x, self._name)

    def extra_repr(self):
        name_str = 'name={}'.format(self._name) if self._name else ''
        return name_str


Z
zhiboniu 已提交
1031
class Tanhshrink(Layer):
1032 1033 1034 1035 1036
    """
    Tanhshrink Activation

    .. math::

1037
        Tanhshrink(x) = x - tanh(x)
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049

    Parameters:
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.

    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.

    Examples:
        .. code-block:: python

1050
            import paddle
1051

1052
            x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3])
1053
            m = paddle.nn.Tanhshrink()
1054 1055 1056 1057
            out = m(x)
            print(out)
            # Tensor(shape=[4], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [-0.02005106, -0.00262468,  0.00033200,  0.00868741])
1058 1059 1060 1061 1062 1063 1064 1065 1066
    """

    def __init__(self, name=None):
        super(Tanhshrink, self).__init__()
        self._name = name

    def forward(self, x):
        return F.tanhshrink(x, self._name)

1067 1068 1069 1070
    def extra_repr(self):
        name_str = 'name={}'.format(self._name) if self._name else ''
        return name_str

1071

Z
zhiboniu 已提交
1072
class ThresholdedReLU(Layer):
1073
    r"""
1074 1075 1076 1077
    Thresholded ReLU Activation

    .. math::

1078 1079 1080 1081 1082 1083 1084 1085
        ThresholdedReLU(x) =
            \left\{
                \begin{array}{rl}
                x,& \text{if } \ x > threshold \\
                0,& \text{otherwise}
                \end{array}
            \right.

1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100

    Parameters:
        threshold (float, optional): The value of threshold for ThresholdedReLU. Default is 1.0
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.

    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.

    Examples:
        .. code-block:: python

            import paddle

1101
            x = paddle.to_tensor([2., 0., 1.])
1102
            m = paddle.nn.ThresholdedReLU()
1103 1104 1105 1106
            out = m(x)
            print(out)
            # Tensor(shape=[3], dtype=float32, place=Place(gpu:0), stop_gradient=True,
            #        [2., 0., 0.])
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
    """

    def __init__(self, threshold=1.0, name=None):
        super(ThresholdedReLU, self).__init__()
        self._threshold = threshold
        self._name = name

    def forward(self, x):
        return F.thresholded_relu(x, self._threshold, self._name)

1117 1118 1119 1120
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'threshold={}{}'.format(self._threshold, name_str)

1121

Z
zhiboniu 已提交
1122
class Silu(Layer):
1123 1124 1125
    r"""
    Silu Activation

M
minghaoBD 已提交
1126 1127
    .. math::

1128 1129 1130
        silu(x) = \frac{x}{1 + \mathrm{e}^{-x}}

    Where :math:`x` is the input Tensor.
M
minghaoBD 已提交
1131 1132

    Parameters:
1133
        name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
M
minghaoBD 已提交
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160

    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.

    Examples:
        .. code-block:: python

            import paddle

            x = paddle.to_tensor([1.0, 2.0, 3.0, 4.0])
            m = paddle.nn.Silu()
            out = m(x) # [ 0.731059, 1.761594, 2.857722, 3.928055 ]
    """

    def __init__(self, name=None):
        super(Silu, self).__init__()
        self._name = name

    def forward(self, x):
        return F.silu(x, self._name)

    def extra_repr(self):
        name_str = 'name={}'.format(self._name) if self._name else ''
        return name_str


Z
zhiboniu 已提交
1161
class LogSigmoid(Layer):
1162
    r"""
1163
    LogSigmoid Activation.
1164

1165
    .. math::
1166

1167
        LogSigmoid(x) = log \frac{1}{1 + e^{-x}}
1168 1169 1170 1171 1172

    Parameters:
        x (Tensor): The input Tensor with data type float32, or float64.
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.
1173

1174 1175 1176
    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.
1177

1178 1179 1180
    Examples:
        .. code-block:: python

1181
            import paddle
1182

1183
            x = paddle.to_tensor([1.0, 2.0, 3.0, 4.0])
1184 1185
            m = paddle.nn.LogSigmoid()
            out = m(x) # [-0.313262 -0.126928 -0.0485874 -0.0181499]
1186 1187 1188 1189 1190 1191 1192
    """

    def __init__(self, name=None):
        super(LogSigmoid, self).__init__()
        self._name = name

    def forward(self, x):
1193
        return F.log_sigmoid(x, self._name)
1194

1195 1196 1197 1198
    def extra_repr(self):
        name_str = 'name={}'.format(self._name) if self._name else ''
        return name_str

1199

Z
zhiboniu 已提交
1200
class Softmax(Layer):
1201
    r"""
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
    Softmax Activation.

    This operator implements the softmax layer. The calculation process is as follows:

    1. The dimension :attr:`axis` of ``x`` will be permuted to the last.

    2. Then ``x`` will be logically flattened to a 2-D matrix. The matrix's second
    dimension(row length) is the same as the dimension :attr:`axis` of ``x``,
    and the first dimension(column length) is the product of all other dimensions
    of ``x``. For each row of the matrix, the softmax operator squashes the
    K-dimensional(K is the width of the matrix, which is also the size of ``x``'s
    dimension :attr:`axis`) vector of arbitrary real values to a K-dimensional
    vector of real values in the range [0, 1] that add up to 1.

    3. After the softmax operation is completed, the inverse operations of steps 1 and 2
    are performed to restore the two-dimensional matrix to the same dimension as the ``x`` .

    It computes the exponential of the given dimension and the sum of exponential
    values of all the other dimensions in the K-dimensional vector input.
    Then the ratio of the exponential of the given dimension and the sum of
    exponential values of all the other dimensions is the output of the softmax
    operator.

    For each row :math:`i` and each column :math:`j` in the matrix, we have:

    .. math::

1229
        Softmax[i, j] = \frac{\exp(x[i, j])}{\sum_j(exp(x[i, j])}
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294

    Example:

    .. code-block:: text

        Case 1:
          Input:
            x.shape = [2, 3, 4]
            x.data = [[[2.0, 3.0, 4.0, 5.0],
                       [3.0, 4.0, 5.0, 6.0],
                       [7.0, 8.0, 8.0, 9.0]],
                      [[1.0, 2.0, 3.0, 4.0],
                       [5.0, 6.0, 7.0, 8.0],
                       [6.0, 7.0, 8.0, 9.0]]]

          Attrs:
            axis = -1

          Output:
            out.shape = [2, 3, 4]
            out.data = [[[0.0320586 , 0.08714432, 0.23688282, 0.64391426],
                         [0.0320586 , 0.08714432, 0.23688282, 0.64391426],
                         [0.07232949, 0.19661193, 0.19661193, 0.53444665]],
                        [[0.0320586 , 0.08714432, 0.23688282, 0.64391426],
                         [0.0320586 , 0.08714432, 0.23688282, 0.64391426],
                         [0.0320586 , 0.08714432, 0.23688282, 0.64391426]]]

        Case 2:
          Input:
            x.shape = [2, 3, 4]
            x.data = [[[2.0, 3.0, 4.0, 5.0],
                       [3.0, 4.0, 5.0, 6.0],
                       [7.0, 8.0, 8.0, 9.0]],
                      [[1.0, 2.0, 3.0, 4.0],
                       [5.0, 6.0, 7.0, 8.0],
                       [6.0, 7.0, 8.0, 9.0]]]
          Attrs:
            axis = 1

          Output:
            out.shape = [2, 3, 4]
            out.data = [[[0.00657326, 0.00657326, 0.01714783, 0.01714783],
                         [0.01786798, 0.01786798, 0.04661262, 0.04661262],
                         [0.97555875, 0.97555875, 0.93623955, 0.93623955]],
                        [[0.00490169, 0.00490169, 0.00490169, 0.00490169],
                         [0.26762315, 0.26762315, 0.26762315, 0.26762315],
                         [0.72747516, 0.72747516, 0.72747516, 0.72747516]]]

    Parameters:
        axis (int, optional): The axis along which to perform log_softmax
            calculations. It should be in range [-D, D), where D is the
            dimensions of ``x`` . If ``axis`` < 0, it works the same way as
            :math:`axis + D` . Default is -1.
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.

    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.

    Examples:
        .. code-block:: python

            import paddle

1295
            x = paddle.to_tensor([[[2.0, 3.0, 4.0, 5.0],
1296 1297 1298 1299
                        [3.0, 4.0, 5.0, 6.0],
                        [7.0, 8.0, 8.0, 9.0]],
                        [[1.0, 2.0, 3.0, 4.0],
                        [5.0, 6.0, 7.0, 8.0],
1300
                        [6.0, 7.0, 8.0, 9.0]]], dtype='float32')
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
            m = paddle.nn.Softmax()
            out = m(x)
            # [[[0.0320586 , 0.08714432, 0.23688282, 0.64391426],
            #   [0.0320586 , 0.08714432, 0.23688282, 0.64391426],
            #   [0.07232949, 0.19661193, 0.19661193, 0.53444665]],
            # [[0.0320586 , 0.08714432, 0.23688282, 0.64391426],
            #   [0.0320586 , 0.08714432, 0.23688282, 0.64391426],
            #   [0.0320586 , 0.08714432, 0.23688282, 0.64391426]]]
    """

    def __init__(self, axis=-1, name=None):
        super(Softmax, self).__init__()
        self._axis = axis
        self._dtype = None
        self._name = name

    def forward(self, x):
        return F.softmax(x, self._axis, self._dtype, self._name)

1320 1321 1322 1323
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'axis={}{}'.format(self._axis, name_str)

1324

Z
zhiboniu 已提交
1325
class LogSoftmax(Layer):
1326
    r"""
1327 1328 1329 1330
    This operator implements the log_softmax layer. The calculation process is as follows:

    .. math::

1331 1332 1333 1334
        \begin{array} {rcl}
            Out[i, j] &= &log(softmax(x)) \\
            &= &log(\frac{\exp(X[i, j])}{\sum_j(\exp(X[i, j])})
        \end{array}
1335 1336

    Parameters:
1337 1338 1339 1340 1341 1342
        axis (int, optional): The axis along which to perform log_softmax
            calculations. It should be in range [-D, D), where D is the
            dimensions of the input Tensor . If ``axis`` < 0, it works the
            same way as :math:`axis + D` . Default is -1.
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.
1343

1344 1345 1346
    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.
1347 1348 1349 1350

    Examples:
        .. code-block:: python

1351 1352
            import paddle

Z
zhupengyang 已提交
1353 1354 1355 1356 1357 1358
            x = [[[-2.0, 3.0, -4.0, 5.0],
                  [3.0, -4.0, 5.0, -6.0],
                  [-7.0, -8.0, 8.0, 9.0]],
                 [[1.0, -2.0, -3.0, 4.0],
                  [-5.0, 6.0, 7.0, -8.0],
                  [6.0, 7.0, 8.0, 9.0]]]
1359 1360 1361 1362 1363 1364 1365 1366 1367
            m = paddle.nn.LogSoftmax()
            x = paddle.to_tensor(x)
            out = m(x)
            # [[[ -7.1278396   -2.1278396   -9.127839    -0.12783948]
            #   [ -2.1270514   -9.127051    -0.12705144 -11.127051  ]
            #   [-16.313261   -17.313261    -1.3132617   -0.31326184]]
            #  [[ -3.0518122   -6.051812    -7.051812    -0.051812  ]
            #   [-12.313267    -1.3132664   -0.3132665  -15.313267  ]
            #   [ -3.4401896   -2.4401896   -1.4401896   -0.44018966]]]
1368 1369
    """

1370
    def __init__(self, axis=-1, name=None):
1371 1372
        super(LogSoftmax, self).__init__()
        self._axis = axis
1373
        self._name = name
1374

1375 1376
    def forward(self, x):
        return F.log_softmax(x, self._axis)
1377

1378 1379 1380 1381
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'axis={}{}'.format(self._axis, name_str)

1382

Z
zhiboniu 已提交
1383
class Maxout(Layer):
1384
    r"""
1385
    Maxout Activation. Create a callable object of `Maxout`.
1386 1387 1388 1389 1390 1391 1392

    Assumed the input shape is (N, Ci, H, W).
    The output shape is (N, Co, H, W).
    Then Co = Ci/groups and the operator formula is as follows:

    .. math::

1393 1394 1395 1396 1397 1398 1399 1400
        \begin{array}{l}
            &out_{si+j} = \max_{k} x_{gsi + sk + j} \\
            &g = groups \\
            &s = \frac{input.size}{num\_channels} \\
            &0 \le i < \frac{num\_channels}{groups} \\
            &0 \le j < s \\
            &0 \le k < groups
        \end{array}
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443

    Parameters:
        groups (int, optional): The groups number of maxout. `groups` specifies the
            index of channel dimension where maxout will be performed. This must be
            a factor of number of features. Default is 1.
        axis (int, optional): The axis along which to perform maxout calculations.
            It should be 1 when data format is NCHW, be -1 or 3 when data format
            is NHWC. If ``axis`` < 0, it works the same way as :math:`axis + D` ,
            where D is the dimensions of ``x`` . Default is 1.
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.

    Shape:
        - input: :math:`(N, C_{in}, H_{in}, W_{in})`
        - output: :math:`(N, C_{out}, H_{out}, W_{out})`

    Examples:
        .. code-block:: python

            import paddle

            x = paddle.rand([1, 2, 3, 4])
            # [[[[0.5002636  0.22272532 0.17402348 0.2874594 ]
            #    [0.95313174 0.6228939  0.7129065  0.7087491 ]
            #    [0.02879342 0.88725346 0.61093384 0.38833922]]
            #   [[0.5231306  0.03807496 0.91661984 0.15602879]
            #    [0.666127   0.616567   0.30741522 0.24044901]
            #    [0.7142536  0.7351477  0.31588817 0.23782359]]]]
            m = paddle.nn.Maxout(groups=2)
            out = m(x)
            # [[[[0.5231306  0.22272532 0.91661984 0.2874594 ]
            #    [0.95313174 0.6228939  0.7129065  0.7087491 ]
            #    [0.7142536  0.88725346 0.61093384 0.38833922]]]]
    """

    def __init__(self, groups, axis=1, name=None):
        super(Maxout, self).__init__()
        self._groups = groups
        self._axis = axis
        self._name = name

    def forward(self, x):
        return F.maxout(x, self._groups, self._axis, self._name)
1444 1445 1446 1447

    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'groups={}, axis={}{}'.format(self._groups, self._axis, name_str)
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492


class Softmax2D(Layer):
    r"""
    Softmax2D Activation.
    Given a Tensor with shape (B, C, H, W) or (C, H, W), it will apply Softmax to each location (C, h_i, w_j).
    The sum of result in each location (C, H_i, W_j) will be one.

    Shape:
        - Input: :math:`(B, C, H, W)` or :math:`(C, H, W)`
        - Output: :math:`(B, C, H, W)` or :math:`(C, H, W)`(same as input)

    Return:
        A Tensor of the same shape and dtype as input with value in range [0, 1].

    Examples:
        .. code-block:: python

            import paddle

            x = paddle.rand([1, 2, 3, 4])
            # [[[[0.42496058 0.1172187  0.14664008 0.8151267 ]
            #    [0.24430142 0.42052492 0.60372984 0.79307914]
            #    [0.4539401  0.90458065 0.10235776 0.62009853]]

            #   [[0.11731581 0.16053623 0.05667042 0.91876775]
            #    [0.9413854  0.30770817 0.6788164  0.9543593 ]
            #    [0.4145064  0.75909156 0.11598814 0.73599935]]]]
            m = paddle.nn.Softmax2D()
            out = m(x)
            # [[[[0.5763103  0.48917228 0.5224772  0.4741129 ]
            #    [0.3324591  0.5281743  0.48123717 0.45976716]
            #    [0.5098571  0.5363083  0.49659243 0.4710572 ]]

            #   [[0.42368975 0.51082766 0.47752273 0.5258871 ]
            #    [0.66754097 0.47182566 0.5187628  0.5402329 ]
            #    [0.49014282 0.46369177 0.50340754 0.5289428 ]]]]
    """

    def __init__(self, name=None):
        super(Softmax2D, self).__init__()
        self._dtype = None
        self._name = name

    def forward(self, x):
1493 1494 1495 1496 1497
        assert (
            x.ndim == 3 or x.ndim == 4
        ), "Softmax2D requires a 3D or 4D tensor as input. Received: {}D.".format(
            x.ndim
        )
1498 1499 1500 1501 1502
        return F.softmax(x, axis=-3, dtype=self._dtype, name=self._name)

    def extra_repr(self):
        name_str = 'name={}'.format(self._name) if self._name else ''
        return name_str