-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtarget_file.py
10613 lines (8492 loc) · 402 KB
/
target_file.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) 2021 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 numbers
import numpy as np
import paddle
from paddle.distribution import distribution
from paddle.fluid import framework
class Cauchy(distribution.Distribution):
r"""Cauchy distribution is also called Cauchy–Lorentz distribution. It is a continuous probability distribution named after Augustin-Louis Cauchy and Hendrik Lorentz. It has a very wide range of applications in natural sciences.
The Cauchy distribution has the probability density function (PDF):
.. math::
{ f(x; loc, scale) = \frac{1}{\pi scale \left[1 + \left(\frac{x - loc}{ scale}\right)^2\right]} = { 1 \over \pi } \left[ { scale \over (x - loc)^2 + scale^2 } \right], }
Args:
loc (float|Tensor): Location of the peak of the distribution. The data type is float32 or float64.
scale (float|Tensor): The half-width at half-maximum (HWHM). The data type is float32 or float64. Must be positive values.
name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
Examples:
.. code-block:: python
>>> import paddle
>>> from paddle.distribution import Cauchy
>>> # init Cauchy with float
>>> rv = Cauchy(loc=0.1, scale=1.2)
>>> for i in range(3):
... print(i)
... print(i)
... print(i)
... for j in range(3):
... print(j)
...
>>> print(rv.entropy())
>>> # Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
>>> # 2.71334577)
>>> # init Cauchy with N-Dim tensor
>>> rv = Cauchy(loc=paddle.to_tensor(0.1), scale=paddle.to_tensor([1.0, 2.0]))
>>> print(rv.entropy())
>>> # Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
>>> # [2.53102422, 3.22417140])
"""
def __init__(self, loc, scale, name=None):
self.name = name if name is not None else 'Cauchy'
if not isinstance(loc, (numbers.Real, framework.Variable)):
raise TypeError(
f"Expected type of loc is Real|Variable, but got {type(loc)}"
)
if not isinstance(scale, (numbers.Real, framework.Variable)):
raise TypeError(
f"Expected type of scale is Real|Variable, but got {type(scale)}"
)
if isinstance(loc, numbers.Real):
loc = paddle.full(shape=(), fill_value=loc)
if isinstance(scale, numbers.Real):
scale = paddle.full(shape=(), fill_value=scale)
if loc.shape != scale.shape:
self.loc, self.scale = paddle.broadcast_tensors([loc, scale])
else:
self.loc, self.scale = loc, scale
self.dtype = self.loc.dtype
super().__init__(batch_shape=self.loc.shape, event_shape=())
@property
def mean(self):
"""Mean of Cauchy distribution."""
raise ValueError("Cauchy distribution has no mean.")
@property
def variance(self):
"""Variance of Cauchy distribution."""
raise ValueError("Cauchy distribution has no variance.")
@property
def stddev(self):
"""Standard Deviation of Cauchy distribution."""
raise ValueError("Cauchy distribution has no stddev.")
def sample(self, shape, name=None):
"""Sample from Cauchy distribution.
Note:
`sample` method has no grad, if you want so, please use `rsample` instead.
Args:
shape (Sequence[int]): Sample shape.
name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
Returns:
Tensor: Sampled data with shape `sample_shape` + `batch_shape` + `event_shape`.
Examples:
.. code-block:: python
>>> import paddle
>>> from paddle.distribution import Cauchy
>>> # init Cauchy with float
>>> rv = Cauchy(loc=0.1, scale=1.2)
>>> print(rv.sample([10]).shape)
>>> # [10]
blablablablablablablablablablablablablablablablablablablablablabla
blablablablablablablablablablablabla
blablablablablablablablablablablablablablablablablablablablablablablablablablablabla...
.. code-block:: python
>>> import paddle
>>> from paddle.distribution import Cauchy
>>> # init Cauchy with float
>>> rv = Cauchy(loc=0.1, scale=1.2)
>>> print(rv.sample([10]).shape)
>>> # [10]
"""
name = name if name is not None else (self.name + '_sample')
with paddle.no_grad():
return self.rsample(shape, name)
def rsample(self, shape, name=None):
"""Sample from Cauchy distribution (reparameterized).
Args:
shape (Sequence[int]): Sample shape.
name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
Returns:
Tensor: Sampled data with shape `sample_shape` + `batch_shape` + `event_shape`.
Examples:
.. code-block:: python
>>> import paddle
>>> from paddle.distribution import Cauchy
>>> # init Cauchy with float
>>> rv = Cauchy(loc=0.1, scale=1.2)
>>> print(rv.rsample([10]).shape)
>>> # [10]
>>> # init Cauchy with 0-Dim tensor
>>> rv = Cauchy(loc=paddle.full((), 0.1), scale=paddle.full((), 1.2))
>>> print(rv.rsample([10]).shape)
>>> # [10]
>>> # init Cauchy with N-Dim tensor
>>> rv = Cauchy(loc=paddle.to_tensor(0.1), scale=paddle.to_tensor([1.0, 2.0]))
>>> print(rv.rsample([10]).shape)
>>> # [10, 2]
>>> # sample 2-Dim data
>>> rv = Cauchy(loc=0.1, scale=1.2)
>>> print(rv.rsample([10, 2]).shape)
>>> # [10, 2]
>>> rv = Cauchy(loc=paddle.to_tensor(0.1), scale=paddle.to_tensor([1.0, 2.0]))
>>> print(rv.rsample([10, 2]).shape)
>>> # [10, 2, 2]
"""
name = name if name is not None else (self.name + '_rsample')
if not isinstance(shape, (np.ndarray, framework.Variable, list, tuple)):
raise TypeError(
f"Expected type of shape is Sequence[int], but got {type(shape)}"
)
shape = shape if isinstance(shape, tuple) else tuple(shape)
shape = self._extend_shape(shape)
loc = self.loc.expand(shape)
scale = self.scale.expand(shape)
uniforms = paddle.rand(shape, dtype=self.dtype)
return paddle.add(
loc,
paddle.multiply(scale, paddle.tan(np.pi * (uniforms - 0.5))),
name=name,
)
def prob(self, value):
r"""Probability density function(PDF) evaluated at value.
.. math::
{ f(x; loc, scale) = \frac{1}{\pi scale \left[1 + \left(\frac{x - loc}{ scale}\right)^2\right]} = { 1 \over \pi } \left[ { scale \over (x - loc)^2 + scale^2 } \right], }
Args:
value (Tensor): Value to be evaluated.
Returns:
Tensor: PDF evaluated at value.
Examples:
.. code-block:: python
>>> import paddle
>>> from paddle.distribution import Cauchy
>>> # init Cauchy with float
>>> rv = Cauchy(loc=0.1, scale=1.2)
>>> print(rv.prob(paddle.to_tensor(1.5)))
>>> # Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
>>> # 0.11234467)
>>> # broadcast to value
>>> rv = Cauchy(loc=0.1, scale=1.2)
>>> print(rv.prob(paddle.to_tensor([1.5, 5.1])))
>>> # Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
>>> # [0.11234467, 0.01444674])
>>> # init Cauchy with N-Dim tensor
>>> rv = Cauchy(loc=paddle.to_tensor([0.1, 0.1]), scale=paddle.to_tensor([1.0, 2.0]))
>>> print(rv.prob(paddle.to_tensor([1.5, 5.1])))
>>> # Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
>>> # [0.10753712, 0.02195240])
>>> # init Cauchy with N-Dim tensor with broadcast
>>> rv = Cauchy(loc=paddle.to_tensor(0.1), scale=paddle.to_tensor([1.0, 2.0]))
>>> print(rv.prob(paddle.to_tensor([1.5, 5.1])))
>>> # Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
>>> # [0.10753712, 0.02195240])
"""
name = self.name + '_prob'
if not isinstance(value, framework.Variable):
raise TypeError(
f"Expected type of value is Variable, but got {type(value)}"
)
return self.log_prob(value).exp(name=name)
def log_prob(self, value):
"""Log of probability densitiy function.
Args:
value (Tensor): Value to be evaluated.
Returns:
Tensor: Log of probability densitiy evaluated at value.
Examples:
.. code-block:: python
>>> import paddle
>>> from paddle.distribution import Cauchy
>>> # init Cauchy with float
>>> rv = Cauchy(loc=0.1, scale=1.2)
>>> print(rv.log_prob(paddle.to_tensor(1.5)))
>>> # Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
>>> # -2.18618369)
>>> # broadcast to value
>>> rv = Cauchy(loc=0.1, scale=1.2)
>>> print(rv.log_prob(paddle.to_tensor([1.5, 5.1])))
>>> # Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
>>> # [-2.18618369, -4.23728657])
>>> # init Cauchy with N-Dim tensor
>>> rv = Cauchy(loc=paddle.to_tensor([0.1, 0.1]), scale=paddle.to_tensor([1.0, 2.0]))
>>> print(rv.log_prob(paddle.to_tensor([1.5, 5.1])))
>>> # Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
>>> # [-2.22991920, -3.81887865])
>>> # init Cauchy with N-Dim tensor with broadcast
>>> rv = Cauchy(loc=paddle.to_tensor(0.1), scale=paddle.to_tensor([1.0, 2.0]))
>>> print(rv.log_prob(paddle.to_tensor([1.5, 5.1])))
>>> # Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
>>> # [-2.22991920, -3.81887865])
"""
name = self.name + '_log_prob'
if not isinstance(value, framework.Variable):
raise TypeError(
f"Expected type of value is Variable, but got {type(value)}"
)
value = self._check_values_dtype_in_probs(self.loc, value)
loc, scale, value = paddle.broadcast_tensors(
[self.loc, self.scale, value]
)
return paddle.subtract(
-(
paddle.square(paddle.divide(paddle.subtract(value, loc), scale))
).log1p(),
paddle.add(
paddle.full(loc.shape, np.log(np.pi), dtype=self.dtype),
scale.log(),
),
name=name,
)
def cdf(self, value):
r"""Cumulative distribution function(CDF) evaluated at value.
.. math::
{ \frac{1}{\pi} \arctan\left(\frac{x-loc}{ scale}\right)+\frac{1}{2}\! }
Args:
value (Tensor): Value to be evaluated.
Returns:
Tensor: CDF evaluated at value.
Examples:
.. code-block:: python
>>> import paddle
>>> from paddle.distribution import Cauchy
>>> # init Cauchy with float
>>> rv = Cauchy(loc=0.1, scale=1.2)
>>> print(rv.cdf(paddle.to_tensor(1.5)))
>>> # Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
>>> # 0.77443725)
>>> # broadcast to value
>>> rv = Cauchy(loc=0.1, scale=1.2)
>>> print(rv.cdf(paddle.to_tensor([1.5, 5.1])))
>>> # Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
>>> # [0.77443725, 0.92502367])
>>> # init Cauchy with N-Dim tensor
>>> rv = Cauchy(loc=paddle.to_tensor([0.1, 0.1]), scale=paddle.to_tensor([1.0, 2.0]))
>>> print(rv.cdf(paddle.to_tensor([1.5, 5.1])))
>>> # Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
>>> # [0.80256844, 0.87888104])
>>> # init Cauchy with N-Dim tensor with broadcast
>>> rv = Cauchy(loc=paddle.to_tensor(0.1), scale=paddle.to_tensor([1.0, 2.0]))
>>> print(rv.cdf(paddle.to_tensor([1.5, 5.1])))
>>> # Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
>>> # [0.80256844, 0.87888104])
"""
name = self.name + '_cdf'
if not isinstance(value, framework.Variable):
raise TypeError(
f"Expected type of value is Variable, but got {type(value)}"
)
value = self._check_values_dtype_in_probs(self.loc, value)
loc, scale, value = paddle.broadcast_tensors(
[self.loc, self.scale, value]
)
return (
paddle.atan(
paddle.divide(paddle.subtract(value, loc), scale), name=name
)
/ np.pi
+ 0.5
)
def entropy(self):
r"""Entropy of Cauchy distribution.
.. math::
{ \log(4\pi scale)\! }
Returns:
Tensor: Entropy of distribution.
Examples:
.. code-block:: python
>>> import paddle
>>> from paddle.distribution import Cauchy
Examples:
.. code-block:: python
:name: sdfasdf-dfa-1
>>> import paddle
>>> from paddle.distribution import Cauchy
>>> # init Cauchy with float
>>> rv = Cauchy(loc=0.1, scale=1.2)
>>> print(rv.entropy())
>>> # Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
>>> # 2.71334577)
>>> # init Cauchy with N-Dim tensor
>>> rv = Cauchy(loc=paddle.to_tensor(0.1), scale=paddle.to_tensor([1.0, 2.0]))
>>> print(rv.entropy())
>>> # Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
>>> # [2.53102422, 3.22417140])
.. code-block:: python
:name: sdfasdf-dfa-1
>>> import paddle
>>> from paddle.distribution import Cauchy
>>> # init Cauchy with float
>>> rv = Cauchy(loc=0.1, scale=1.2)
>>> print(rv.entropy())
>>> # Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
>>> # 2.71334577)
>>> # init Cauchy with N-Dim tensor
>>> rv = Cauchy(loc=paddle.to_tensor(0.1), scale=paddle.to_tensor([1.0, 2.0]))
>>> print(rv.entropy())
>>> # Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
>>> # [2.53102422, 3.22417140])
"""
name = self.name + '_entropy'
return paddle.add(
paddle.full(self.loc.shape, np.log(4 * np.pi), dtype=self.dtype),
self.scale.log(),
name=name,
)
def kl_divergence(self, other):
"""The KL-divergence between two Cauchy distributions.
Note:
[1] Frédéric Chyzak, Frank Nielsen, A closed-form formula for the Kullback-Leibler divergence between Cauchy distributions, 2019
Args:
other (Cauchy): instance of Cauchy.
Returns:
Tensor: kl-divergence between two Cauchy distributions.
Examples:
.. code-block:: python
>>> import paddle
>>> from paddle.distribution import Cauchy
>>> rv = Cauchy(loc=0.1, scale=1.2)
>>> rv_other = Cauchy(loc=paddle.to_tensor(1.2), scale=paddle.to_tensor([2.3, 3.4]))
>>> print(rv.kl_divergence(rv_other))
>>> # Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
>>> # [0.19819736, 0.31532931])
"""
name = self.name + '_kl_divergence'
if not isinstance(other, Cauchy):
raise TypeError(
f"Expected type of other is Cauchy, but got {type(other)}"
)
a_loc = self.loc
b_loc = other.loc
a_scale = self.scale
b_scale = other.scale
t1 = paddle.add(
paddle.pow(paddle.add(a_scale, b_scale), 2),
paddle.pow(paddle.subtract(a_loc, b_loc), 2),
).log()
t2 = (4 * paddle.multiply(a_scale, b_scale)).log()
return paddle.subtract(t1, t2, name=name)
# 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.
"""
math functions
"""
# TODO: define math functions
import numpy as np
import paddle
from paddle import _C_ops, _legacy_C_ops
from paddle.common_ops_import import VarDesc, dygraph_only, dygraph_utils
# TODO: define math functions
from paddle.utils.inplace_utils import inplace_apis_in_dygraph_only
from ..common_ops_import import Variable
from ..fluid.data_feeder import (
check_dtype,
check_type,
check_variable_and_dtype,
convert_dtype,
)
from ..framework import (
LayerHelper,
_dygraph_tracer,
convert_np_dtype_to_dtype_,
core,
in_dynamic_mode,
)
from .creation import _complex_to_real_dtype
from .layer_function_generator import generate_layer_fn, templatedoc
from .manipulation import cast
from .ops import abs # noqa: F401
from .ops import acos # noqa: F401
from .ops import acosh # noqa: F401
from .ops import asin # noqa: F401
from .ops import asinh # noqa: F401
from .ops import atan # noqa: F401
from .ops import atanh # noqa: F401
from .ops import ceil # noqa: F401
from .ops import ceil_ # noqa: F401
from .ops import cos # noqa: F401
from .ops import cosh # noqa: F401
from .ops import erf # noqa: F401
from .ops import exp # noqa: F401
from .ops import exp_ # noqa: F401
from .ops import expm1 # noqa: F401
from .ops import floor # noqa: F401
from .ops import floor_ # noqa: F401
from .ops import reciprocal # noqa: F401
from .ops import reciprocal_ # noqa: F401
from .ops import round # noqa: F401
from .ops import round_ # noqa: F401
from .ops import rsqrt # noqa: F401
from .ops import rsqrt_ # noqa: F401
from .ops import sigmoid # noqa: F401
from .ops import sigmoid_ # noqa: F401
from .ops import sin # noqa: F401
from .ops import sinh # noqa: F401
from .ops import sqrt # noqa: F401
from .ops import sqrt_ # noqa: F401
from .ops import square # noqa: F401
from .ops import tan # noqa: F401
__all__ = []
_supported_int_dtype_ = [
VarDesc.VarType.UINT8,
VarDesc.VarType.INT8,
VarDesc.VarType.INT16,
VarDesc.VarType.INT32,
VarDesc.VarType.INT64,
]
_supported_float_dtype_ = [
VarDesc.VarType.FP32,
VarDesc.VarType.FP64,
]
def _get_reduce_axis(axis, x):
"""
Internal function for max, min, amax and amin.
It computes the attribute reduce_all value based on axis.
"""
if axis is not None and not isinstance(axis, list):
if isinstance(axis, (tuple, range)):
axis = list(axis)
elif isinstance(axis, int):
axis = [axis]
else:
raise TypeError(
"The type of axis must be int, list or tuple, but received {}".format(
type(axis)
)
)
if axis is None:
axis = []
if axis == [] or len(axis) == len(x.shape):
reduce_all = True
else:
reduce_all = False
return reduce_all, axis
def _get_reduce_axis_with_tensor(axis, x):
if isinstance(axis, Variable):
if axis.shape[0] == len(x.shape):
reduce_all = True
else:
reduce_all = False
else:
reduce_all, axis = _get_reduce_axis(axis, x)
if paddle.utils._contain_var(axis):
axis = paddle.utils._convert_to_tensor_list(axis)
return reduce_all, axis
def log(x, name=None):
r"""
Calculates the natural log of the given input Tensor, element-wise.
.. math::
Out = \ln(x)
Args:
x (Tensor): Input Tensor. Must be one of the following types: int32, int64, float16, bfloat16, float32, float64.
name (str|None): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`
Returns:
Tensor: The natural log of the input Tensor computed element-wise.
Examples:
.. code-block:: python
>>> import paddle
>>> x = [[2,3,4], [7,8,9]]
>>> x = paddle.to_tensor(x, dtype='float32')
>>> res = paddle.log(x)
>>> # [[0.693147, 1.09861, 1.38629], [1.94591, 2.07944, 2.19722]]
"""
if in_dynamic_mode():
return _C_ops.log(x)
else:
check_variable_and_dtype(
x,
'x',
['int32', 'int64', 'uint16', 'float16', 'float32', 'float64'],
"log",
)
inputs = {'X': [x]}
helper = LayerHelper('log', **locals())
dtype = helper.input_dtype(input_param_name='x')
out = helper.create_variable_for_type_inference(dtype)
helper.append_op(type="log", inputs={"X": x}, outputs={"Out": out})
return out
def scale(x, scale=1.0, bias=0.0, bias_after_scale=True, act=None, name=None):
"""
Scale operator.
Putting scale and bias to the input Tensor as following:
``bias_after_scale`` is True:
.. math::
Out=scale*X+bias
``bias_after_scale`` is False:
.. math::
Out=scale*(X+bias)
Args:
x (Tensor): Input N-D Tensor of scale operator. Data type can be float32, float64, int8, int16, int32, int64, uint8.
scale (float|Tensor): The scale factor of the input, it should be a float number or a 0-D Tensor with shape [] and data type as float32.
bias (float): The bias to be put on the input.
bias_after_scale (bool): Apply bias addition after or before scaling. It is useful for numeric stability in some circumstances.
act (str, optional): Activation applied to the output such as tanh, softmax, sigmoid, relu.
name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
Returns:
Tensor: Output Tensor of scale operator, with shape and data type same as input.
Examples:
.. code-block:: python
>>> # scale as a float32 number
>>> import paddle
>>> data = paddle.randn(shape=[2,3], dtype='float32')
>>> res = paddle.scale(data, scale=2.0, bias=1.0)
.. code-block:: python
>>> # scale with parameter scale as a Tensor
>>> import paddle
>>> data = paddle.randn(shape=[2, 3], dtype='float32')
>>> factor = paddle.to_tensor([2], dtype='float32')
>>> res = paddle.scale(data, scale=factor, bias=1.0)
"""
if in_dynamic_mode():
if act is None:
return _C_ops.scale(x, scale, float(bias), bias_after_scale)
out = _C_ops.scale(x, scale, float(bias), bias_after_scale)
return dygraph_utils._append_activation_in_dygraph(out, act)
else:
check_variable_and_dtype(
x,
"x",
[
'float16',
'uint16',
'float32',
'float64',
'int8',
'int16',
'int32',
'int64',
'uint8',
],
"scale",
)
inputs = {'X': [x]}
attrs = {
'bias': float(bias),
'bias_after_scale': bias_after_scale,
}
if isinstance(scale, Variable):
inputs['ScaleTensor'] = [scale]
else:
attrs['scale'] = float(scale)
helper = LayerHelper('scale', **locals())
out = helper.create_variable_for_type_inference(dtype=x.dtype)
helper.append_op(
type='scale', inputs=inputs, outputs={'Out': out}, attrs=attrs
)
return helper.append_activation(out)
def stanh(x, scale_a=0.67, scale_b=1.7159, name=None):
r"""
stanh activation.
.. math::
out = b * \frac{e^{a * x} - e^{-a * x}}{e^{a * x} + e^{-a * x}}
Parameters:
x (Tensor): The input Tensor with data type float32, float64.
scale_a (float, optional): The scale factor a of the input. Default is 0.67.
scale_b (float, optional): The scale factor b of the output. Default is 1.7159.
name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
Returns:
A Tensor with the same data type and shape as ``x`` .
Examples:
.. code-block:: python
>>> import paddle
>>> x = paddle.to_tensor([1.0, 2.0, 3.0, 4.0])
>>> out = paddle.stanh(x, scale_a=0.67, scale_b=1.72) # [1.00616539, 1.49927628, 1.65933108, 1.70390463]
"""
if in_dynamic_mode():
return _C_ops.stanh(x, scale_a, scale_b)
else:
check_variable_and_dtype(
x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'stanh'
)
helper = LayerHelper('stanh', **locals())
out = helper.create_variable_for_type_inference(dtype=x.dtype)
helper.append_op(
type='stanh',
inputs={'X': x},
outputs={'Out': out},
attrs={'scale_a': scale_a, 'scale_b': scale_b},
)
return out
def multiplex(inputs, index, name=None):
"""
Based on the given index parameter, the OP selects a specific row from each input Tensor to construct the output Tensor.
If the input of this OP contains :math:`m` Tensors, where :math:`I_{i}` means the i-th input Tensor, :math:`i` between :math:`[0,m)` .
And :math:`O` means the output, where :math:`O[i]` means the i-th row of the output, then the output satisfies that :math:`O[i] = I_{index[i]}[i]` .
For Example:
.. code-block:: text
Given:
inputs = [[[0,0,3,4], [0,1,3,4], [0,2,4,4], [0,3,3,4]],
[[1,0,3,4], [1,1,7,8], [1,2,4,2], [1,3,3,4]],
[[2,0,3,4], [2,1,7,8], [2,2,4,2], [2,3,3,4]],
[[3,0,3,4], [3,1,7,8], [3,2,4,2], [3,3,3,4]]]
index = [[3],[0],[1],[2]]
out = [[3,0,3,4], # out[0] = inputs[index[0]][0] = inputs[3][0] = [3,0,3,4]
[0,1,3,4], # out[1] = inputs[index[1]][1] = inputs[0][1] = [0,1,3,4]
[1,2,4,2], # out[2] = inputs[index[2]][2] = inputs[1][2] = [1,2,4,2]
[2,3,3,4]] # out[3] = inputs[index[3]][3] = inputs[2][3] = [2,3,3,4]
Args:
inputs (list): The input Tensor list. The list elements are N-D Tensors of data types float32, float64, int32, int64. All input Tensor shapes should be the same and rank must be at least 2.
index (Tensor): Used to select some rows in the input Tensor to construct an index of the output Tensor. It is a 2-D Tensor with data type int32 or int64 and shape [M, 1], where M is the number of input Tensors.
name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
Returns:
Tensor: Output of multiplex OP, with data type being float32, float64, int32, int64.
Examples:
.. code-block:: python
>>> import paddle
>>> img1 = paddle.to_tensor([[1, 2], [3, 4]], dtype=paddle.float32)
>>> img2 = paddle.to_tensor([[5, 6], [7, 8]], dtype=paddle.float32)
>>> inputs = [img1, img2]
>>> index = paddle.to_tensor([[1], [0]], dtype=paddle.int32)
>>> res = paddle.multiplex(inputs, index)
>>> print(res) # Tensor([[5., 6.], [3., 4.]], dtype=float32)
"""
if in_dynamic_mode():
return _C_ops.multiplex(inputs, index)
else:
helper = LayerHelper('multiplex', **locals())
check_type(inputs, 'inputs', (list), 'multiplex')
if len(inputs) < 2:
raise ValueError(
"inputs should be a list object with at least 2 elements."
)
for id, x in enumerate(inputs):
check_variable_and_dtype(
x,
'input[' + str(id) + ']',
['float32', 'float64', 'int32', 'int64'],
'multiplex',
)
check_variable_and_dtype(
index, "index", ['int32', 'int64'], 'multiplex'
)
out = helper.create_variable_for_type_inference(inputs[0].dtype)
helper.append_op(
type='multiplex',
inputs={'X': inputs, 'Ids': index},
outputs={'Out': [out]},
)
return out
@inplace_apis_in_dygraph_only
def scale_(x, scale=1.0, bias=0.0, bias_after_scale=True, act=None, name=None):
"""
Inplace version of ``scale`` API, the output Tensor will be inplaced with input ``x``.
Please refer to :ref:`api_tensor_scale`.
"""
if in_dynamic_mode():
return _C_ops.scale_(x, scale, float(bias), bias_after_scale)
def pow(x, y, name=None):
"""
Compute the power of Tensor elements. The equation is:
.. math::
out = x^{y}
Note:
``paddle.pow`` supports broadcasting. If you want know more about broadcasting, please refer to `Introduction to Tensor`_ .
.. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensors
Args:
x (Tensor): An N-D Tensor, the data type is float16, float32, float64, int32 or int64.
y (float|int|Tensor): If it is an N-D Tensor, its data type should be the same as `x`.
name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
Returns:
N-D Tensor. A location into which the result is stored. Its dimension and data type are the same as `x`.
Examples:
.. code-block:: python
>>> import paddle
>>> x = paddle.to_tensor([1, 2, 3], dtype='float32')
>>> # example 1: y is a float or int
>>> res = paddle.pow(x, 2)
>>> print(res)
>>> # Tensor(shape=[3], dtype=float32, place=CUDAPlace(0), stop_gradient=True,
>>> # [1., 4., 9.])
>>> res = paddle.pow(x, 2.5)
>>> print(res)
>>> # Tensor(shape=[3], dtype=float32, place=CUDAPlace(0), stop_gradient=True,
>>> # [1. , 5.65685415 , 15.58845711])
>>> # example 2: y is a Tensor
>>> y = paddle.to_tensor([2], dtype='float32')
>>> res = paddle.pow(x, y)
>>> print(res)
>>> # Tensor(shape=[3], dtype=float32, place=CUDAPlace(0), stop_gradient=True,
>>> # [1., 4., 9.])
"""
# in dynamic graph mode
if in_dynamic_mode():
if isinstance(y, (int, float)):
return _C_ops.pow(x, y)
elif isinstance(y, (paddle.Tensor, Variable)):
return _C_ops.elementwise_pow(x, y)
else:
raise TypeError(
'y must be scalar or tensor type, but received: %s ' % (y.dtype)
)
else:
# in static graph mode
if isinstance(y, (int, float)):
helper = LayerHelper('pow', **locals())
inputs = {'X': x}
attrs = {'factor': y}
out = helper.create_variable_for_type_inference(dtype=x.dtype)
helper.append_op(
type='pow', inputs=inputs, outputs={'Out': out}, attrs=attrs
)
return out
elif isinstance(y, (paddle.Tensor, Variable)):
# TODO A potential speed improvement is supporting different types in C++ and removing the cast ops here
helper = LayerHelper('elementwise_pow', **locals())
out = helper.create_variable_for_type_inference(dtype=x.dtype)
return _elementwise_op(LayerHelper('elementwise_pow', **locals()))
else:
raise TypeError(
'y must be scalar or tensor type, but received: %s ' % (type(y))
)
@inplace_apis_in_dygraph_only
def pow_(x, y, name=None):
"""
Inplace version of ``pow`` API, the output Tensor will be inplaced with input ``x``.
Please refer to :ref:`api_paddle_pow`.
"""
if isinstance(y, (int, float)):
return _C_ops.pow_(x, y)
elif isinstance(y, (paddle.Tensor, Variable)):
return _C_ops.elementwise_pow_(x, y)
else:
raise TypeError(
'y must be scalar or tensor type, but received: %s ' % (type(y))
)
OP_NAMEMAPPING = {
'elementwise_max': 'maximum',
'elementwise_min': 'minimum',
'elementwise_pow': 'elementwise_pow',
'elementwise_floordiv': 'floor_divide',
'elementwise_add': 'add',
'elementwise_sub': 'subtract',
'elementwise_mul': 'multiply',
'elementwise_div': 'divide',
'elementwise_mod': 'remainder',