activation.py 36.6 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

17 18 19
from ...fluid.dygraph import layers
from ...fluid import core
from ...fluid.framework import in_dygraph_mode
20 21
from ...fluid.param_attr import ParamAttr
from ...fluid.initializer import Constant
Q
Qi Li 已提交
22
from paddle.framework import get_default_dtype
23
from .. import functional as F
24 25


26
class ELU(layers.Layer):
27
    r"""
28 29
    ELU Activation.

30
    .. math::
31

32 33 34 35 36 37
        ELU(x) = max(0, x) + min(0, \\alpha * (e^{x}-1))

    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`.
38

39 40 41
    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.
42

43 44 45
    Examples:
        .. code-block:: python

46
            import paddle
47

Z
zhupengyang 已提交
48
            x = paddle.to_tensor([[-1. ,6.], [1., 15.6]])
49 50 51 52
            m = paddle.nn.ELU(0.2)
            out = m(x)
            # [[-0.12642411  6.        ]
            #  [ 1.          15.6      ]]
53 54 55 56 57 58 59 60 61 62
    """

    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)

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

67 68

class GELU(layers.Layer):
69
    r"""
70 71 72 73
    GELU Activation.

    If approximate is True

74
    .. math::
75 76 77 78 79

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

    else

80
    .. math::
81 82 83 84 85 86 87

        GELU(x) = 0.5 * x * (1 + erf(\\frac{x}{\\sqrt{2}}))

    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`.
88

89 90 91
    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.
92

93 94 95
    Examples:
        .. code-block:: python

96 97
            import paddle
            import numpy as np
98

99
            x = paddle.to_tensor(np.array([[-1, 0.5],[1, 1.5]]))
100

101 102
            m = paddle.nn.GELU()
            out = m(x) # [-0.158655 0.345731 0.841345 1.39979]
103

104 105
            m = paddle.nn.GELU(True)
            out = m(x) # [-0.158808 0.345714 0.841192 1.39957]
106 107 108 109 110 111 112 113 114 115
    """

    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)

116 117 118 119
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'approximate={}{}'.format(self._approximate, name_str)

120

121
class Hardshrink(layers.Layer):
122
    r"""
123 124 125 126 127
    Hardshrink Activation

    .. math::

        hardshrink(x)=
128 129 130 131 132 133 134
            \\left\\{
            \\begin{aligned}
            &x, & & if \\ x > threshold \\\\
            &x, & & if \\ x < -threshold \\\\
            &0, & & if \\ others
            \\end{aligned}
            \\right.
135 136 137 138 139 140 141 142 143 144 145 146 147 148

    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

149
            import paddle
150

Z
zhupengyang 已提交
151
            x = paddle.to_tensor([-1, 0.3, 2.5])
152 153
            m = paddle.nn.Hardshrink()
            out = m(x) # [-1., 0., 2.5]
154 155 156 157 158 159 160 161
    """

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

    def forward(self, x):
162
        return F.hardshrink(x, self._threshold, self._name)
163

164 165 166 167
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'threshold={}{}'.format(self._threshold, name_str)

168

169
class Hardswish(layers.Layer):
170
    r"""
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
    Hardswish activation

    Hardswish is proposed in MobileNetV3, and performs better in computational stability
    and efficiency compared to swish function. For more details please refer
    to: https://arxiv.org/pdf/1905.02244.pdf

    .. math::

        Hardswish(x)=
            \\left\\{
            \\begin{aligned}
            &0, & & \\text{if } x \\leq -3 \\\\
            &x, & & \\text{if } x \\geq 3 \\\\
            &\\frac{x(x+3)}{6}, & & \\text{otherwise}
            \\end{aligned}
            \\right.

    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)

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

218

W
WangXi 已提交
219
class Tanh(layers.Layer):
220
    r"""
W
WangXi 已提交
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
    Tanh Activation.

    .. math::
        Tanh(x) = \\frac{e^{x} - e^{-x}}{e^{x} + e^{-x}}

    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
            import numpy as np

            x = paddle.to_tensor(np.array([-0.4, -0.2, 0.1, 0.3]))
            m = paddle.nn.Tanh()
            out = m(x)
W
WangXi 已提交
244
            print(out)
W
WangXi 已提交
245 246 247 248 249 250 251 252 253 254
            # [-0.37994896 -0.19737532  0.09966799  0.29131261]
    """

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

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

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

W
WangXi 已提交
259

260
class Hardtanh(layers.Layer):
261
    r"""
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
    Hardtanh Activation

    .. math::

        Hardtanh(x)= \\begin{cases}
                        max, \\text{if } x > max \\\\
                        min, \\text{if } x < min \\\\
                        x,  \\text{otherwise}
                      \\end{cases}

    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`.
277

278 279 280
    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.
281

282 283 284 285 286
    Examples:
        .. code-block:: python

            import paddle

Z
zhupengyang 已提交
287
            x = paddle.to_tensor([-1.5, 0.3, 2.5])
288
            m = paddle.nn.Hardtanh()
Z
zhupengyang 已提交
289
            out = m(x) # [-1., 0.3, 1.]
290 291 292 293 294 295 296 297 298 299 300
    """

    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)

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

305 306 307 308 309 310 311 312 313 314 315

class PReLU(layers.Layer):
    """
    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:
316
            1 - a single parameter `alpha` is used for all input channels;
317 318 319
            Number of channels - a seperate `alpha` is used for each input channel.
            Default is 1.
        init (float, optional): Init value of learnable `weight`. Default is 0.25.
320
        weight_attr(ParamAttr, optional): The parameter attribute for the learnable `weight`.
321
            Default is None. For more information, please refer to :ref:`api_paddle_ParamAttr`.
322 323
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.
324

325
    Shape:
Q
Qi Li 已提交
326
        - input: Tensor with any shape. Default dtype is float32.
327
        - output: Tensor with the same shape as input.
328

329 330 331 332 333 334
    Examples:
        .. code-block:: python

            import paddle
            import numpy as np

Q
Qi Li 已提交
335
            paddle.set_default_dtype("float64")
336 337 338 339 340 341

            data = np.array([[[[-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],
Q
Qi Li 已提交
342
                            [ 6.0,  7.0,  8.0,  9.0]]]], 'float64')
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
            x = paddle.to_tensor(data)
            m = paddle.nn.PReLU(1, 0.25)
            out = m(x)
            # [[[[-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.  ]]]]
    """

    def __init__(self, num_parameters=1, init=0.25, weight_attr=None,
                 name=None):
        super(PReLU, self).__init__()
        self._num_parameters = num_parameters
        self._init = init
        self._weight_attr = weight_attr
        self._name = name

        self._weight = self.create_parameter(
            attr=self._weight_attr,
Q
Qi Li 已提交
364 365
            shape=[self._num_parameters],
            dtype=get_default_dtype(),
366
            is_bias=False,
Q
Qi Li 已提交
367
            default_initializer=Constant(self._init))
368 369 370 371

    def forward(self, x):
        return F.prelu(x, self._weight)

372 373 374 375 376
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'num_parameters={}, init={}, dtype={}{}'.format(
            self._num_parameters, self._init, self._dtype, name_str)

377

378 379 380 381
class ReLU(layers.Layer):
    """
    ReLU Activation.

382
    .. math::
383

384
        ReLU(x) = max(x, 0)
385 386

    Parameters:
387 388 389 390 391 392
        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.
393

394 395 396
    Examples:
        .. code-block:: python

397
            import paddle
398

Z
zhupengyang 已提交
399
            x = paddle.to_tensor([-2., 0., 1.])
400 401
            m = paddle.nn.ReLU()
            out = m(x) # [0., 0., 1.]
402 403
    """

404
    def __init__(self, name=None):
405
        super(ReLU, self).__init__()
406
        self._name = name
407

408 409
    def forward(self, x):
        return F.relu(x, self._name)
410

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

415

416 417 418 419 420 421
class ReLU6(layers.Layer):
    """
    ReLU6 Activation

    .. math::

422
        ReLU6(x) = min(max(0,x), 6)
423 424 425 426 427 428 429 430 431 432 433 434

    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

435 436
            import paddle
            import numpy as np
437

438 439 440
            x = paddle.to_tensor(np.array([-1, 0.3, 6.5]))
            m = paddle.nn.ReLU6()
            out = m(x) # [0, 0.3, 6]
441 442 443 444 445 446 447 448 449
    """

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

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

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

454 455

class SELU(layers.Layer):
456
    r"""
457 458 459 460
    SELU Activation

    .. math::

461 462 463 464 465
        SELU(x)= scale *
                 \\begin{cases}
                   x, \\text{if } x > 0 \\\\
                   alpha * e^{x} - alpha, \\text{if } x <= 0
                 \\end{cases}
466 467

    Parameters:
468 469
        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
470 471 472 473 474 475 476 477 478 479
        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

480 481
            import paddle
            import numpy as np
482

483
            x = paddle.to_tensor(np.array([[0.0, 1.0],[2.0, 3.0]]))
484 485
            m = paddle.nn.SELU()
            out = m(x) # [[0, 1.050701],[2.101402, 3.152103]]
486 487 488 489 490 491 492 493 494 495 496 497 498 499
    """

    def __init__(self,
                 scale=1.0507009873554804934193349852946,
                 alpha=1.6732632423543772848170429916717,
                 name=None):
        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)

500 501 502 503 504
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'scale={:.16f}, alpha={:.16f}{}'.format(self._scale, self._alpha,
                                                       name_str)

505

C
ceci3 已提交
506
class LeakyReLU(layers.Layer):
507
    r"""
C
ceci3 已提交
508 509
    Leaky ReLU Activation.

510
    .. math::
C
ceci3 已提交
511

512
        LeakyReLU(x)=
513 514 515 516 517 518
            \\left\\{
            \\begin{aligned}
            &x, & & if \\ x >= 0 \\\\
            &negative\_slope * x, & & otherwise \\\\
            \\end{aligned}
            \\right. \\\\
C
ceci3 已提交
519 520

    Parameters:
521 522
        negative_slope (float, optional): Slope of the activation function at
            :math:`x < 0` . Default is 0.01.
523 524
        name (str, optional): Name for the operation (optional, default is None).
            For more information, please refer to :ref:`api_guide_Name`.
525

526 527 528
    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.
529

C
ceci3 已提交
530 531 532
    Examples:
        .. code-block:: python

533
            import paddle
C
Chen Long 已提交
534
            import numpy as np
535

536
            m = paddle.nn.LeakyReLU()
Z
zhupengyang 已提交
537
            x = paddle.to_tensor(np.array([-2, 0, 1], 'float32'))
538
            out = m(x)  # [-0.02, 0., 1.]
C
ceci3 已提交
539 540
    """

541
    def __init__(self, negative_slope=0.01, name=None):
C
ceci3 已提交
542
        super(LeakyReLU, self).__init__()
543
        self._negative_slope = negative_slope
544
        self._name = name
C
ceci3 已提交
545

546
    def forward(self, x):
547
        return F.leaky_relu(x, self._negative_slope, self._name)
C
ceci3 已提交
548

549 550 551 552
    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 已提交
553

554 555
class Sigmoid(layers.Layer):
    """
556
    this interface is used to construct a callable object of the ``Sigmoid`` class. This layer calcluate the `sigmoid` of input x.
557

558
    .. math::
S
swtkiwi 已提交
559

560
        Sigmoid(x) = \\frac{1}{1 + e^{-x}}
561

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

565 566
    Shape:
        x: N-D tensor, available dtype is float16, float32, float64.
567 568

    Returns:
569
        A callable object of Sigmoid.
570

571
    Examples:
572

573 574
        .. code-block:: python

575 576 577
          import paddle

          m = paddle.nn.Sigmoid()
578 579
          x = paddle.to_tensor([1.0, 2.0, 3.0, 4.0])
          out = m(x) # [0.7310586, 0.880797, 0.95257413, 0.98201376]
580 581
    """

582
    def __init__(self, name=None):
583
        super(Sigmoid, self).__init__()
584
        self.name = name
585

586 587
    def forward(self, x):
        return F.sigmoid(x, self.name)
588

589 590 591 592
    def extra_repr(self):
        name_str = 'name={}'.format(self.name) if self.name else ''
        return name_str

593

594
class Hardsigmoid(layers.Layer):
595
    r"""
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
    This interface is used to construct a callable object of the ``Hardsigmoid`` class.
    This layer calcluate the `hardsigmoid` of input x.

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

    .. math::

        Hardsigmoid(x)=
            \\left\\{
            \\begin{aligned}
            &0, & & \\text{if } x \\leq -3 \\\\
            &1, & & \\text{if } x \\geq 3 \\\\
            &x/6 + 1/2, & & \\text{otherwise}
            \\end{aligned}
            \\right.

    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 已提交
628
          m = paddle.nn.Hardsigmoid()
629 630 631 632 633 634 635 636 637
          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):
638
        return F.hardsigmoid(x, name=self.name)
639

640 641 642 643
    def extra_repr(self):
        name_str = 'name={}'.format(self.name) if self.name else ''
        return name_str

644

645
class Softplus(layers.Layer):
646
    r"""
647 648 649 650
    Softplus Activation

    .. math::

651 652
        Softplus(x) = \\frac{1}{beta} * \\log(1 + e^{beta * x}) \\\\
        \\text{For numerical stability, the implementation reverts to the linear function when: beta * x > threshold.}
653 654

    Parameters:
655 656
        beta (float, optional): The value of beta for Softplus. Default is 1
        threshold (float, optional): The value of threshold for Softplus. Default is 20
657 658 659 660 661 662 663 664 665 666
        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

667 668
            import paddle
            import numpy as np
669

670 671 672
            x = paddle.to_tensor(np.array([-0.4, -0.2, 0.1, 0.3]))
            m = paddle.nn.Softplus()
            out = m(x) # [0.513015, 0.598139, 0.744397, 0.854355]
673 674 675 676 677 678 679 680 681 682 683
    """

    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)

684 685 686 687 688
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'beta={}, threshold={}{}'.format(self._beta, self._threshold,
                                                name_str)

689 690

class Softshrink(layers.Layer):
691
    r"""
692 693 694 695
    Softshrink Activation

    .. math::

696 697 698 699 700
        Softshrink(x)= \\begin{cases}
                        x - threshold, \\text{if } x > threshold \\\\
                        x + threshold, \\text{if } x < -threshold \\\\
                        0,  \\text{otherwise}
                      \\end{cases}
701 702

    Parameters:
703
        threshold (float, optional): The value of threshold(must be no less than zero) for softplus. Default is 0.5
704 705 706 707 708 709 710 711 712 713
        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

714 715
            import paddle
            import numpy as np
716

717 718 719
            x = paddle.to_tensor(np.array([-0.9, -0.2, 0.1, 0.8]))
            m = paddle.nn.Softshrink()
            out = m(x) # [-0.4, 0, 0, 0.3]
720 721 722 723 724 725 726 727 728 729
    """

    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)

730 731 732 733
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'threshold={}{}'.format(self._threshold, name_str)

734 735

class Softsign(layers.Layer):
736
    r"""
737 738 739 740
    Softsign Activation

    .. math::

741
        Softsign(x) = \\frac{x}{1 + |x|}
742 743 744 745 746 747 748 749 750 751 752 753

    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

754 755
            import paddle
            import numpy as np
756

757 758 759
            x = paddle.to_tensor(np.array([-0.4, -0.2, 0.1, 0.3]))
            m = paddle.nn.Softsign()
            out = m(x) # [-0.285714, -0.166667, 0.0909091, 0.230769]
760 761 762 763 764 765 766 767 768
    """

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

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

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

773

774
class Swish(layers.Layer):
775
    r"""
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
    Swish Activation.

    .. math::

        Swish(x) = \\frac{x}{1 + e^{-x}}

    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
            import numpy as np

            x = paddle.to_tensor(np.array([-2., 0., 1.]))
            m = paddle.nn.Swish()
            out = m(x) # [-0.238406, 0., 0.731059]
    """

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

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

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

812

813 814 815 816 817 818
class Tanhshrink(layers.Layer):
    """
    Tanhshrink Activation

    .. math::

819
        Tanhshrink(x) = x - tanh(x)
820 821 822 823 824 825 826 827 828 829 830 831

    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

832 833
            import paddle
            import numpy as np
834

835 836 837
            x = paddle.to_tensor(np.array([-0.4, -0.2, 0.1, 0.3]))
            m = paddle.nn.Tanhshrink()
            out = m(x) # [-0.020051, -0.00262468, 0.000332005, 0.00868739]
838 839 840 841 842 843 844 845 846
    """

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

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

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

851

852
class ThresholdedReLU(layers.Layer):
853
    r"""
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
    Thresholded ReLU Activation

    .. math::

        ThresholdedReLU(x) = \\begin{cases}
                               x, \\text{if } x > threshold \\\\
                               0, \\text{otherwise}
                              \\end{cases}

    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
            import numpy as np

            x = paddle.to_tensor(np.array([2., 0., 1.]))
            m = paddle.nn.ThresholdedReLU()
            out = m(x) # [2., 0., 0.]
    """

    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)

891 892 893 894
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'threshold={}{}'.format(self._threshold, name_str)

895

M
minghaoBD 已提交
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
class Silu(layers.Layer):
    """
    Silu Activation.
    .. math::

        Silu(x) = \frac{x}{1 + e^{-x}}

    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`.

    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


934
class LogSigmoid(layers.Layer):
935
    r"""
936
    LogSigmoid Activation.
937

938
    .. math::
939

940
        LogSigmoid(x) = log \\frac{1}{1 + e^{-x}}
941 942 943 944 945

    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`.
946

947 948 949
    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.
950

951 952 953
    Examples:
        .. code-block:: python

954
            import paddle
955

956
            x = paddle.to_tensor([1.0, 2.0, 3.0, 4.0])
957 958
            m = paddle.nn.LogSigmoid()
            out = m(x) # [-0.313262 -0.126928 -0.0485874 -0.0181499]
959 960 961 962 963 964 965
    """

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

    def forward(self, x):
966
        return F.log_sigmoid(x, self._name)
967

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

972

973
class Softmax(layers.Layer):
974
    r"""
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
    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::

        Softmax[i, j] = \\frac{\\exp(x[i, j])}{\\sum_j(exp(x[i, j])}

    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
            import numpy as np

            x = np.array([[[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]]], 'float32')
            x = paddle.to_tensor(x)
            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)

1095 1096 1097 1098
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'axis={}{}'.format(self._axis, name_str)

1099

1100
class LogSoftmax(layers.Layer):
1101
    r"""
1102 1103 1104 1105
    This operator implements the log_softmax layer. The calculation process is as follows:

    .. math::

Z
zhupengyang 已提交
1106 1107 1108 1109
        \\begin{aligned} 
        Out[i, j] &= log(softmax(x)) \\\\
        &= log(\\frac{\\exp(X[i, j])}{\\sum_j(\\exp(X[i, j])})
        \\end{aligned}
1110 1111

    Parameters:
1112 1113 1114 1115 1116 1117
        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`.
1118

1119 1120 1121
    Shape:
        - input: Tensor with any shape.
        - output: Tensor with the same shape as input.
1122 1123 1124 1125

    Examples:
        .. code-block:: python

1126 1127
            import paddle

Z
zhupengyang 已提交
1128 1129 1130 1131 1132 1133
            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]]]
1134 1135 1136 1137 1138 1139 1140 1141 1142
            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]]]
1143 1144
    """

1145
    def __init__(self, axis=-1, name=None):
1146 1147
        super(LogSoftmax, self).__init__()
        self._axis = axis
1148
        self._name = name
1149

1150 1151
    def forward(self, x):
        return F.log_softmax(x, self._axis)
1152

1153 1154 1155 1156
    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'axis={}{}'.format(self._axis, name_str)

1157 1158

class Maxout(layers.Layer):
1159
    r"""
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
    Maxout Activation.

    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::

        &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

    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)
1217 1218 1219 1220

    def extra_repr(self):
        name_str = ', name={}'.format(self._name) if self._name else ''
        return 'groups={}, axis={}{}'.format(self._groups, self._axis, name_str)