-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
activation.py
1728 lines (1396 loc) · 56.8 KB
/
activation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
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
891
892
893
894
895
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
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
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
# 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.
import paddle
from paddle import _C_ops, _legacy_C_ops, in_dynamic_mode
from paddle.framework import core
from paddle.utils.inplace_utils import inplace_apis_in_dygraph_only
from ...fluid.data_feeder import check_dtype, check_variable_and_dtype
from ...fluid.framework import convert_np_dtype_to_dtype_
from ...fluid.layer_helper import LayerHelper
from ...tensor.manipulation import chunk
from ...tensor.math import tanh # noqa: F401
from ...tensor.math import tanh_ # noqa: F401
from ...tensor.ops import sigmoid # noqa: F401
__all__ = []
def celu(x, alpha=1.0, name=None):
r"""
celu activation.
Apply the following operation to each element of the input Tensor accroding to the `Continuously Differentiable Exponential Linear Units <https://arxiv.org/abs/1704.07483>`_.
.. math::
\operatorname{celu}(x) = \max(0, x) + \min(0, \alpha * (\mathrm{e}^{x/\alpha}-1))
Parameters:
x (Tensor): The input Tensor with data type float16, float32, or float64.
alpha (float, optional): The 'alpha' value of the CELU formula. Default is 1.0.
name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
Returns:
A ``Tensor`` with the same data type and shape as ``x`` .
Examples:
.. code-block:: python
import paddle
import paddle.nn.functional as F
x = paddle.to_tensor([[-1., 6.], [1., 15.6]])
out = F.celu(x, alpha=0.2)
# [[-0.19865242, 6. ],
# [ 1. , 15.60000038]]
"""
if alpha == 0:
raise ZeroDivisionError("alpha cannot be 0 for celu")
if in_dynamic_mode():
return _C_ops.celu(x, alpha)
else:
check_variable_and_dtype(
x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'celu'
)
helper = LayerHelper("celu", **locals())
out = helper.create_variable_for_type_inference(x.dtype)
helper.append_op(
type='celu',
inputs={'X': x},
outputs={'Out': out},
attrs={'alpha': alpha},
)
return out
def elu(x, alpha=1.0, name=None):
r"""
elu activation.
.. math::
elu(x)=
\left\{
\begin{array}{lcl}
x,& &\text{if } \ x > 0 \\
alpha * (e^{x} - 1),& &\text{if } \ x <= 0
\end{array}
\right.
Parameters:
x (Tensor): The input Tensor with data type float32, float64.
alpha (float, optional): The 'alpha' value of the ELU formulation. Default is 1.0.
name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
Returns:
A Tensor with the same data type and shape as ``x`` .
Examples:
.. code-block:: python
import paddle
import paddle.nn.functional as F
x = paddle.to_tensor([[-1., 6.], [1., 15.6]])
out = F.elu(x, alpha=0.2)
# [[-0.12642411 6. ]
# [ 1. 15.6 ]]
"""
if in_dynamic_mode():
return _C_ops.elu(x, alpha)
else:
check_variable_and_dtype(
x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'elu'
)
helper = LayerHelper("elu", **locals())
out = helper.create_variable_for_type_inference(x.dtype)
helper.append_op(
type='elu',
inputs={'X': x},
outputs={'Out': out},
attrs={'alpha': alpha},
)
return out
@inplace_apis_in_dygraph_only
def elu_(x, alpha=1.0, name=None):
r"""
Inplace version of ``elu`` API, the output Tensor will be inplaced with input ``x``.
Please refer to :ref:`api_nn_cn_elu`.
"""
assert alpha >= 0.0, "elu_ only support alpha >= 0, please use elu instead."
if in_dynamic_mode():
return _C_ops.elu_(x, alpha)
return _legacy_C_ops.elu_(x, 'alpha', alpha)
def gelu(x, approximate=False, name=None):
r"""
gelu activation.
The activation function of Gelu is calculated element by element. More information refers to :ref: `Gaussian Error Linear Units`.
if approximate is True
.. math::
gelu(x) = 0.5 * x * (1 + tanh(\sqrt{\frac{2}{\pi}} * (x + 0.044715x^{3})))
else
.. math::
gelu(x) = 0.5 * x * (1 + erf(\frac{x}{\sqrt{2}}))
Parameters:
x (Tensor): The input Tensor with data type float32, float64.
approximate (bool, optional): Whether to enable approximation. Default is False.
name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
Returns:
A Tensor with the same data type and shape as ``x`` .
Examples:
.. code-block:: python
import paddle
import paddle.nn.functional as F
x = paddle.to_tensor([[-1, 0.5], [1, 1.5]])
out1 = F.gelu(x)
# [[-0.15865529, 0.34573123],
# [ 0.84134471, 1.39978933]]
out2 = F.gelu(x, True)
# [[-0.15880799, 0.34571400],
# [ 0.84119201, 1.39957154]]
"""
if in_dynamic_mode():
return _C_ops.gelu(x, approximate)
else:
check_variable_and_dtype(
x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'gelu'
)
helper = LayerHelper("gelu", **locals())
out = helper.create_variable_for_type_inference(x.dtype)
helper.append_op(
type='gelu',
inputs={'X': x},
outputs={'Out': out},
attrs={'approximate': approximate},
)
return out
def hardshrink(x, threshold=0.5, name=None):
r"""
hard shrinkage activation
.. math::
hardshrink(x)=
\left\{
\begin{array}{rcl}
x,& &if \ {x > threshold} \\
x,& &if \ {x < -threshold} \\
0,& &if \ {others} &
\end{array}
\right.
Args:
x (Tensor): The input Tensor with data type float32, float64.
threshold (float, optional): The value of threshold for hardthrink. Default is 0.5.
name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
Returns:
A Tensor with the same data type and shape as ``x`` .
Examples:
.. code-block:: python
import paddle
import paddle.nn.functional as F
x = paddle.to_tensor([-1, 0.3, 2.5])
out = F.hardshrink(x) # [-1., 0., 2.5]
"""
if in_dynamic_mode():
return _C_ops.hardshrink(x, threshold)
else:
check_variable_and_dtype(
x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'hardshrink'
)
helper = LayerHelper('hardshrink', **locals())
out = helper.create_variable_for_type_inference(x.dtype)
helper.append_op(
type='hard_shrink',
inputs={'X': x},
outputs={'Out': out},
attrs={'threshold': threshold},
)
return out
def hardtanh(x, min=-1.0, max=1.0, name=None):
r"""
hardtanh activation. Calculate the `hardtanh` of input `x`.
.. math::
hardtanh(x)=
\left\{
\begin{array}{cll}
max,& & \text{if } x > max \\
min,& & \text{if } x < min \\
x,& & \text{otherwise}
\end{array}
\right.
Parameters:
x (Tensor): The input Tensor with data type float32, float64.
min (float, optional): The minimum value of the linear region range. Default is -1.
max (float, optional): The maximum value of the linear region range. Default is 1.
name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
Returns:
A Tensor with the same data type and shape as ``x`` .
Examples:
.. code-block:: python
import paddle
import paddle.nn.functional as F
x = paddle.to_tensor([-1.5, 0.3, 2.5])
out = F.hardtanh(x) # [-1., 0.3, 1.]
"""
if in_dynamic_mode():
return _C_ops.hardtanh(x, min, max)
else:
check_variable_and_dtype(
x, 'x', ['float16', 'float32', 'float64'], 'hardtanh'
)
helper = LayerHelper('hardtanh', **locals())
out = helper.create_variable_for_type_inference(dtype=x.dtype)
helper.append_op(
type='brelu',
inputs={'X': x},
outputs={'Out': out},
attrs={'t_min': min, 't_max': max},
)
return out
def hardsigmoid(x, slope=0.1666667, offset=0.5, name=None):
r"""
hardsigmoid activation. Calculate 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{array}{lcl}
0, & &\text{if } \ x \leq -3 \\
1, & &\text{if } \ x \geq 3 \\
slope * x + offset, & &\text{otherwise}
\end{array}
\right.
Parameters:
x (Tensor): The input Tensor with data type float32, float64.
slope (float, optional): The slope of hardsigmoid function. Default is 0.1666667.
offset (float, optional): The offset of hardsigmoid function. Default is 0.5.
name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
Returns:
A Tensor with the same data type and shape as ``x`` .
Examples:
.. code-block:: python
import paddle
import paddle.nn.functional as F
x = paddle.to_tensor([-4., 5., 1.])
out = F.hardsigmoid(x) # [0., 1., 0.666667]
"""
if in_dynamic_mode():
return _C_ops.hardsigmoid(x, slope, offset)
else:
check_variable_and_dtype(
x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'hardsigmoid'
)
helper = LayerHelper('hardsigmoid', **locals())
out = helper.create_variable_for_type_inference(x.dtype)
helper.append_op(
type='hard_sigmoid',
inputs={'X': x},
outputs={'Out': out},
attrs={'slope': slope, 'offset': offset},
)
return out
def hardswish(x, name=None):
r"""
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{array}{cll}
0 &, & \text{if } x \leq -3 \\
x &, & \text{if } x \geq 3 \\
\frac{x(x+3)}{6} &, & \text{otherwise}
\end{array}
\right.
Parameters:
x (Tensor): The input Tensor with data type float32, float64.
name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
Returns:
A Tensor with the same data type and shape as ``x`` .
Examples:
.. code-block:: python
import paddle
import paddle.nn.functional as F
x = paddle.to_tensor([-4., 5., 1.])
out = F.hardswish(x) # [0., 5., 0.666667]
"""
if in_dynamic_mode():
return _C_ops.hardswish(x)
else:
check_variable_and_dtype(
x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'hardswish'
)
threshold = 6.0
scale = 6.0
offset = 3.0
helper = LayerHelper('hardswish', **locals())
out = helper.create_variable_for_type_inference(x.dtype)
helper.append_op(
type='hard_swish',
inputs={'X': x},
outputs={'Out': out},
attrs={'threshold': threshold, 'scale': scale, 'offset': offset},
)
return out
def leaky_relu(x, negative_slope=0.01, name=None):
r"""
leaky_relu activation. The calculation formula is:
.. math::
leaky\_relu(x)=
\left\{
\begin{array}{rcl}
x, & & if \ x >= 0 \\
negative\_slope * x, & & otherwise \\
\end{array}
\right.
Args:
x (Tensor): The input Tensor with data type float32, float64.
negative_slope (float, optional): Slope of the activation function at
:math:`x < 0` . Default is 0.01.
name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
Returns:
A Tensor with the same data type and shape as ``x`` .
Examples:
.. code-block:: python
import paddle
import paddle.nn.functional as F
x = paddle.to_tensor([-2., 0., 1.])
out = F.leaky_relu(x)
print(out)
# [-0.02, 0., 1.]
"""
if in_dynamic_mode():
return _C_ops.leaky_relu(x, negative_slope)
else:
check_variable_and_dtype(
x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'leaky_relu'
)
helper = LayerHelper('leaky_relu', **locals())
out = helper.create_variable_for_type_inference(dtype=x.dtype)
helper.append_op(
type='leaky_relu',
inputs={'X': x},
outputs={'Out': out},
attrs={'alpha': negative_slope},
)
return out
def prelu(x, weight, data_format="NCHW", name=None):
"""
prelu activation. The calculation formula is follows:
.. math::
prelu(x) = max(0, x) + weight * min(0, x)
x and weight is input Tensor.
Parameters:
x (Tensor): The input Tensor with data type float32, float64.
weight (Tensor): The learnable parameter with data type same as ``x``.
The weight shape is [], [1] or [in], where `in` is the input channel of ``x``.
name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
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".
Returns:
A Tensor with the same data type and shape as ``x`` .
Examples:
.. code-block:: python
import paddle
import paddle.nn.functional as F
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]]]], dtype='float32')
w = paddle.to_tensor([0.25], dtype='float32')
out = F.prelu(data, w)
print(out)
# [[[[-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. ]]]]
"""
assert (
len(weight.shape) == 0 or len(weight.shape) == 1
), "The dim count of weight shape should be 0 or 1 in prelu()."
mode = 'all'
if len(weight.shape) == 1 and weight.shape[0] > 1:
true_data_format = [
'NC',
'NCL',
'NCHW',
'NCDHW',
'NLC',
'NHWC',
'NDHWC',
]
if data_format not in true_data_format:
raise ValueError(
"data_format must be one of 'NC', 'NCL', 'NCHW', 'NCDHW', "
"'NLC', 'NHWC', 'NDHWC' but receive {}".format(data_format)
)
data_format = 'NCHW' if data_format[1] == 'C' else 'NHWC'
assert (
len(x.shape) > 1
), "The dim count of x should be equal or larger than 2 in prelu() when weight shape is not [1]."
# NOTE(GuoxiaWang): support NHWC data format
if data_format == 'NHWC':
assert (
weight.shape[0] == x.shape[-1]
), "The weight size should be equal to x input channel in prelu() when weight shape is not [1]."
else:
assert (
weight.shape[0] == x.shape[1]
), "The weight size should be equal to x input channel in prelu() when weight shape is not [1]."
mode = 'channel'
if in_dynamic_mode():
return _C_ops.prelu(x, weight, data_format, mode)
else:
check_variable_and_dtype(
x, 'x', ['float16', 'float32', 'float64', 'uint16'], 'prelu'
)
check_variable_and_dtype(
weight,
'weight',
['float16', 'float32', 'float64', 'uint16'],
'prelu',
)
helper = LayerHelper('prelu', **locals())
out = helper.create_variable_for_type_inference(x.dtype)
helper.append_op(
type="prelu",
inputs={"X": x, "Alpha": weight},
outputs={"Out": out},
attrs={"mode": mode, "data_format": data_format},
)
return out
def rrelu(x, lower=1.0 / 8.0, upper=1.0 / 3.0, training=True, name=None):
r"""
rrelu activation.
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:
x (Tensor): The input Tensor with data type float16, float32, float64.
lower (float, optional): The lower bound of uniform distribution. Default: 0.125.
upper (float, optional): The upper bound of uniform distribution. Default: 0.3333333333333333.
training (bool, optional): Current mode is in training or others. Default is True.
name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
Returns:
A Tensor with the same data type and shape as ``x`` .
Examples:
.. code-block:: python
import paddle
import paddle.nn.functional as F
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')
out = F.rrelu(input_tensor, 0.1, 0.3)
print(out)
#[[[[-0.20000899 3. -0.8810822 5. ]
# [ 3. -0.55175185 5. -1.0776101 ]
# [-1.0680687 -1.9896201 8. 9. ]]
# [[ 1. -0.5238267 -0.65515125 4. ]
# [-1.3766339 6. 7. -2.3465784 ]
# [ 6. 7. 8. 9. ]]]]
"""
if not isinstance(lower, float) or not isinstance(upper, float):
raise TypeError(
"The lower and upper values must be float type. Received: lower {}, upper {}.".format(
lower, upper
)
)
if lower < 0 or lower > 1:
raise ValueError(
"The lower value must be no less than zero or greater than one. Received: {}.".format(
lower
)
)
if upper < lower:
raise ValueError(
"The upper value must be greater than lower value. Received: lower {}, upper {}.".format(
lower, upper
)
)
if upper > 1:
raise ValueError(
"The upper value must be no greater than one. Received: {}.".format(
upper
)
)
is_test = not training
if in_dynamic_mode():
return _C_ops.rrelu(x, lower, upper, is_test)
else:
check_variable_and_dtype(
x, 'X', ['float16', 'uint16', 'float32', 'float64'], 'rrelu'
)
helper = LayerHelper('rrelu', **locals())
out = helper.create_variable_for_type_inference(x.dtype)
noise = helper.create_variable_for_type_inference(dtype=x.dtype)
attrs = {'lower': lower, 'upper': upper, 'is_test': is_test}
helper.append_op(
type='rrelu',
inputs={"X": x},
outputs={"Out": out, "Noise": noise},
attrs=attrs,
)
return out
def relu(x, name=None):
"""
relu activation. The calculation formula is follows:
.. math::
out = max(x, 0)
x is input Tensor.
Parameters:
x (Tensor): The input Tensor with data type float32, float64.
name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
Returns:
A Tensor with the same data type and shape as ``x`` .
Examples:
.. code-block:: python
import paddle
import paddle.nn.functional as F
x = paddle.to_tensor([-2, 0, 1], dtype='float32')
out = F.relu(x)
print(out)
# [0., 0., 1.]
"""
if in_dynamic_mode():
return _C_ops.relu(x)
else:
check_variable_and_dtype(
x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'relu'
)
helper = LayerHelper('relu', **locals())
out = helper.create_variable_for_type_inference(x.dtype)
helper.append_op(type='relu', inputs={'X': x}, outputs={'Out': out})
return out
@inplace_apis_in_dygraph_only
def relu_(x, name=None):
"""
Inplace version of ``relu`` API, the output Tensor will be inplaced with input ``x``.
Please refer to :ref:`api_nn_cn_relu`.
"""
return _C_ops.relu_(x)
def log_sigmoid(x, name=None):
r"""
log_sigmoid activation.
.. math::
log\_sigmoid(x) = log \frac{1}{1 + e^{-x}}
Parameters:
x (Tensor): The input Tensor with data type float32, float64.
name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
Returns:
A Tensor with the same data type and shape as ``x`` .
Examples:
.. code-block:: python
import paddle
import paddle.nn.functional as F
x = paddle.to_tensor([1.0, 2.0, 3.0, 4.0])
out = F.log_sigmoid(x) # [-0.313262 -0.126928 -0.0485874 -0.0181499]
"""
if in_dynamic_mode():
return _C_ops.logsigmoid(x)
else:
check_variable_and_dtype(
x, 'x', ['float16', 'float32', 'float64'], 'log_sigmoid'
)
helper = LayerHelper("log_sigmoid", **locals())
out = helper.create_variable_for_type_inference(x.dtype)
helper.append_op(
type='logsigmoid', inputs={'X': x}, outputs={'Out': out}
)
return out
def maxout(x, groups, axis=1, name=None):
r"""
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::
\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}
Parameters:
x (Tensor): The input is 4-D Tensor with shape [N, C, H, W] or [N, H, W, C], the data type
of input is float16, float32 or float64.
groups (int): 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.
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`` . ``axis`` only supports 1, 3 or -1.
Default is 1.
name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
Returns:
A Tensor with the same data type as ``x`` .
Examples:
.. code-block:: python
import paddle
import paddle.nn.functional as F
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]]]]
out = F.maxout(x, groups=2)
# [[[[0.5231306 0.22272532 0.91661984 0.2874594 ]
# [0.95313174 0.6228939 0.7129065 0.7087491 ]
# [0.7142536 0.88725346 0.61093384 0.38833922]]]]
"""
if in_dynamic_mode():
return _C_ops.maxout(x, groups, axis)
else:
check_variable_and_dtype(
x, 'x', ['float16', 'float32', 'float64'], 'maxout'
)
if axis not in [1, -1, 3]:
raise ValueError(
"Attr(axis) should be 1 when data format is NCHW, -1 or 3 when data format is NHWC. Received "
"Attr(axis): %s." % str(axis)
)
if axis == -1:
axis = 3
helper = LayerHelper('maxout', **locals())
out = helper.create_variable_for_type_inference(x.dtype)
helper.append_op(
type='maxout',
inputs={'X': x},
outputs={'Out': out},
attrs={'groups': groups, 'axis': axis},
)
return out
def relu6(x, name=None):
"""
relu6 activation
.. math::
relu6(x) = min(max(0,x), 6)
Parameters:
x (Tensor): The input Tensor with data type float32, float64.
name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
Returns:
A Tensor with the same data type and shape as ``x`` .
Examples:
.. code-block:: python
import paddle
import paddle.nn.functional as F
x = paddle.to_tensor([-1, 0.3, 6.5])
out = F.relu6(x)
print(out)
# [0, 0.3, 6]
"""
threshold = 6.0
if in_dynamic_mode():
return _C_ops.relu6(x)
check_variable_and_dtype(
x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'relu6'
)
helper = LayerHelper('relu6', **locals())
out = helper.create_variable_for_type_inference(x.dtype)
helper.append_op(
type='relu6',
inputs={'X': x},
outputs={'Out': out},
attrs={'threshold': threshold},
)
return out
def selu(
x,
scale=1.0507009873554804934193349852946,
alpha=1.6732632423543772848170429916717,
name=None,
):
r"""
selu activation
.. math::
selu(x)= scale *
\left\{
\begin{array}{lcl}
x,& &\text{if } \ x > 0 \\
alpha * e^{x} - alpha,& &\text{if } \ x <= 0
\end{array}
\right.
Parameters:
x (Tensor): The input Tensor with data type float32, float64.
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.
name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
Returns:
A Tensor with the same data type and shape as ``x`` .
Examples:
.. code-block:: python
import paddle
import paddle.nn.functional as F
x = paddle.to_tensor([[0.0, 1.0],[2.0, 3.0]])
out = F.selu(x)
print(out)
# [[0, 1.050701],[2.101402, 3.152103]]
"""
if scale <= 1.0:
raise ValueError(
f"The scale must be greater than 1.0. Received: {scale}."
)
if alpha < 0:
raise ValueError(
f"The alpha must be no less than zero. Received: {alpha}."
)
if in_dynamic_mode():
return _C_ops.selu(x, scale, alpha)
else:
check_variable_and_dtype(
x, 'x', ['float16', 'float32', 'float64'], 'selu'
)
helper = LayerHelper('selu', **locals())
out = helper.create_variable_for_type_inference(x.dtype)
helper.append_op(
type='selu',
inputs={'X': x},
outputs={'Out': out},
attrs={'scale': scale, 'alpha': alpha},
)
return out
def silu(x, name=None):
r"""
silu activation
.. math::
silu(x) = \frac{x}{1 + e^{-x}}
Where :math:`x` is the input Tensor.
Parameters:
x (Tensor): The input Tensor with data type bfloat16, float16, float32, float64.
name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
Returns:
A Tensor with the same data type and shape as :attr:`x`.
Examples:
.. code-block:: python
import paddle
import paddle.nn.functional as F
x = paddle.to_tensor([1.0, 2.0, 3.0, 4.0])
out = F.silu(x) # [ 0.731059, 1.761594, 2.857722, 3.928055 ]
"""
if in_dynamic_mode():
return _C_ops.silu(x)
else:
check_variable_and_dtype(
x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'silu'
)
helper = LayerHelper("silu", **locals())
out = helper.create_variable_for_type_inference(x.dtype)
helper.append_op(type='silu', inputs={'X': x}, outputs={'Out': out})
return out