-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
random.py
1926 lines (1691 loc) · 75.3 KB
/
random.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.
# TODO: define random functions
from __future__ import annotations
from typing import TYPE_CHECKING
import paddle
from paddle import _C_ops, _legacy_C_ops
from paddle.base.framework import _current_expected_place
from paddle.base.libpaddle import DataType
from paddle.common_ops_import import Variable
from paddle.framework import (
in_dynamic_mode,
in_dynamic_or_pir_mode,
in_pir_mode,
use_pir_api,
)
from ..base.data_feeder import (
check_dtype,
check_shape,
check_type,
check_variable_and_dtype,
)
from ..framework import (
LayerHelper,
convert_np_dtype_to_dtype_,
core,
dygraph_only,
)
if TYPE_CHECKING:
from paddle import Tensor
from paddle._typing import DTypeLike, ShapeLike
__all__ = []
def bernoulli(x: Tensor, name: str | None = None) -> Tensor:
r"""
For each element :math:`x_i` in input ``x``, take a sample from the Bernoulli distribution, also called two-point distribution, with success probability :math:`x_i`. The Bernoulli distribution with success probability :math:`x_i` is a discrete probability distribution with probability mass function
.. math::
p(y)=\begin{cases}
x_i,&y=1\\
1-x_i,&y=0
\end{cases}.
Args:
x (Tensor): The input Tensor, it's data type should be float32, float64.
name (str|None, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
Returns:
Tensor, A Tensor filled samples from Bernoulli distribution, whose shape and dtype are same as ``x``.
Examples:
.. code-block:: python
>>> import paddle
>>> paddle.set_device('cpu') # on CPU device
>>> paddle.seed(100)
>>> x = paddle.rand([2,3])
>>> print(x)
>>> # doctest: +SKIP("Random output")
Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
[[0.55355281, 0.20714243, 0.01162981],
[0.51577556, 0.36369765, 0.26091650]])
>>> # doctest: -SKIP
>>> out = paddle.bernoulli(x)
>>> print(out)
>>> # doctest: +SKIP("Random output")
Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
[[1., 0., 1.],
[0., 1., 0.]])
>>> # doctest: -SKIP
"""
if in_dynamic_or_pir_mode():
return _C_ops.bernoulli(x)
else:
check_variable_and_dtype(
x, "x", ["float32", "float64", "float16", "uint16"], "bernoulli"
)
helper = LayerHelper("randint", **locals())
out = helper.create_variable_for_type_inference(
dtype=x.dtype
) # maybe set out to int32 ?
helper.append_op(
type='bernoulli', inputs={"X": x}, outputs={'Out': out}, attrs={}
)
out.stop_gradient = True
return out
@dygraph_only
def bernoulli_(
x: Tensor, p: float | Tensor = 0.5, name: str | None = None
) -> Tensor:
"""
This is the inplace version of api ``bernoulli``, which returns a Tensor filled
with random values sampled from a bernoulli distribution. The output Tensor will
be inplaced with input ``x``. Please refer to :ref:`api_paddle_bernoulli`.
Args:
x(Tensor): The input tensor to be filled with random values.
p (float|Tensor, optional): The success probability parameter of the output Tensor's bernoulli distribution.
If ``p`` is float, all elements of the output Tensor shared the same success probability.
If ``p`` is a Tensor, it has per-element success probabilities, and the shape should be broadcastable to ``x``.
Default is 0.5
name(str|None, optional): 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, A Tensor filled with random values sampled from the bernoulli distribution with success probability ``p`` .
Examples:
.. code-block:: python
>>> import paddle
>>> paddle.set_device('cpu')
>>> paddle.seed(200)
>>> x = paddle.randn([3, 4])
>>> x.bernoulli_()
>>> print(x)
Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
[[0., 1., 0., 1.],
[1., 1., 0., 1.],
[0., 1., 0., 0.]])
>>> x = paddle.randn([3, 4])
>>> p = paddle.randn([3, 1])
>>> x.bernoulli_(p)
>>> print(x)
Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
[[1., 1., 1., 1.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
"""
x.uniform_(0.0, 1.0)
ones_mask = x > p
zeros_mask = x < p
x.masked_fill_(ones_mask, 1.0)
x.masked_fill_(zeros_mask, 0.0)
return x
def binomial(count: Tensor, prob: Tensor, name: str | None = None) -> Tensor:
r"""
Returns a tensor filled with random number from the Binomial Distribution, which supports Tensor shape
broadcasting. The returned Tensor's data type is int64.
.. math::
out_i \sim Binomial (n = count_i, p = prob_i)
Args:
count(Tensor): A tensor with each element specifying the size of a binomial distribution. The input
data type should be int32 or int64.
prob(Tensor): A tensor with each element specifying the probability of success in the binomial experiment.
The input data type should be bfloat16, float16, float32, float64.
name(str|None, optional): 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, A Tensor filled with binomial random values with the same shape as the broadcasted Tensors of
``count`` and ``prob``. The data type is int64.
Examples:
.. code-block:: python
>>> import paddle
>>> paddle.set_device('cpu')
>>> paddle.seed(100)
>>> n = paddle.to_tensor([10.0, 50.0])
>>> p = paddle.to_tensor([0.2, 0.6])
>>> out = paddle.binomial(n, p)
>>> print(out)
>>> # doctest: +SKIP("Random output")
Tensor(shape=[2], dtype=int64, place=Place(cpu), stop_gradient=True,
[1 , 31])
>>> # doctest: -SKIP
"""
if in_dynamic_or_pir_mode():
count, prob = paddle.broadcast_tensors(
[paddle.cast(count, dtype=prob.dtype), prob]
)
return _C_ops.binomial(count, prob)
else:
check_variable_and_dtype(count, "count", ["int32", "int64"], "binomial")
check_variable_and_dtype(
prob,
"prob",
["bfloat16", "float16", "float32", "float64"],
"binomial",
)
count, prob = paddle.broadcast_tensors(
[paddle.cast(count, dtype=prob.dtype), prob]
)
helper = LayerHelper("binomial", **locals())
out = helper.create_variable_for_type_inference(
dtype=convert_np_dtype_to_dtype_('int64')
)
helper.append_op(
type='binomial',
inputs={"count": count, "prob": prob},
outputs={'out': out},
attrs={},
)
out.stop_gradient = True
return out
def poisson(x: Tensor, name: str | None = None) -> Tensor:
r"""
Returns a tensor filled with random number from a Poisson Distribution.
.. math::
out_i \sim Poisson (lambda = x_i)
Args:
x(Tensor): A tensor with rate parameter of poisson Distribution. The data type
should be bfloat16, float16, float32, float64.
name(str|None, optional): 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, A Tensor filled with random number with the same shape and dtype as ``x``.
Examples:
.. code-block:: python
>>> import paddle
>>> paddle.set_device('cpu')
>>> paddle.seed(100)
>>> x = paddle.uniform([2,3], min=1.0, max=5.0)
>>> out = paddle.poisson(x)
>>> print(out)
>>> # doctest: +SKIP("Random output")
Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
[[2., 5., 0.],
[5., 1., 3.]])
>>> # doctest: -SKIP
"""
if in_dynamic_or_pir_mode():
return _C_ops.poisson(x)
else:
check_variable_and_dtype(x, "x", ["float32", "float64"], "poisson")
helper = LayerHelper("poisson", **locals())
out = helper.create_variable_for_type_inference(dtype=x.dtype)
helper.append_op(
type='poisson', inputs={'X': x}, outputs={'Out': out}, attrs={}
)
return out
def standard_gamma(x: Tensor, name: str | None = None) -> Tensor:
r"""
Returns a tensor filled with random number from a Standard Gamma Distribution.
.. math::
out_i \sim Gamma (alpha = x_i, beta = 1.0)
Args:
x(Tensor): A tensor with rate parameter of standard gamma Distribution. The data type
should be bfloat16, float16, float32, float64.
name(str|None, optional): 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, A Tensor filled with random number with the same shape and dtype as ``x``.
Examples:
.. code-block:: python
>>> import paddle
>>> paddle.set_device('cpu')
>>> paddle.seed(100)
>>> x = paddle.uniform([2,3], min=1.0, max=5.0)
>>> out = paddle.standard_gamma(x)
>>> print(out)
>>> # doctest: +SKIP("Random output")
Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
[[3.35393834, 0.80538225, 0.36511323],
[6.10344696, 4.28612375, 6.37196636]])
>>> # doctest: -SKIP
"""
if in_dynamic_or_pir_mode():
return _C_ops.standard_gamma(x)
else:
check_variable_and_dtype(
x, "x", ["float32", "float64"], "standard_gamma"
)
helper = LayerHelper("standard_gamma", **locals())
out = helper.create_variable_for_type_inference(dtype=x.dtype)
helper.append_op(
type='standard_gamma',
inputs={'x': x},
outputs={'out': out},
attrs={},
)
return out
def log_normal(
mean: float | Tensor = 1.0,
std: float | Tensor = 2.0,
shape: ShapeLike | None = None,
name: str | None = None,
) -> Tensor:
r"""
Returns a Tensor filled with random values sampled from a Log Normal
Distribution, with ``mean``, ``std``.
The Log Normal Distribution is defined as follows
.. math::
f(x) = \frac{1}{x\sigma\sqrt{2\pi}}e^{-\frac{(\ln{x}-\mu)^2}{2\sigma^2}}
Args:
mean (float|Tensor, optional): The mean of the output Tensor's underlying normal distribution.
If ``mean`` is float, all elements of the output Tensor share the same mean.
If ``mean`` is a Tensor(data type supports float32, float64), it has per-element means.
Default is 1.0
std (float|Tensor, optional): The standard deviation of the output Tensor's underlying normal distribution.
If ``std`` is float, all elements of the output Tensor share the same standard deviation.
If ``std`` is a Tensor(data type supports float32, float64), it has per-element standard deviations.
Defaule is 2.0
shape (tuple|list|Tensor|None, optional): Shape of the Tensor to be created. The data type is ``int32`` or ``int64`` .
If ``shape`` is a list or tuple, each element of it should be integer or 0-D Tensor with shape [].
If ``shape`` is an Tensor, it should be an 1-D Tensor which represents a list. If ``mean`` or ``std``
is a Tensor, the shape of the output Tensor is the same as ``mean`` or ``std`` , attr ``shape`` is ignored.
Default is None
name (str|None, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
Returns:
Tensor, A Tensor filled with random values sampled from a log normal distribution with the underlying normal distribution's ``mean`` and ``std`` .
Examples:
.. code-block:: python
>>> import paddle
>>> paddle.seed(200)
>>> out1 = paddle.log_normal(shape=[2, 3])
>>> print(out1)
Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
[[4.01107359 , 3.53824377 , 25.79078865],
[0.83332109 , 0.40513405 , 2.09763741 ]])
>>> mean_tensor = paddle.to_tensor([1.0, 2.0, 3.0])
>>> out2 = paddle.log_normal(mean=mean_tensor)
>>> print(out2)
Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
[4.45330524 , 0.57903880 , 31.82369995])
>>> std_tensor = paddle.to_tensor([1.0, 2.0, 3.0])
>>> out3 = paddle.log_normal(mean=mean_tensor, std=std_tensor)
>>> print(out3)
Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
[10.31321430, 8.97369766 , 35.76752090])
"""
normal_sample = paddle.normal(mean=mean, std=std, shape=shape, name=name)
return paddle.exp(normal_sample)
@dygraph_only
def log_normal_(
x: Tensor, mean: float = 1.0, std: float = 2.0, name: str | None = None
) -> Tensor:
r"""
This inplace version of api ``log_normal``, which returns a Tensor filled
with random values sampled from a log normal distribution. The output Tensor will
be inplaced with input ``x``. Please refer to :ref:`api_paddle_log_normal`.
Args:
x (Tensor): The input tensor to be filled with random values.
mean (float|int, optional): Mean of the output tensor, default is 1.0.
std (float|int, optional): Standard deviation of the output tensor, default
is 2.0.
name(str|None, optional): 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, A Tensor filled with random values sampled from a log normal distribution with the underlying normal distribution's ``mean`` and ``std`` .
Examples:
.. code-block:: python
>>> import paddle
>>> paddle.seed(200)
>>> x = paddle.randn([3, 4])
>>> x.log_normal_()
>>> print(x)
Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
[[3.99360156 , 0.11746082 , 12.14813519, 4.74383831 ],
[0.36592522 , 0.09426476 , 31.81549835, 0.61839998 ],
[1.33314908 , 12.31954002, 36.44527435, 1.69572163 ]])
"""
return normal_(x, mean=mean, std=std).exp_()
def multinomial(
x: Tensor,
num_samples: int = 1,
replacement: bool = False,
name: str | None = None,
) -> Tensor:
"""
Returns a Tensor filled with random values sampled from a Multinomical
distribution. The input ``x`` is a tensor with probabilities for generating the
random number. Each element in ``x`` should be larger or equal to 0, but not all
0. ``replacement`` indicates whether it is a replaceable sample. If ``replacement``
is True, a category can be sampled more than once.
Args:
x(Tensor): A tensor with probabilities for generating the random number. The data type
should be float32, float64.
num_samples(int, optional): Number of samples, default is 1.
replacement(bool, optional): Whether it is a replaceable sample, default is False.
name(str|None, optional): 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, A Tensor filled with sampled category index after ``num_samples`` times samples.
Examples:
.. code-block:: python
>>> import paddle
>>> paddle.seed(100) # on CPU device
>>> x = paddle.rand([2,4])
>>> print(x)
>>> # doctest: +SKIP("Random output")
Tensor(shape=[2, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
[[0.55355281, 0.20714243, 0.01162981, 0.51577556],
[0.36369765, 0.26091650, 0.18905126, 0.56219709]])
>>> # doctest: -SKIP
>>> paddle.seed(200) # on CPU device
>>> out1 = paddle.multinomial(x, num_samples=5, replacement=True)
>>> print(out1)
>>> # doctest: +SKIP("Random output")
Tensor(shape=[2, 5], dtype=int64, place=Place(cpu), stop_gradient=True,
[[3, 3, 0, 0, 0],
[3, 3, 3, 1, 0]])
>>> # doctest: -SKIP
>>> # out2 = paddle.multinomial(x, num_samples=5)
>>> # InvalidArgumentError: When replacement is False, number of samples
>>> # should be less than non-zero categories
>>> paddle.seed(300) # on CPU device
>>> out3 = paddle.multinomial(x, num_samples=3)
>>> print(out3)
>>> # doctest: +SKIP("Random output")
Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
[[3, 0, 1],
[3, 1, 0]])
>>> # doctest: -SKIP
"""
if in_dynamic_or_pir_mode():
return _C_ops.multinomial(x, num_samples, replacement)
else:
check_variable_and_dtype(
x, "x", ["uint16", "float16", "float32", "float64"], "multinomial"
)
helper = LayerHelper("multinomial", **locals())
out = helper.create_variable_for_type_inference(
dtype=convert_np_dtype_to_dtype_('int64')
)
helper.append_op(
type='multinomial',
inputs={"X": x},
outputs={'Out': out},
attrs={'num_samples': num_samples, 'replacement': replacement},
)
out.stop_gradient = True
return out
def uniform_random_batch_size_like(
input: Tensor,
shape: ShapeLike,
dtype: DTypeLike = 'float32',
input_dim_idx: int = 0,
output_dim_idx: int = 0,
min: float = -1.0,
max: float = 1.0,
seed: int = 0,
) -> Tensor:
"""
This OP initializes a variable with random values sampled from a
uniform distribution in the range [min, max). The input_dim_idx used to get the input dimension value which will be used to resize the output dimension.
.. code-block:: text
*Case 1:
Given:
input =[[0.946741 , 0.1357001 , 0.38086128]] # input.shape=[1,3]
shape=[2,4]
result.shape[output_dim_idx] = input.shape[input_dim_idx],
output_dim_idx = 0,
input_dim_idx = 0,
result.shape[0] = input.shape[0],
then:
result=[[ 0.3443427 , -0.23056602, 0.3477049 , 0.06139076]] # result.shape=[1,4]
*Case 2:
Given:
input =[[0.946741 , 0.1357001 , 0.38086128]] # input.shape=[1,3]
shape=[2,4]
input_dim_idx=1
output_dim_idx=1
result.shape[output_dim_idx] = input.shape[input_dim_idx],
output_dim_idx = 1,
input_dim_idx = 1,
result.shape[1] = input.shape[1],
then:
result=[[-0.23133647, -0.84195036, 0.21441269],
[-0.08774924, 0.25605237, -0.09403259]] # result.shape=[2,3]
Args:
input (Tensor): A Tensor. Supported data types: float32, float64.
shape (tuple|list): A python list or python tuple. The shape of the output Tensor, the data type is int.
dtype(np.dtype|paddle.dtype|str, optional): The data type of output Tensor. Supported data types: float32, float64. Default float32.
input_dim_idx (int, optional): An index used to get the input dimension value which will be used to resize the output dimension. Default 0.
output_dim_idx (int, optional): An index used to indicate the specific dimension that will be replaced by corresponding input dimension value. Default 0.
min (float, optional): The lower bound on the range of random values to generate, the min is included in the range. Default -1.0.
max (float, optional): The upper bound on the range of random values to generate, the max is excluded in the range. Default 1.0.
seed (int, optional): Random seed used for generating samples. 0 means use a seed generated by the system.Note that if seed is not 0, this operator will always generate the same random numbers every time.
Returns:
Tensor, A Tensor of the specified shape filled with uniform_random values. The shape of the Tensor is determined by the shape parameter and the specified dimension of the input Tensor.
Examples:
.. code-block:: python
>>> import paddle
>>> import paddle.base as base
>>> from paddle.tensor import random
>>> paddle.enable_static()
>>> # example 1:
>>> input = paddle.static.data(name="input", shape=[1, 3], dtype='float32')
>>> out_1 = random.uniform_random_batch_size_like(input, [2, 4])
>>> print(out_1.shape)
[1, 4]
>>> # example 2:
>>> out_2 = random.uniform_random_batch_size_like(input, [2, 4], input_dim_idx=1, output_dim_idx=1)
>>> print(out_2.shape)
[2, 3]
"""
if in_dynamic_or_pir_mode():
dtype = convert_np_dtype_to_dtype_(dtype)
return _C_ops.uniform_random_batch_size_like(
input,
shape,
input_dim_idx,
output_dim_idx,
min,
max,
seed,
0,
0,
1.0,
dtype,
)
check_variable_and_dtype(
input,
'Input',
("float32", 'float64', "uint16"),
'uniform_random_batch_size_like',
)
check_type(shape, 'shape', (list, tuple), 'uniform_random_batch_size_like')
check_dtype(
dtype,
'dtype',
('float32', 'float64', "uint16"),
'uniform_random_batch_size_like',
)
helper = LayerHelper('uniform_random_batch_size_like', **locals())
out = helper.create_variable_for_type_inference(dtype)
c_dtype = convert_np_dtype_to_dtype_(dtype)
helper.append_op(
type='uniform_random_batch_size_like',
inputs={'Input': input},
outputs={'Out': out},
attrs={
'shape': shape,
'input_dim_idx': input_dim_idx,
'output_dim_idx': output_dim_idx,
'min': min,
'max': max,
'seed': seed,
'dtype': c_dtype,
},
)
return out
def gaussian(
shape: ShapeLike,
mean: complex = 0.0,
std: float = 1.0,
seed: int = 0,
dtype: DTypeLike | None = None,
name: str | None = None,
) -> Tensor:
"""
Returns a Tensor filled with random values sampled from a Gaussian
distribution, with ``shape`` and ``dtype``.
Args:
shape (tuple|list|Tensor): Shape of the Tensor to be created. The data type is ``int32`` or ``int64`` .
If ``shape`` is a list or tuple, each element of it should be integer or 0-D Tensor with shape [].
If ``shape`` is an Tensor, it should be an 1-D Tensor which represents a list.
mean (float|int|complex, optional): Mean of the output tensor, default is 0.0.
std (float|int, optional): Standard deviation of the output tensor, default
is 1.0.
seed (int, optional): Random seed of generator.
dtype (str|np.dtype|paddle.dtype|None, optional): The data type of the output Tensor.
Supported data types: bfloat16, float16, float32, float64, complex64, complex128.
Default is None, use global default dtype (see ``get_default_dtype``
for details).
name (str|None, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
Returns:
Tensor, A Tensor filled with random values sampled from a Gaussian
distribution, with ``shape`` and ``dtype``.
"""
op_type_for_check = 'gaussian/standard_normal/randn/normal'
supported_dtypes = [
'float32',
'float64',
'float16',
'uint16',
'bfloat16',
'complex64',
'complex128',
]
if dtype is None:
dtype = paddle.framework.get_default_dtype()
if dtype not in supported_dtypes:
raise TypeError(
f"{op_type_for_check} only supports {supported_dtypes}, but the default dtype is {dtype}"
)
if not isinstance(dtype, (core.VarDesc.VarType, core.DataType)):
dtype = convert_np_dtype_to_dtype_(dtype)
if isinstance(mean, complex):
if dtype not in [
core.VarDesc.VarType.COMPLEX64,
core.VarDesc.VarType.COMPLEX128,
core.DataType.COMPLEX64,
core.DataType.COMPLEX128,
]:
raise TypeError(
"if mean is a complex number, dtype should be complex64 or complex128, "
f"but got dtype = {dtype}",
)
if mean.real != mean.imag:
raise ValueError(
"The mean of complex gaussian distribution should be a complex number with "
f"real part equal imaginary part, but got {mean.real} != {mean.imag}",
)
mean = mean.real
if in_dynamic_or_pir_mode():
if in_dynamic_mode():
shape = paddle.utils.convert_shape_to_list(shape)
elif in_pir_mode() and paddle.utils._contain_var(shape):
shape = paddle.utils.get_int_tensor_list(shape)
place = _current_expected_place()
return _C_ops.gaussian(
shape, float(mean), float(std), seed, dtype, place
)
else:
check_shape(shape, op_type_for_check)
check_dtype(dtype, 'dtype', supported_dtypes, op_type_for_check)
inputs = {}
attrs = {
'mean': mean,
'std': std,
'seed': seed,
'dtype': dtype,
}
paddle.utils.get_shape_tensor_inputs(
inputs=inputs, attrs=attrs, shape=shape, op_type=op_type_for_check
)
helper = LayerHelper('gaussian', **locals())
out = helper.create_variable_for_type_inference(dtype)
helper.append_op(
type='gaussian_random',
inputs=inputs,
outputs={'Out': out},
attrs=attrs,
)
out.stop_gradient = True
return out
@dygraph_only
def gaussian_(
x: Tensor,
mean: complex = 0.0,
std: float = 1.0,
seed: int = 0,
name: str | None = None,
) -> Tensor:
"""
This is the inplace version of OP ``gaussian``, which returns a Tensor filled
with random values sampled from a gaussian distribution. The output Tensor will
be inplaced with input ``x``. Please refer to :ref:`api_tensor_gaussian`.
Args:
x(Tensor): The input tensor to be filled with random values.
mean (float|int|complex, optional): Mean of the output tensor, default is 0.0.
std (float|int, optional): Standard deviation of the output tensor, default
is 1.0.
seed (int, optional): Random seed of generator.
name(str|None, optional): 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 input tensor x filled with random values sampled from a gaussian
distribution.
Examples:
.. code-block:: python
>>> import paddle
>>> x = paddle.randn([3, 4])
>>> paddle.tensor.random.gaussian_(x)
>>> print(x)
Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
[[ 0.86384124, 0.67328387, 0.21874231, -0.12615913],
[ 0.69844258, 0.42084831, -0.42476156, -0.00072985],
[ 1.72819555, 1.87785017, 0.48915744, 0.09235018]])
"""
if isinstance(mean, complex):
if x.dtype not in [
core.VarDesc.VarType.COMPLEX64,
core.VarDesc.VarType.COMPLEX128,
core.DataType.COMPLEX64,
core.DataType.COMPLEX128,
]:
raise TypeError(
"if mean is a complex number, x's dtype should be complex64 or complex128, "
f"but dtype = {x.dtype}",
)
if mean.real != mean.imag:
raise ValueError(
"The mean of complex gaussian distribution should be a complex number with "
f"real part equal imaginary part, but got {mean.real} != {mean.imag}",
)
mean = mean.real
return _C_ops.gaussian_inplace_(x, float(mean), float(std), int(seed))
def standard_normal(
shape: ShapeLike, dtype: DTypeLike | None = None, name: str | None = None
) -> Tensor:
"""
Returns a Tensor filled with random values sampled from a standard
normal distribution with mean 0 and standard deviation 1, with ``shape``
and ``dtype``.
Args:
shape (tuple|list|Tensor): Shape of the Tensor to be created. The data type is ``int32`` or ``int64`` .
If ``shape`` is a list or tuple, each element of it should be integer or 0-D Tensor with shape [].
If ``shape`` is an Tensor, it should be an 1-D Tensor which represents a list.
dtype (str|np.dtype|paddle.dtype|None, optional): The data type of the output Tensor.
Supported data types: float32, float64, complex64, complex128.
Default is None, use global default dtype (see ``get_default_dtype``
for details).
name (str|None, optional): Name for the operation (optional, default is None).
For more information, please refer to :ref:`api_guide_Name`.
Returns:
Tensor, A Tensor filled with random values sampled from a standard
normal distribution with mean 0 and standard deviation 1, with
``shape`` and ``dtype``.
Examples:
.. code-block:: python
>>> import paddle
>>> # doctest: +SKIP("Random output")
>>> # example 1: attr shape is a list which doesn't contain Tensor.
>>> out1 = paddle.standard_normal(shape=[2, 3])
>>> print(out1)
>>> # doctest: +SKIP("Random output")
Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
[[-0.33719197, -0.25688133, -0.42868865],
[-0.27804616, -0.25058213, -0.28209466]])
>>> # doctest: -SKIP
>>> # example 2: attr shape is a list which contains Tensor.
>>> dim1 = paddle.to_tensor(2, 'int64')
>>> dim2 = paddle.to_tensor(3, 'int32')
>>> out2 = paddle.standard_normal(shape=[dim1, dim2, 2])
>>> print(out2)
>>> # doctest: +SKIP("Random output")
Tensor(shape=[2, 3, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
[[[ 0.81888396, -0.64831746],
[ 1.28911388, -1.88154876],
[-0.03271919, -0.32410008]],
[[-0.20224631, 0.46683890],
[ 1.91947734, 0.71657443],
[ 0.33410960, -0.64256823]]])
>>> # doctest: -SKIP
>>> # example 3: attr shape is a Tensor, the data type must be int64 or int32.
>>> shape_tensor = paddle.to_tensor([2, 3])
>>> out3 = paddle.standard_normal(shape_tensor)
>>> print(out3)
>>> # doctest: +SKIP("Random output")
Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
[[ 0.01182475, -0.44895259, -1.79227340],
[ 1.52022707, -0.83830303, 0.05261501]])
>>> # doctest: -SKIP
>>> # example 4: attr dtype is complex64.
>>> paddle.seed(200)
>>> shape_tensor = paddle.to_tensor([2, 3])
>>> out4 = paddle.standard_normal(shape_tensor, dtype='complex64')
>>> print(out4)
Tensor(shape=[2, 3], dtype=complex64, place=Place(cpu), stop_gradient=True,
[[ (0.1375531256198883+0.0932074561715126j) ,
(0.7955012917518616-0.41801896691322327j),
(-0.6730020642280579-0.09163688868284225j)],
[ (0.17453041672706604-0.9002832770347595j),
(0.16270922124385834-1.3086302280426025j),
(0.9428746104240417+0.06869460642337799j)]])
"""
if dtype is not None and not isinstance(
dtype, (core.VarDesc.VarType, core.DataType)
):
dtype = convert_np_dtype_to_dtype_(dtype)
if dtype in [
core.VarDesc.VarType.COMPLEX64,
core.VarDesc.VarType.COMPLEX64,
]:
return gaussian(
shape=shape, mean=(0.0 + 0.0j), std=1.0, dtype=dtype, name=name
)
else:
return gaussian(
shape=shape, mean=0.0, std=1.0, dtype=dtype, name=name
)
else:
return gaussian(shape=shape, mean=0.0, std=1.0, dtype=dtype, name=name)
def randn(
shape: ShapeLike, dtype: DTypeLike | None = None, name: str | None = None
) -> Tensor:
"""
Returns a Tensor filled with random values sampled from a standard
normal distribution with mean 0 and standard deviation 1, with ``shape``
and ``dtype``.
Args:
shape (tuple|list|Tensor): Shape of the Tensor to be created. The data type is ``int32`` or ``int64`` .
If ``shape`` is a list or tuple, each element of it should be integer or 0-D Tensor with shape [].
If ``shape`` is an Tensor, it should be an 1-D Tensor which represents a list.
dtype (str|np.dtype|paddle.dtype|None, optional): The data type of the output Tensor.
Supported data types: float32, float64, complex64, complex128.
Default is None, use global default dtype (see ``get_default_dtype``
for details).
name (str|None, optional): Name for the operation (optional, default is None).
For more information, please refer to :ref:`api_guide_Name`.
Returns:
Tensor, A Tensor filled with random values sampled from a standard
normal distribution with mean 0 and standard deviation 1, with
``shape`` and ``dtype``.
Examples:
.. code-block:: python
>>> import paddle
>>> # example 1: attr shape is a list which doesn't contain Tensor.
>>> out1 = paddle.randn(shape=[2, 3])
>>> print(out1)
>>> # doctest: +SKIP("Random output")
Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
[[-0.29270014, -0.02925120, -1.07807338],
[ 1.19966674, -0.46673676, -0.18050613]])
>>> # doctest: -SKIP
>>> # example 2: attr shape is a list which contains Tensor.
>>> dim1 = paddle.to_tensor(2, 'int64')
>>> dim2 = paddle.to_tensor(3, 'int32')
>>> out2 = paddle.randn(shape=[dim1, dim2, 2])
>>> print(out2)
>>> # doctest: +SKIP("Random output")
Tensor(shape=[2, 3, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
[[[-0.26019713, 0.54994684],
[ 0.46403214, -1.41178775],
[-0.15682915, -0.26639181]],
[[ 0.01364388, -2.81676364],
[ 0.86996621, 0.07524570],
[ 0.21443737, 0.90938759]]])
>>> # doctest: -SKIP
>>> # example 3: attr shape is a Tensor, the data type must be int64 or int32.
>>> shape_tensor = paddle.to_tensor([2, 3])
>>> out3 = paddle.randn(shape_tensor)
>>> print(out3)
>>> # doctest: +SKIP("Random output")
Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
[[ 0.57575506, -1.60349274, -0.27124876],
[ 1.08381045, 0.81270242, -0.26763600]])
>>> # doctest: -SKIP
>>> # example 4: attr dtype is complex64.
>>> paddle.seed(200)
>>> shape_tensor = paddle.to_tensor([2, 3])
>>> out4 = paddle.randn(shape_tensor, dtype='complex64')
>>> print(out4)
Tensor(shape=[2, 3], dtype=complex64, place=Place(cpu), stop_gradient=True,
[[ (0.1375531256198883+0.0932074561715126j) ,
(0.7955012917518616-0.41801896691322327j),
(-0.6730020642280579-0.09163688868284225j)],
[ (0.17453041672706604-0.9002832770347595j),
(0.16270922124385834-1.3086302280426025j),
(0.9428746104240417+0.06869460642337799j)]])
"""
return standard_normal(shape, dtype, name)
def normal(
mean: complex | Tensor = 0.0,
std: float | Tensor = 1.0,
shape: ShapeLike | None = None,
name: str | None = None,
) -> Tensor:
"""
Returns a Tensor filled with random values sampled from a normal
distribution with ``mean`` and ``std`` (standard deviation) .
If ``mean`` is a Tensor, the output Tensor has the same shape and data type as ``mean``.
If ``mean`` is not a Tensor and ``std`` is a Tensor, the output Tensor has the same shape and data type as ``std``.
If ``mean`` and ``std`` are not a Tensor, the output Tensor has the same shape as ``shape``, with data type float32.
If ``mean`` and ``std`` are Tensor, the num of elements of ``mean`` and ``std`` should be the same.
If ``mean`` is a complex number, the output Tensor follows complex normal distribution, with data type complex 64.
If ``mean`` is a Tensor with complex data type, the output Tensor has same data type with ``mean``.
Args:
mean (float|complex|Tensor, optional): The mean of the output Tensor's normal distribution.
If ``mean`` is float, all elements of the output Tensor shared the same mean.
If ``mean`` is a Tensor(data type supports float32, float64, complex64, complex128), it has per-element means.
Default is 0.0
std (float|Tensor, optional): The standard deviation of the output Tensor's normal distribution.
If ``std`` is float, all elements of the output Tensor shared the same standard deviation.
If ``std`` is a Tensor(data type supports float32, float64), it has per-element standard deviations.
Default is 1.0
shape (tuple|list|Tensor|None, optional): Shape of the Tensor to be created. The data type is ``int32`` or ``int64`` .
If ``shape`` is a list or tuple, each element of it should be integer or 0-D Tensor with shape [].
If ``shape`` is an Tensor, it should be an 1-D Tensor which represents a list. If ``mean`` or ``std``
is a Tensor, the shape of the output Tensor is the same as ``mean`` or ``std`` , attr ``shape`` is ignored.