random.py 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # TODO: define random functions
  15. import paddle
  16. from paddle import _C_ops, _legacy_C_ops
  17. from paddle.base.framework import _current_expected_place
  18. from paddle.base.libpaddle import DataType
  19. from paddle.common_ops_import import Variable
  20. from paddle.framework import (
  21. in_dynamic_mode,
  22. in_dynamic_or_pir_mode,
  23. in_pir_mode,
  24. use_pir_api,
  25. )
  26. from ..base.data_feeder import (
  27. check_dtype,
  28. check_shape,
  29. check_type,
  30. check_variable_and_dtype,
  31. )
  32. from ..framework import (
  33. LayerHelper,
  34. convert_np_dtype_to_dtype_,
  35. core,
  36. dygraph_only,
  37. )
  38. __all__ = []
  39. def bernoulli(x, name=None):
  40. r"""
  41. 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
  42. .. math::
  43. p(y)=\begin{cases}
  44. x_i,&y=1\\
  45. 1-x_i,&y=0
  46. \end{cases}.
  47. Args:
  48. x (Tensor): The input Tensor, it's data type should be float32, float64.
  49. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  50. Returns:
  51. Tensor: A Tensor filled samples from Bernoulli distribution, whose shape and dtype are same as ``x``.
  52. Examples:
  53. .. code-block:: python
  54. >>> import paddle
  55. >>> paddle.set_device('cpu') # on CPU device
  56. >>> paddle.seed(100)
  57. >>> x = paddle.rand([2,3])
  58. >>> print(x)
  59. >>> # doctest: +SKIP("Random output")
  60. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  61. [[0.55355281, 0.20714243, 0.01162981],
  62. [0.51577556, 0.36369765, 0.26091650]])
  63. >>> # doctest: -SKIP
  64. >>> out = paddle.bernoulli(x)
  65. >>> print(out)
  66. >>> # doctest: +SKIP("Random output")
  67. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  68. [[1., 0., 1.],
  69. [0., 1., 0.]])
  70. >>> # doctest: -SKIP
  71. """
  72. if in_dynamic_or_pir_mode():
  73. return _C_ops.bernoulli(x)
  74. else:
  75. check_variable_and_dtype(
  76. x, "x", ["float32", "float64", "float16", "uint16"], "bernoulli"
  77. )
  78. helper = LayerHelper("randint", **locals())
  79. out = helper.create_variable_for_type_inference(
  80. dtype=x.dtype
  81. ) # maybe set out to int32 ?
  82. helper.append_op(
  83. type='bernoulli', inputs={"X": x}, outputs={'Out': out}, attrs={}
  84. )
  85. out.stop_gradient = True
  86. return out
  87. @dygraph_only
  88. def bernoulli_(x, p=0.5, name=None):
  89. """
  90. This is the inplace version of api ``bernoulli``, which returns a Tensor filled
  91. with random values sampled from a bernoulli distribution. The output Tensor will
  92. be inplaced with input ``x``. Please refer to :ref:`api_paddle_bernoulli`.
  93. Args:
  94. x(Tensor): The input tensor to be filled with random values.
  95. p (float|Tensor, optional): The success probability parameter of the output Tensor's bernoulli distribution.
  96. If ``p`` is float, all elements of the output Tensor shared the same success probability.
  97. If ``p`` is a Tensor, it has per-element success probabilities, and the shape should be broadcastable to ``x``.
  98. Default is 0.5
  99. name(str, optional): The default value is None. Normally there is no
  100. need for user to set this property. For more information, please
  101. refer to :ref:`api_guide_Name`.
  102. Returns:
  103. A Tensor filled with random values sampled from the bernoulli distribution with success probability ``p`` .
  104. Examples:
  105. .. code-block:: python
  106. >>> import paddle
  107. >>> paddle.set_device('cpu')
  108. >>> paddle.seed(200)
  109. >>> x = paddle.randn([3, 4])
  110. >>> x.bernoulli_()
  111. >>> print(x)
  112. Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
  113. [[0., 1., 0., 1.],
  114. [1., 1., 0., 1.],
  115. [0., 1., 0., 0.]])
  116. >>> x = paddle.randn([3, 4])
  117. >>> p = paddle.randn([3, 1])
  118. >>> x.bernoulli_(p)
  119. >>> print(x)
  120. Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
  121. [[1., 1., 1., 1.],
  122. [0., 0., 0., 0.],
  123. [0., 0., 0., 0.]])
  124. """
  125. x.uniform_(0.0, 1.0)
  126. ones_mask = x > p
  127. zeros_mask = x < p
  128. x.masked_fill_(ones_mask, 1.0)
  129. x.masked_fill_(zeros_mask, 0.0)
  130. return x
  131. def binomial(count, prob, name=None):
  132. r"""
  133. Returns a tensor filled with random number from the Binomial Distribution, which supports Tensor shape
  134. broadcasting. The returned Tensor's data type is int64.
  135. .. math::
  136. out_i \sim Binomial (n = count_i, p = prob_i)
  137. Args:
  138. count(Tensor): A tensor with each element specifying the size of a binomial distribution. The input
  139. data type should be int32 or int64.
  140. prob(Tensor): A tensor with each element specifying the probability of success in the binomial experiment.
  141. The input data type should be bfloat16, float16, float32, float64.
  142. name(str, optional): The default value is None. Normally there is no need for user to set this
  143. property. For more information, please refer to :ref:`api_guide_Name`.
  144. Returns:
  145. Tensor: A Tensor filled with binomial random values with the same shape as the broadcasted Tensors of
  146. ``count`` and ``prob``. The data type is int64.
  147. Examples:
  148. .. code-block:: python
  149. >>> import paddle
  150. >>> paddle.set_device('cpu')
  151. >>> paddle.seed(100)
  152. >>> n = paddle.to_tensor([10.0, 50.0])
  153. >>> p = paddle.to_tensor([0.2, 0.6])
  154. >>> out = paddle.binomial(n, p)
  155. >>> print(out)
  156. >>> # doctest: +SKIP("Random output")
  157. Tensor(shape=[2], dtype=int64, place=Place(cpu), stop_gradient=True,
  158. [1 , 31])
  159. >>> # doctest: -SKIP
  160. """
  161. if in_dynamic_or_pir_mode():
  162. count, prob = paddle.broadcast_tensors(
  163. [paddle.cast(count, dtype=prob.dtype), prob]
  164. )
  165. return _C_ops.binomial(count, prob)
  166. else:
  167. check_variable_and_dtype(count, "count", ["int32", "int64"], "binomial")
  168. check_variable_and_dtype(
  169. prob,
  170. "prob",
  171. ["bfloat16", "float16", "float32", "float64"],
  172. "binomial",
  173. )
  174. count, prob = paddle.broadcast_tensors(
  175. [paddle.cast(count, dtype=prob.dtype), prob]
  176. )
  177. helper = LayerHelper("binomial", **locals())
  178. out = helper.create_variable_for_type_inference(
  179. dtype=convert_np_dtype_to_dtype_('int64')
  180. )
  181. helper.append_op(
  182. type='binomial',
  183. inputs={"count": count, "prob": prob},
  184. outputs={'out': out},
  185. attrs={},
  186. )
  187. out.stop_gradient = True
  188. return out
  189. def poisson(x, name=None):
  190. r"""
  191. Returns a tensor filled with random number from a Poisson Distribution.
  192. .. math::
  193. out_i \sim Poisson (lambda = x_i)
  194. Args:
  195. x(Tensor): A tensor with rate parameter of poisson Distribution. The data type
  196. should be bfloat16, float16, float32, float64.
  197. name(str, optional): The default value is None. Normally there is no
  198. need for user to set this property. For more information, please
  199. refer to :ref:`api_guide_Name`.
  200. Returns:
  201. Tensor: A Tensor filled with random number with the same shape and dtype as ``x``.
  202. Examples:
  203. .. code-block:: python
  204. >>> import paddle
  205. >>> paddle.set_device('cpu')
  206. >>> paddle.seed(100)
  207. >>> x = paddle.uniform([2,3], min=1.0, max=5.0)
  208. >>> out = paddle.poisson(x)
  209. >>> print(out)
  210. >>> # doctest: +SKIP("Random output")
  211. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  212. [[2., 5., 0.],
  213. [5., 1., 3.]])
  214. >>> # doctest: -SKIP
  215. """
  216. if in_dynamic_or_pir_mode():
  217. return _C_ops.poisson(x)
  218. else:
  219. check_variable_and_dtype(x, "x", ["float32", "float64"], "poisson")
  220. helper = LayerHelper("poisson", **locals())
  221. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  222. helper.append_op(
  223. type='poisson', inputs={'X': x}, outputs={'Out': out}, attrs={}
  224. )
  225. return out
  226. def standard_gamma(x, name=None):
  227. r"""
  228. Returns a tensor filled with random number from a Standard Gamma Distribution.
  229. .. math::
  230. out_i \sim Gamma (alpha = x_i, beta = 1.0)
  231. Args:
  232. x(Tensor): A tensor with rate parameter of standard gamma Distribution. The data type
  233. should be bfloat16, float16, float32, float64.
  234. name(str, optional): The default value is None. Normally there is no
  235. need for user to set this property. For more information, please
  236. refer to :ref:`api_guide_Name`.
  237. Returns:
  238. Tensor: A Tensor filled with random number with the same shape and dtype as ``x``.
  239. Examples:
  240. .. code-block:: python
  241. >>> import paddle
  242. >>> paddle.set_device('cpu')
  243. >>> paddle.seed(100)
  244. >>> x = paddle.uniform([2,3], min=1.0, max=5.0)
  245. >>> out = paddle.standard_gamma(x)
  246. >>> print(out)
  247. >>> # doctest: +SKIP("Random output")
  248. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  249. [[3.35393834, 0.80538225, 0.36511323],
  250. [6.10344696, 4.28612375, 6.37196636]])
  251. >>> # doctest: -SKIP
  252. """
  253. if in_dynamic_or_pir_mode():
  254. return _C_ops.standard_gamma(x)
  255. else:
  256. check_variable_and_dtype(
  257. x, "x", ["float32", "float64"], "standard_gamma"
  258. )
  259. helper = LayerHelper("standard_gamma", **locals())
  260. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  261. helper.append_op(
  262. type='standard_gamma',
  263. inputs={'x': x},
  264. outputs={'out': out},
  265. attrs={},
  266. )
  267. return out
  268. def multinomial(x, num_samples=1, replacement=False, name=None):
  269. """
  270. Returns a Tensor filled with random values sampled from a Multinomical
  271. distribution. The input ``x`` is a tensor with probabilities for generating the
  272. random number. Each element in ``x`` should be larger or equal to 0, but not all
  273. 0. ``replacement`` indicates whether it is a replaceable sample. If ``replacement``
  274. is True, a category can be sampled more than once.
  275. Args:
  276. x(Tensor): A tensor with probabilities for generating the random number. The data type
  277. should be float32, float64.
  278. num_samples(int, optional): Number of samples, default is 1.
  279. replacement(bool, optional): Whether it is a replaceable sample, default is False.
  280. name(str, optional): The default value is None. Normally there is no
  281. need for user to set this property. For more information, please
  282. refer to :ref:`api_guide_Name`.
  283. Returns:
  284. Tensor: A Tensor filled with sampled category index after ``num_samples`` times samples.
  285. Examples:
  286. .. code-block:: python
  287. >>> import paddle
  288. >>> paddle.seed(100) # on CPU device
  289. >>> x = paddle.rand([2,4])
  290. >>> print(x)
  291. >>> # doctest: +SKIP("Random output")
  292. Tensor(shape=[2, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
  293. [[0.55355281, 0.20714243, 0.01162981, 0.51577556],
  294. [0.36369765, 0.26091650, 0.18905126, 0.56219709]])
  295. >>> # doctest: -SKIP
  296. >>> paddle.seed(200) # on CPU device
  297. >>> out1 = paddle.multinomial(x, num_samples=5, replacement=True)
  298. >>> print(out1)
  299. >>> # doctest: +SKIP("Random output")
  300. Tensor(shape=[2, 5], dtype=int64, place=Place(cpu), stop_gradient=True,
  301. [[3, 3, 0, 0, 0],
  302. [3, 3, 3, 1, 0]])
  303. >>> # doctest: -SKIP
  304. >>> # out2 = paddle.multinomial(x, num_samples=5)
  305. >>> # InvalidArgumentError: When replacement is False, number of samples
  306. >>> # should be less than non-zero categories
  307. >>> paddle.seed(300) # on CPU device
  308. >>> out3 = paddle.multinomial(x, num_samples=3)
  309. >>> print(out3)
  310. >>> # doctest: +SKIP("Random output")
  311. Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  312. [[3, 0, 1],
  313. [3, 1, 0]])
  314. >>> # doctest: -SKIP
  315. """
  316. if in_dynamic_or_pir_mode():
  317. return _C_ops.multinomial(x, num_samples, replacement)
  318. else:
  319. check_variable_and_dtype(
  320. x, "x", ["uint16", "float16", "float32", "float64"], "multinomial"
  321. )
  322. helper = LayerHelper("multinomial", **locals())
  323. out = helper.create_variable_for_type_inference(
  324. dtype=convert_np_dtype_to_dtype_('int64')
  325. )
  326. helper.append_op(
  327. type='multinomial',
  328. inputs={"X": x},
  329. outputs={'Out': out},
  330. attrs={'num_samples': num_samples, 'replacement': replacement},
  331. )
  332. out.stop_gradient = True
  333. return out
  334. def uniform_random_batch_size_like(
  335. input,
  336. shape,
  337. dtype='float32',
  338. input_dim_idx=0,
  339. output_dim_idx=0,
  340. min=-1.0,
  341. max=1.0,
  342. seed=0,
  343. ):
  344. """
  345. This OP initializes a variable with random values sampled from a
  346. 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.
  347. .. code-block:: text
  348. *Case 1:
  349. Given:
  350. input =[[0.946741 , 0.1357001 , 0.38086128]] # input.shape=[1,3]
  351. shape=[2,4]
  352. result.shape[output_dim_idx] = input.shape[input_dim_idx],
  353. output_dim_idx = 0,
  354. input_dim_idx = 0,
  355. result.shape[0] = input.shape[0],
  356. then:
  357. result=[[ 0.3443427 , -0.23056602, 0.3477049 , 0.06139076]] # result.shape=[1,4]
  358. *Case 2:
  359. Given:
  360. input =[[0.946741 , 0.1357001 , 0.38086128]] # input.shape=[1,3]
  361. shape=[2,4]
  362. input_dim_idx=1
  363. output_dim_idx=1
  364. result.shape[output_dim_idx] = input.shape[input_dim_idx],
  365. output_dim_idx = 1,
  366. input_dim_idx = 1,
  367. result.shape[1] = input.shape[1],
  368. then:
  369. result=[[-0.23133647, -0.84195036, 0.21441269],
  370. [-0.08774924, 0.25605237, -0.09403259]] # result.shape=[2,3]
  371. Args:
  372. input (Variable): A Tensor. Supported data types: float32, float64.
  373. shape (tuple|list): A python list or python tuple. The shape of the output Tensor, the data type is int.
  374. 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.
  375. output_dim_idx (int, optional): An index used to indicate the specific dimension that will be replaced by corresponding input dimension value. Default 0.
  376. min (float, optional): The lower bound on the range of random values to generate, the min is included in the range. Default -1.0.
  377. max (float, optional): The upper bound on the range of random values to generate, the max is excluded in the range. Default 1.0.
  378. 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.
  379. dtype(np.dtype|core.VarDesc.VarType|str, optional): The data type of output Tensor. Supported data types: float32, float64. Default float32.
  380. Returns:
  381. Variable: 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.
  382. Examples:
  383. .. code-block:: python
  384. >>> import paddle
  385. >>> import paddle.base as base
  386. >>> from paddle.tensor import random
  387. >>> paddle.enable_static()
  388. >>> # example 1:
  389. >>> input = paddle.static.data(name="input", shape=[1, 3], dtype='float32')
  390. >>> out_1 = random.uniform_random_batch_size_like(input, [2, 4])
  391. >>> print(out_1.shape)
  392. [1, 4]
  393. >>> # example 2:
  394. >>> out_2 = random.uniform_random_batch_size_like(input, [2, 4], input_dim_idx=1, output_dim_idx=1)
  395. >>> print(out_2.shape)
  396. [2, 3]
  397. """
  398. if in_dynamic_or_pir_mode():
  399. dtype = convert_np_dtype_to_dtype_(dtype)
  400. return _C_ops.uniform_random_batch_size_like(
  401. input,
  402. shape,
  403. input_dim_idx,
  404. output_dim_idx,
  405. min,
  406. max,
  407. seed,
  408. 0,
  409. 0,
  410. 1.0,
  411. dtype,
  412. )
  413. check_variable_and_dtype(
  414. input,
  415. 'Input',
  416. ("float32", 'float64', "uint16"),
  417. 'uniform_random_batch_size_like',
  418. )
  419. check_type(shape, 'shape', (list, tuple), 'uniform_random_batch_size_like')
  420. check_dtype(
  421. dtype,
  422. 'dtype',
  423. ('float32', 'float64', "uint16"),
  424. 'uniform_random_batch_size_like',
  425. )
  426. helper = LayerHelper('uniform_random_batch_size_like', **locals())
  427. out = helper.create_variable_for_type_inference(dtype)
  428. c_dtype = convert_np_dtype_to_dtype_(dtype)
  429. helper.append_op(
  430. type='uniform_random_batch_size_like',
  431. inputs={'Input': input},
  432. outputs={'Out': out},
  433. attrs={
  434. 'shape': shape,
  435. 'input_dim_idx': input_dim_idx,
  436. 'output_dim_idx': output_dim_idx,
  437. 'min': min,
  438. 'max': max,
  439. 'seed': seed,
  440. 'dtype': c_dtype,
  441. },
  442. )
  443. return out
  444. def gaussian(shape, mean=0.0, std=1.0, seed=0, dtype=None, name=None):
  445. """
  446. Returns a Tensor filled with random values sampled from a Gaussian
  447. distribution, with ``shape`` and ``dtype``.
  448. Args:
  449. shape (tuple|list|Tensor): Shape of the Tensor to be created. The data type is ``int32`` or ``int64`` .
  450. If ``shape`` is a list or tuple, each element of it should be integer or 0-D Tensor with shape [].
  451. If ``shape`` is an Tensor, it should be an 1-D Tensor which represents a list.
  452. mean (float|int, optional): Mean of the output tensor, default is 0.0.
  453. std (float|int, optional): Standard deviation of the output tensor, default
  454. is 1.0.
  455. seed (int, optional): Random seed of generator.
  456. dtype (str|np.dtype, optional): The data type of the output Tensor.
  457. Supported data types: float32, float64.
  458. Default is None, use global default dtype (see ``get_default_dtype``
  459. for details).
  460. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  461. Returns:
  462. Tensor: A Tensor filled with random values sampled from a Gaussian
  463. distribution, with ``shape`` and ``dtype``.
  464. """
  465. op_type_for_check = 'gaussian/standard_normal/randn/normal'
  466. supported_dtypes = ['float32', 'float64', 'float16', 'uint16', 'bfloat16']
  467. if dtype is None:
  468. dtype = paddle.framework.get_default_dtype()
  469. if dtype not in supported_dtypes:
  470. raise TypeError(
  471. f"{op_type_for_check} only supports {supported_dtypes}, but the default dtype is {dtype}"
  472. )
  473. if not isinstance(dtype, (core.VarDesc.VarType, core.DataType)):
  474. dtype = convert_np_dtype_to_dtype_(dtype)
  475. if in_dynamic_or_pir_mode():
  476. if in_dynamic_mode():
  477. shape = paddle.utils.convert_shape_to_list(shape)
  478. elif in_pir_mode() and paddle.utils._contain_var(shape):
  479. shape = paddle.utils.get_int_tensor_list(shape)
  480. place = _current_expected_place()
  481. return _C_ops.gaussian(
  482. shape, float(mean), float(std), seed, dtype, place
  483. )
  484. else:
  485. check_shape(shape, op_type_for_check)
  486. check_dtype(dtype, 'dtype', supported_dtypes, op_type_for_check)
  487. inputs = {}
  488. attrs = {
  489. 'mean': mean,
  490. 'std': std,
  491. 'seed': seed,
  492. 'dtype': dtype,
  493. }
  494. paddle.utils.get_shape_tensor_inputs(
  495. inputs=inputs, attrs=attrs, shape=shape, op_type=op_type_for_check
  496. )
  497. helper = LayerHelper('gaussian', **locals())
  498. out = helper.create_variable_for_type_inference(dtype)
  499. helper.append_op(
  500. type='gaussian_random',
  501. inputs=inputs,
  502. outputs={'Out': out},
  503. attrs=attrs,
  504. )
  505. out.stop_gradient = True
  506. return out
  507. @dygraph_only
  508. def gaussian_(x, mean=0.0, std=1.0, seed=0, name=None):
  509. """
  510. This is the inplace version of OP ``gaussian``, which returns a Tensor filled
  511. with random values sampled from a gaussian distribution. The output Tensor will
  512. be inplaced with input ``x``. Please refer to :ref:`api_tensor_gaussian`.
  513. Args:
  514. x(Tensor): The input tensor to be filled with random values.
  515. mean (float|int, optional): Mean of the output tensor, default is 0.0.
  516. std (float|int, optional): Standard deviation of the output tensor, default
  517. is 1.0.
  518. seed (int, optional): Random seed of generator.
  519. name(str, optional): The default value is None. Normally there is no
  520. need for user to set this property. For more information, please
  521. refer to :ref:`api_guide_Name`.
  522. Returns:
  523. Tensor: The input tensor x filled with random values sampled from a gaussian
  524. distribution.
  525. Examples:
  526. .. code-block:: python
  527. >>> import paddle
  528. >>> x = paddle.randn([3, 4])
  529. >>> paddle.tensor.random.gaussian_(x)
  530. >>> print(x)
  531. Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
  532. [[ 0.86384124, 0.67328387, 0.21874231, -0.12615913],
  533. [ 0.69844258, 0.42084831, -0.42476156, -0.00072985],
  534. [ 1.72819555, 1.87785017, 0.48915744, 0.09235018]])
  535. """
  536. return _C_ops.gaussian_inplace_(x, float(mean), float(std), int(seed))
  537. def standard_normal(shape, dtype=None, name=None):
  538. """
  539. Returns a Tensor filled with random values sampled from a standard
  540. normal distribution with mean 0 and standard deviation 1, with ``shape``
  541. and ``dtype``.
  542. Args:
  543. shape (tuple|list|Tensor): Shape of the Tensor to be created. The data type is ``int32`` or ``int64`` .
  544. If ``shape`` is a list or tuple, each element of it should be integer or 0-D Tensor with shape [].
  545. If ``shape`` is an Tensor, it should be an 1-D Tensor which represents a list.
  546. dtype (str|np.dtype, optional): The data type of the output Tensor.
  547. Supported data types: float32, float64.
  548. Default is None, use global default dtype (see ``get_default_dtype``
  549. for details).
  550. name (str, optional): Name for the operation (optional, default is None).
  551. For more information, please refer to :ref:`api_guide_Name`.
  552. Returns:
  553. Tensor: A Tensor filled with random values sampled from a standard
  554. normal distribution with mean 0 and standard deviation 1, with
  555. ``shape`` and ``dtype``.
  556. Examples:
  557. .. code-block:: python
  558. >>> import paddle
  559. >>> # doctest: +SKIP("Random output")
  560. >>> # example 1: attr shape is a list which doesn't contain Tensor.
  561. >>> out1 = paddle.standard_normal(shape=[2, 3])
  562. >>> print(out1)
  563. >>> # doctest: +SKIP("Random output")
  564. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  565. [[-0.33719197, -0.25688133, -0.42868865],
  566. [-0.27804616, -0.25058213, -0.28209466]])
  567. >>> # doctest: -SKIP
  568. >>> # example 2: attr shape is a list which contains Tensor.
  569. >>> dim1 = paddle.to_tensor(2, 'int64')
  570. >>> dim2 = paddle.to_tensor(3, 'int32')
  571. >>> out2 = paddle.standard_normal(shape=[dim1, dim2, 2])
  572. >>> print(out2)
  573. >>> # doctest: +SKIP("Random output")
  574. Tensor(shape=[2, 3, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  575. [[[ 0.81888396, -0.64831746],
  576. [ 1.28911388, -1.88154876],
  577. [-0.03271919, -0.32410008]],
  578. [[-0.20224631, 0.46683890],
  579. [ 1.91947734, 0.71657443],
  580. [ 0.33410960, -0.64256823]]])
  581. >>> # doctest: -SKIP
  582. >>> # example 3: attr shape is a Tensor, the data type must be int64 or int32.
  583. >>> shape_tensor = paddle.to_tensor([2, 3])
  584. >>> out3 = paddle.standard_normal(shape_tensor)
  585. >>> print(out3)
  586. >>> # doctest: +SKIP("Random output")
  587. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  588. [[ 0.01182475, -0.44895259, -1.79227340],
  589. [ 1.52022707, -0.83830303, 0.05261501]])
  590. >>> # doctest: -SKIP
  591. """
  592. return gaussian(shape=shape, mean=0.0, std=1.0, dtype=dtype, name=name)
  593. def randn(shape, dtype=None, name=None):
  594. """
  595. Returns a Tensor filled with random values sampled from a standard
  596. normal distribution with mean 0 and standard deviation 1, with ``shape``
  597. and ``dtype``.
  598. Args:
  599. shape (tuple|list|Tensor): Shape of the Tensor to be created. The data type is ``int32`` or ``int64`` .
  600. If ``shape`` is a list or tuple, each element of it should be integer or 0-D Tensor with shape [].
  601. If ``shape`` is an Tensor, it should be an 1-D Tensor which represents a list.
  602. dtype (str|np.dtype, optional): The data type of the output Tensor.
  603. Supported data types: float32, float64.
  604. Default is None, use global default dtype (see ``get_default_dtype``
  605. for details).
  606. name (str, optional): Name for the operation (optional, default is None).
  607. For more information, please refer to :ref:`api_guide_Name`.
  608. Returns:
  609. Tensor: A Tensor filled with random values sampled from a standard
  610. normal distribution with mean 0 and standard deviation 1, with
  611. ``shape`` and ``dtype``.
  612. Examples:
  613. .. code-block:: python
  614. >>> import paddle
  615. >>> # example 1: attr shape is a list which doesn't contain Tensor.
  616. >>> out1 = paddle.randn(shape=[2, 3])
  617. >>> print(out1)
  618. >>> # doctest: +SKIP("Random output")
  619. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  620. [[-0.29270014, -0.02925120, -1.07807338],
  621. [ 1.19966674, -0.46673676, -0.18050613]])
  622. >>> # doctest: -SKIP
  623. >>> # example 2: attr shape is a list which contains Tensor.
  624. >>> dim1 = paddle.to_tensor(2, 'int64')
  625. >>> dim2 = paddle.to_tensor(3, 'int32')
  626. >>> out2 = paddle.randn(shape=[dim1, dim2, 2])
  627. >>> print(out2)
  628. >>> # doctest: +SKIP("Random output")
  629. Tensor(shape=[2, 3, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  630. [[[-0.26019713, 0.54994684],
  631. [ 0.46403214, -1.41178775],
  632. [-0.15682915, -0.26639181]],
  633. [[ 0.01364388, -2.81676364],
  634. [ 0.86996621, 0.07524570],
  635. [ 0.21443737, 0.90938759]]])
  636. >>> # doctest: -SKIP
  637. >>> # example 3: attr shape is a Tensor, the data type must be int64 or int32.
  638. >>> shape_tensor = paddle.to_tensor([2, 3])
  639. >>> out3 = paddle.randn(shape_tensor)
  640. >>> print(out3)
  641. >>> # doctest: +SKIP("Random output")
  642. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  643. [[ 0.57575506, -1.60349274, -0.27124876],
  644. [ 1.08381045, 0.81270242, -0.26763600]])
  645. >>> # doctest: -SKIP
  646. """
  647. return standard_normal(shape, dtype, name)
  648. def normal(mean=0.0, std=1.0, shape=None, name=None):
  649. """
  650. Returns a Tensor filled with random values sampled from a normal
  651. distribution with ``mean`` and ``std`` (standard deviation) .
  652. If ``mean`` is a Tensor, the output Tensor has the same shape and data type as ``mean``.
  653. If ``mean`` is not a Tensor and ``std`` is a Tensor, the output Tensor has the same shape and data type as ``std``.
  654. If ``mean`` and ``std`` are not a Tensor, the output Tensor has the same shape as ``shape``, with data type float32.
  655. If ``mean`` and ``std`` are Tensor, the num of elements of ``mean`` and ``std`` should be the same.
  656. Args:
  657. mean (float|Tensor, optional): The mean of the output Tensor's normal distribution.
  658. If ``mean`` is float, all elements of the output Tensor shared the same mean.
  659. If ``mean`` is a Tensor(data type supports float32, float64), it has per-element means.
  660. Default is 0.0
  661. std (float|Tensor, optional): The standard deviation of the output Tensor's normal distribution.
  662. If ``std`` is float, all elements of the output Tensor shared the same standard deviation.
  663. If ``std`` is a Tensor(data type supports float32, float64), it has per-element standard deviations.
  664. Default is 1.0
  665. shape (tuple|list|Tensor): Shape of the Tensor to be created. The data type is ``int32`` or ``int64`` .
  666. If ``shape`` is a list or tuple, each element of it should be integer or 0-D Tensor with shape [].
  667. If ``shape`` is an Tensor, it should be an 1-D Tensor which represents a list. If ``mean`` or ``std``
  668. is a Tensor, the shape of the output Tensor is the same as ``mean`` or ``std`` , attr ``shape`` is ignored.
  669. Default is None
  670. name (str, optional): Name for the operation (optional, default is None).
  671. For more information, please refer to :ref:`api_guide_Name`.
  672. Returns:
  673. A Tensor filled with random values sampled from a normal distribution with ``mean`` and ``std`` .
  674. Examples:
  675. .. code-block:: python
  676. >>> import paddle
  677. >>> out1 = paddle.normal(shape=[2, 3])
  678. >>> print(out1)
  679. >>> # doctest: +SKIP("Random output")
  680. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  681. [[-0.85107994, -0.85490644, -1.35941815],
  682. [-0.55500370, 0.20964541, 2.24193954]])
  683. >>> # doctest: -SKIP
  684. >>> mean_tensor = paddle.to_tensor([1.0, 2.0, 3.0])
  685. >>> out2 = paddle.normal(mean=mean_tensor)
  686. >>> print(out2)
  687. >>> # doctest: +SKIP("Random output")
  688. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  689. [1.05411839, 3.71514320, 3.42665267])
  690. >>> # doctest: -SKIP
  691. >>> std_tensor = paddle.to_tensor([1.0, 2.0, 3.0])
  692. >>> out3 = paddle.normal(mean=mean_tensor, std=std_tensor)
  693. >>> print(out3)
  694. >>> # doctest: +SKIP("Random output")
  695. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  696. [0.48646951, 0.00815189, 3.74022293])
  697. >>> # doctest: -SKIP
  698. """
  699. if not in_dynamic_mode():
  700. check_type(
  701. mean, 'mean', (int, float, Variable, paddle.pir.Value), 'normal'
  702. )
  703. check_type(
  704. std, 'std', (int, float, Variable, paddle.pir.Value), 'normal'
  705. )
  706. if isinstance(mean, (Variable, paddle.pir.Value)):
  707. check_dtype(
  708. mean.dtype,
  709. 'mean',
  710. ['float32', 'float64'],
  711. 'normal',
  712. "If mean is Tensor, it's data type only support float32, float64.",
  713. )
  714. if isinstance(std, (Variable, paddle.pir.Value)):
  715. check_dtype(
  716. std.dtype,
  717. 'std',
  718. ['float32', 'float64'],
  719. 'normal',
  720. "If std is Tensor, it's data type only support float32, float64.",
  721. )
  722. if shape is not None:
  723. check_shape(shape, 'normal')
  724. if isinstance(mean, (Variable, paddle.pir.Value)):
  725. if isinstance(std, (Variable, paddle.pir.Value)):
  726. if std.dtype != mean.dtype:
  727. std = paddle.cast(std, mean.dtype)
  728. mean_shape = paddle.shape(mean)
  729. std = paddle.reshape(std, mean_shape)
  730. else:
  731. std = float(std)
  732. out = standard_normal(paddle.shape(mean), mean.dtype, name)
  733. elif isinstance(std, (Variable, paddle.pir.Value)):
  734. mean = float(mean)
  735. out = standard_normal(paddle.shape(std), std.dtype, name)
  736. else:
  737. return gaussian(shape=shape, mean=mean, std=std, name=name)
  738. out = out * std + mean
  739. if not in_dynamic_or_pir_mode():
  740. out.stop_gradient = True
  741. return out
  742. @dygraph_only
  743. def normal_(x, mean=0.0, std=1.0, name=None):
  744. """
  745. This is the inplace version of api ``normal``, which returns a Tensor filled
  746. with random values sampled from a normal distribution. The output Tensor will
  747. be inplaced with input ``x``. Please refer to :ref:`api_tensor_normal`.
  748. Args:
  749. x(Tensor): The input tensor to be filled with random values.
  750. mean (float|Tensor, optional): The mean of the output Tensor's normal distribution.
  751. If ``mean`` is float, all elements of the output Tensor shared the same mean.
  752. If ``mean`` is a Tensor(data type supports float32, float64), it has per-element means.
  753. Default is 0.0
  754. std (float|Tensor, optional): The standard deviation of the output Tensor's normal distribution.
  755. If ``std`` is float, all elements of the output Tensor shared the same standard deviation.
  756. If ``std`` is a Tensor(data type supports float32, float64), it has per-element standard deviations.
  757. Default is 1.0
  758. name(str, optional): The default value is None. Normally there is no
  759. need for user to set this property. For more information, please
  760. refer to :ref:`api_guide_Name`.
  761. Returns:
  762. A Tensor filled with random values sampled from a normal distribution with ``mean`` and ``std`` .
  763. Examples:
  764. .. code-block:: python
  765. >>> import paddle
  766. >>> x = paddle.randn([3, 4])
  767. >>> x.normal_()
  768. >>> # doctest: +SKIP('random check')
  769. >>> print(x)
  770. Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
  771. [[ 0.06132207, 1.11349595, 0.41906244, -0.24858207],
  772. [-1.85169315, -1.50370061, 1.73954511, 0.13331604],
  773. [ 1.66359663, -0.55764782, -0.59911072, -0.57773495]])
  774. """
  775. return gaussian_(x, mean=mean, std=std)
  776. def uniform(shape, dtype=None, min=-1.0, max=1.0, seed=0, name=None):
  777. """
  778. Returns a Tensor filled with random values sampled from a uniform
  779. distribution in the range [``min``, ``max``), with ``shape`` and ``dtype``.
  780. Examples:
  781. .. code-block:: text
  782. Input:
  783. shape = [1, 2]
  784. Output:
  785. result=[[0.8505902, 0.8397286]]
  786. Args:
  787. shape (tuple|list|Tensor): Shape of the Tensor to be created. The data type is ``int32`` or ``int64`` .
  788. If ``shape`` is a list or tuple, each element of it should be integer or 0-D Tensor with shape [].
  789. If ``shape`` is an Tensor, it should be an 1-D Tensor which represents a list.
  790. dtype(str|np.dtype, optional): The data type of the output Tensor.
  791. Supported data types: float32, float64.
  792. Default is None, use global default dtype (see ``get_default_dtype``
  793. for details).
  794. min(float|int, optional): The lower bound on the range of random values
  795. to generate, ``min`` is included in the range. Default is -1.0.
  796. max(float|int, optional): The upper bound on the range of random values
  797. to generate, ``max`` is excluded in the range. Default is 1.0.
  798. seed(int, optional): Random seed used for generating samples. If seed is 0,
  799. it will use the seed of the global default generator (which can be set by paddle.seed).
  800. Note that if seed is not 0, this operator will always generate the same random numbers every
  801. time. Default is 0.
  802. name(str, optional): Name for the operation (optional, default is None).
  803. For more information, please refer to :ref:`api_guide_Name`.
  804. Returns:
  805. Tensor: A Tensor filled with random values sampled from a uniform
  806. distribution in the range [``min``, ``max``), with ``shape`` and ``dtype``.
  807. Examples:
  808. .. code-block:: python
  809. :name: code-example1
  810. >>> import paddle
  811. >>> # example 1:
  812. >>> # attr shape is a list which doesn't contain Tensor.
  813. >>> out1 = paddle.uniform(shape=[3, 4])
  814. >>> print(out1)
  815. >>> # doctest: +SKIP("Random output")
  816. Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
  817. [[ 0.38170254, -0.47945309, 0.39794648, -0.94233936],
  818. [-0.85296679, -0.76094693, 0.10565400, 0.59155810],
  819. [ 0.11681318, -0.42144555, -0.81596589, 0.62113667]])
  820. >>> # doctest: -SKIP
  821. >>> # example 2:
  822. >>> # attr shape is a list which contains Tensor.
  823. >>> dim1 = paddle.to_tensor(2, 'int64')
  824. >>> dim2 = paddle.to_tensor(3, 'int32')
  825. >>> out2 = paddle.uniform(shape=[dim1, dim2])
  826. >>> print(out2)
  827. >>> # doctest: +SKIP("Random output")
  828. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  829. [[-0.00294012, -0.07210171, -0.44236207],
  830. [ 0.70089281, 0.21500075, -0.22084606]])
  831. >>> # doctest: -SKIP
  832. >>> # example 3:
  833. >>> # attr shape is a Tensor, the data type must be int64 or int32.
  834. >>> shape_tensor = paddle.to_tensor([2, 3])
  835. >>> out3 = paddle.uniform(shape_tensor)
  836. >>> print(out3)
  837. >>> # doctest: +SKIP("Random output")
  838. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  839. [[-0.60801756, 0.32448411, 0.90269291],
  840. [-0.66421294, -0.95218551, -0.51022208]])
  841. >>> # doctest: -SKIP
  842. """
  843. supported_dtypes = ['float32', 'float64', 'float16', 'uint16']
  844. if dtype is None:
  845. dtype = paddle.framework.get_default_dtype()
  846. if dtype not in supported_dtypes:
  847. raise TypeError(
  848. f"uniform/rand only supports {supported_dtypes}, but the default dtype is {dtype}"
  849. )
  850. if not isinstance(dtype, (core.VarDesc.VarType, core.DataType)):
  851. dtype = convert_np_dtype_to_dtype_(dtype)
  852. if in_dynamic_mode():
  853. shape = paddle.utils.convert_shape_to_list(shape)
  854. return _C_ops.uniform(
  855. shape,
  856. dtype,
  857. float(min),
  858. float(max),
  859. seed,
  860. _current_expected_place(),
  861. )
  862. elif in_pir_mode():
  863. check_type(
  864. shape, 'shape', (list, tuple, paddle.pir.Value), 'uniform/rand'
  865. )
  866. check_dtype(dtype, 'dtype', supported_dtypes, 'uniform/rand')
  867. check_type(min, 'min', (float, int, paddle.pir.Value), 'uniform/rand')
  868. check_type(max, 'max', (float, int, paddle.pir.Value), 'uniform/rand')
  869. if paddle.utils._contain_var(shape):
  870. shape = paddle.utils.get_int_tensor_list(shape)
  871. return _C_ops.uniform(
  872. shape,
  873. dtype,
  874. float(min),
  875. float(max),
  876. seed,
  877. _current_expected_place(),
  878. )
  879. else:
  880. check_type(shape, 'shape', (list, tuple, Variable), 'uniform/rand')
  881. check_dtype(dtype, 'dtype', supported_dtypes, 'uniform/rand')
  882. check_type(min, 'min', (float, int, Variable), 'uniform/rand')
  883. check_type(max, 'max', (float, int, Variable), 'uniform/rand')
  884. inputs = {}
  885. attrs = {'seed': seed, 'min': min, 'max': max, 'dtype': dtype}
  886. paddle.utils.get_shape_tensor_inputs(
  887. inputs=inputs, attrs=attrs, shape=shape, op_type='uniform/rand'
  888. )
  889. helper = LayerHelper("uniform", **locals())
  890. out = helper.create_variable_for_type_inference(dtype)
  891. helper.append_op(
  892. type="uniform_random",
  893. inputs=inputs,
  894. attrs=attrs,
  895. outputs={"Out": out},
  896. )
  897. out.stop_gradient = True
  898. return out
  899. @dygraph_only
  900. def uniform_(x, min=-1.0, max=1.0, seed=0, name=None):
  901. """
  902. This is the inplace version of OP ``uniform``, which returns a Tensor filled
  903. with random values sampled from a uniform distribution. The output Tensor will
  904. be inplaced with input ``x``. Please refer to :ref:`api_paddle_uniform`.
  905. Args:
  906. x(Tensor): The input tensor to be filled with random values.
  907. min(float|int, optional): The lower bound on the range of random values
  908. to generate, ``min`` is included in the range. Default is -1.0.
  909. max(float|int, optional): The upper bound on the range of random values
  910. to generate, ``max`` is excluded in the range. Default is 1.0.
  911. seed(int, optional): Random seed used for generating samples. If seed is 0,
  912. it will use the seed of the global default generator (which can be set by paddle.seed).
  913. Note that if seed is not 0, this operator will always generate the same random numbers every
  914. time. Default is 0.
  915. name(str, optional): The default value is None. Normally there is no
  916. need for user to set this property. For more information, please
  917. refer to :ref:`api_guide_Name`.
  918. Returns:
  919. Tensor: The input tensor x filled with random values sampled from a uniform
  920. distribution in the range [``min``, ``max``).
  921. Examples:
  922. .. code-block:: python
  923. >>> import paddle
  924. >>> # example:
  925. >>> x = paddle.ones(shape=[3, 4])
  926. >>> x.uniform_()
  927. >>> # doctest: +SKIP("Random output")
  928. Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
  929. [[-0.50484276, 0.49580324, 0.33357990, -0.93924278],
  930. [ 0.39779735, 0.87677515, -0.24377221, 0.06212139],
  931. [-0.92499518, -0.96244860, 0.79210341, -0.78228098]])
  932. >>> # doctest: -SKIP
  933. """
  934. return _C_ops.uniform_inplace_(x, min, max, seed, 0, 0, 1.0)
  935. def randint(low=0, high=None, shape=[1], dtype=None, name=None):
  936. """
  937. Returns a Tensor filled with random integers from a discrete uniform
  938. distribution in the range [``low``, ``high``), with ``shape`` and ``dtype``.
  939. If ``high`` is None (the default), the range is [0, ``low``).
  940. Args:
  941. low (int, optional): The lower bound on the range of random values to generate.
  942. The ``low`` is included in the range. If ``high`` is None, the
  943. range is [0, ``low``). Default is 0.
  944. high (int, optional): The upper bound on the range of random values to
  945. generate, the ``high`` is excluded in the range. Default is None
  946. (see above for behavior if high = None). Default is None.
  947. shape (tuple|list|Tensor): Shape of the Tensor to be created. The data type is ``int32`` or ``int64`` .
  948. If ``shape`` is a list or tuple, each element of it should be integer or 0-D Tensor with shape [].
  949. If ``shape`` is an Tensor, it should be an 1-D Tensor which represents a list. Default is [1].
  950. dtype (str|np.dtype, optional): The data type of the
  951. output tensor. Supported data types: int32, int64. If ``dtype``
  952. is None, the data type is int64. Default is None.
  953. name (str, optional): The default value is None. Normally there is no
  954. need for user to set this property. For more information, please
  955. refer to :ref:`api_guide_Name`.
  956. Returns:
  957. Tensor: A Tensor filled with random integers from a discrete uniform
  958. distribution in the range [``low``, ``high``), with ``shape`` and ``dtype``.
  959. Examples:
  960. .. code-block:: python
  961. >>> import paddle
  962. >>> # example 1:
  963. >>> # attr shape is a list which doesn't contain Tensor.
  964. >>> out1 = paddle.randint(low=-5, high=5, shape=[2, 3])
  965. >>> print(out1)
  966. >>> # doctest: +SKIP("Random output")
  967. Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  968. [[-1, 4, 4],
  969. [-2, -5, -2]])
  970. >>> # doctest: -SKIP
  971. >>> # example 2:
  972. >>> # attr shape is a list which contains Tensor.
  973. >>> dim1 = paddle.to_tensor(2, 'int64')
  974. >>> dim2 = paddle.to_tensor(3, 'int32')
  975. >>> out2 = paddle.randint(low=-5, high=5, shape=[dim1, dim2])
  976. >>> print(out2)
  977. >>> # doctest: +SKIP("Random output")
  978. Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  979. [[-4, -4, 2],
  980. [-3, -1, -5]])
  981. >>> # doctest: -SKIP
  982. >>> # example 3:
  983. >>> # attr shape is a Tensor
  984. >>> shape_tensor = paddle.to_tensor([2, 3])
  985. >>> out3 = paddle.randint(low=-5, high=5, shape=shape_tensor)
  986. >>> print(out3)
  987. >>> # doctest: +SKIP("Random output")
  988. Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  989. [[-1, 4, -3],
  990. [ 1, 2, -1]])
  991. >>> # doctest: -SKIP
  992. >>> # example 4:
  993. >>> # data type is int32
  994. >>> out4 = paddle.randint(low=-5, high=5, shape=[3], dtype='int32')
  995. >>> print(out4)
  996. >>> # doctest: +SKIP("Random output")
  997. Tensor(shape=[3], dtype=int32, place=Place(cpu), stop_gradient=True,
  998. [4, 4, 0])
  999. >>> # doctest: -SKIP
  1000. >>> # example 5:
  1001. >>> # Input only one parameter
  1002. >>> # low=0, high=10, shape=[1], dtype='int64'
  1003. >>> out5 = paddle.randint(10)
  1004. >>> print(out5)
  1005. >>> # doctest: +SKIP("Random output")
  1006. Tensor(shape=[1], dtype=int64, place=Place(cpu), stop_gradient=True,
  1007. [7])
  1008. >>> # doctest: -SKIP
  1009. """
  1010. if high is None:
  1011. if low <= 0:
  1012. raise ValueError(
  1013. f"If high is None, low must be greater than 0, but received low = {low}."
  1014. )
  1015. high = low
  1016. low = 0
  1017. if dtype is None:
  1018. dtype = core.VarDesc.VarType.INT64
  1019. if use_pir_api():
  1020. dtype = DataType.INT64
  1021. elif not isinstance(dtype, (core.VarDesc.VarType, core.DataType)):
  1022. dtype = convert_np_dtype_to_dtype_(dtype)
  1023. if in_dynamic_mode():
  1024. shape = paddle.utils.convert_shape_to_list(shape)
  1025. return _C_ops.randint(
  1026. low, high, shape, dtype, _current_expected_place()
  1027. )
  1028. elif in_pir_mode():
  1029. check_shape(shape, 'randint')
  1030. check_dtype(dtype, 'dtype', ['int32', 'int64'], 'randint')
  1031. if paddle.utils._contain_var(shape):
  1032. shape = paddle.utils.get_int_tensor_list(shape)
  1033. return _C_ops.randint(
  1034. low, high, shape, dtype, _current_expected_place()
  1035. )
  1036. else:
  1037. check_shape(shape, 'randint')
  1038. check_dtype(dtype, 'dtype', ['int32', 'int64'], 'randint')
  1039. if low >= high:
  1040. raise ValueError(
  1041. f"randint's low must less then high, but received low = {low}, "
  1042. f"high = {high}"
  1043. )
  1044. inputs = {}
  1045. attrs = {'low': low, 'high': high, 'seed': 0, 'dtype': dtype}
  1046. paddle.utils.get_shape_tensor_inputs(
  1047. inputs=inputs, attrs=attrs, shape=shape, op_type='randint'
  1048. )
  1049. helper = LayerHelper("randint", **locals())
  1050. out = helper.create_variable_for_type_inference(dtype=dtype)
  1051. helper.append_op(
  1052. type='randint', inputs=inputs, outputs={'Out': out}, attrs=attrs
  1053. )
  1054. out.stop_gradient = True
  1055. return out
  1056. def randint_like(x, low=0, high=None, dtype=None, name=None):
  1057. """
  1058. Returns a Tensor filled with random integers from a discrete uniform
  1059. distribution in the range [``low``, ``high``), with the same shape as ``x``.
  1060. (use ``dtype`` if ``dtype`` is not None)
  1061. If ``high`` is None (the default), the range is [0, ``low``).
  1062. Args:
  1063. x (Tensor): The input multi-dimensional tensor which specifies shape. The dtype of ``x``
  1064. can be bool, int32, int64, float16, float32, float64.
  1065. low (int, optional): The lower bound on the range of random values to generate.
  1066. The ``low`` is included in the range. If ``high`` is None, the
  1067. range is [0, ``low``). Default is 0.
  1068. high (int, optional): The upper bound on the range of random values to
  1069. generate, the ``high`` is excluded in the range. Default is None.
  1070. If ``high`` is None, the range is [0, ``low``).
  1071. dtype (str|np.dtype, optional): The data type of the
  1072. output tensor. Supported data types: bool, int32, int64, float16,
  1073. float32, float64. If ``dtype`` is None, the data type is the
  1074. same as x's data type. Default is None.
  1075. name (str, optional): The default value is None. Normally there is no
  1076. need for user to set this property. For more information, please
  1077. refer to :ref:`api_guide_Name`.
  1078. Returns:
  1079. Tensor: A Tensor filled with random integers from a discrete uniform
  1080. distribution in the range [``low``, ``high``), with ``shape`` and ``dtype``.
  1081. Examples:
  1082. .. code-block:: python
  1083. >>> import paddle
  1084. >>> # example 1:
  1085. >>> # dtype is None and the dtype of x is float32
  1086. >>> x = paddle.zeros((1,2)).astype("float32")
  1087. >>> out2 = paddle.randint_like(x, low=-5, high=5)
  1088. >>> print(out2)
  1089. >>> # doctest: +SKIP("Random output")
  1090. Tensor(shape=[1, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  1091. [[0., 0.]])
  1092. >>> # doctest: -SKIP
  1093. >>> print(out2.dtype)
  1094. paddle.float32
  1095. >>> # example 2:
  1096. >>> # dtype is None and the dtype of x is float64
  1097. >>> x = paddle.zeros((1,2)).astype("float64")
  1098. >>> out2 = paddle.randint_like(x, low=-5, high=5)
  1099. >>> print(out2)
  1100. >>> # doctest: +SKIP("Random output")
  1101. Tensor(shape=[1, 2], dtype=float64, place=Place(cpu), stop_gradient=True,
  1102. [[ 4., -5.]])
  1103. >>> # doctest: -SKIP
  1104. >>> print(out2.dtype)
  1105. paddle.float64
  1106. >>> # example 3:
  1107. >>> # dtype is None and the dtype of x is int32
  1108. >>> x = paddle.zeros((1,2)).astype("int32")
  1109. >>> out3 = paddle.randint_like(x, low=-5, high=5)
  1110. >>> print(out3)
  1111. >>> # doctest: +SKIP("Random output")
  1112. Tensor(shape=[1, 2], dtype=int32, place=Place(cpu), stop_gradient=True,
  1113. [[ 0, -4]])
  1114. >>> # doctest: -SKIP
  1115. >>> print(out3.dtype)
  1116. paddle.int32
  1117. >>> # example 4:
  1118. >>> # dtype is None and the dtype of x is int64
  1119. >>> x = paddle.zeros((1,2)).astype("int64")
  1120. >>> out4 = paddle.randint_like(x, low=-5, high=5)
  1121. >>> print(out4)
  1122. >>> # doctest: +SKIP("Random output")
  1123. Tensor(shape=[1, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
  1124. [[ 4, -3]])
  1125. >>> # doctest: -SKIP
  1126. >>> print(out4.dtype)
  1127. paddle.int64
  1128. >>> # example 5:
  1129. >>> # dtype is float64 and the dtype of x is float32
  1130. >>> x = paddle.zeros((1,2)).astype("float32")
  1131. >>> out5 = paddle.randint_like(x, low=-5, high=5, dtype="float64")
  1132. >>> print(out5)
  1133. >>> # doctest: +SKIP("Random output")
  1134. Tensor(shape=[1, 2], dtype=float64, place=Place(cpu), stop_gradient=True,
  1135. [[3., 1.]])
  1136. >>> # doctest: -SKIP
  1137. >>> print(out5.dtype)
  1138. paddle.float64
  1139. >>> # example 6:
  1140. >>> # dtype is bool and the dtype of x is float32
  1141. >>> x = paddle.zeros((1,2)).astype("float32")
  1142. >>> out6 = paddle.randint_like(x, low=-5, high=5, dtype="bool")
  1143. >>> print(out6)
  1144. >>> # doctest: +SKIP("Random output")
  1145. Tensor(shape=[1, 2], dtype=bool, place=Place(cpu), stop_gradient=True,
  1146. [[False, True ]])
  1147. >>> # doctest: -SKIP
  1148. >>> print(out6.dtype)
  1149. paddle.bool
  1150. >>> # example 7:
  1151. >>> # dtype is int32 and the dtype of x is float32
  1152. >>> x = paddle.zeros((1,2)).astype("float32")
  1153. >>> out7 = paddle.randint_like(x, low=-5, high=5, dtype="int32")
  1154. >>> print(out7)
  1155. >>> # doctest: +SKIP("Random output")
  1156. Tensor(shape=[1, 2], dtype=int32, place=Place(cpu), stop_gradient=True,
  1157. [[-2, -2]])
  1158. >>> # doctest: -SKIP
  1159. >>> print(out7.dtype)
  1160. paddle.int32
  1161. >>> # example 8:
  1162. >>> # dtype is int64 and the dtype of x is float32
  1163. >>> x = paddle.zeros((1,2)).astype("float32")
  1164. >>> out8 = paddle.randint_like(x, low=-5, high=5, dtype="int64")
  1165. >>> print(out8)
  1166. >>> # doctest: +SKIP("Random output")
  1167. Tensor(shape=[1, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
  1168. [[-5, 4]])
  1169. >>> # doctest: -SKIP
  1170. >>> print(out8.dtype)
  1171. paddle.int64
  1172. >>> # example 9:
  1173. >>> # dtype is int64 and the dtype of x is bool
  1174. >>> x = paddle.zeros((1,2)).astype("bool")
  1175. >>> out9 = paddle.randint_like(x, low=-5, high=5, dtype="int64")
  1176. >>> print(out9)
  1177. >>> # doctest: +SKIP("Random output")
  1178. Tensor(shape=[1, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
  1179. [[ 1, -2]])
  1180. >>> # doctest: -SKIP
  1181. >>> print(out9.dtype)
  1182. paddle.int64
  1183. """
  1184. if high is None:
  1185. if low <= 0:
  1186. raise ValueError(
  1187. f"If high is None, low must be greater than 0, but received low = {low}."
  1188. )
  1189. high = low
  1190. low = 0
  1191. if dtype is None:
  1192. dtype = x.dtype
  1193. else:
  1194. if not isinstance(dtype, (core.VarDesc.VarType, core.DataType)):
  1195. dtype = convert_np_dtype_to_dtype_(dtype)
  1196. shape = paddle.shape(x)
  1197. if low >= high:
  1198. raise ValueError(
  1199. f"randint_like's low must less then high, but received low = {low}, "
  1200. f"high = {high}"
  1201. )
  1202. if in_dynamic_or_pir_mode():
  1203. if in_dynamic_mode():
  1204. shape = paddle.utils.convert_shape_to_list(shape)
  1205. out = _legacy_C_ops.randint(
  1206. 'shape',
  1207. shape,
  1208. 'low',
  1209. low,
  1210. 'high',
  1211. high,
  1212. 'seed',
  1213. 0,
  1214. 'dtype',
  1215. core.VarDesc.VarType.INT64,
  1216. )
  1217. else:
  1218. check_type(
  1219. shape,
  1220. 'shape',
  1221. (list, tuple, paddle.pir.Value),
  1222. 'randint_like',
  1223. )
  1224. check_dtype(
  1225. dtype,
  1226. 'dtype',
  1227. ['bool', 'float16', 'float32', 'float64', 'int32', 'int64'],
  1228. 'randint_like',
  1229. )
  1230. if paddle.utils._contain_var(shape):
  1231. shape = paddle.utils.get_int_tensor_list(shape)
  1232. out = _C_ops.randint(
  1233. low, high, shape, DataType.INT64, _current_expected_place()
  1234. )
  1235. out = paddle.cast(out, dtype)
  1236. return out
  1237. else:
  1238. check_shape(shape, 'randint_like')
  1239. check_dtype(
  1240. dtype,
  1241. 'dtype',
  1242. ['bool', 'float16', 'float32', 'float64', 'int32', 'int64'],
  1243. 'randint_like',
  1244. )
  1245. inputs = {"ShapeTensor": shape}
  1246. attrs = {
  1247. 'low': low,
  1248. 'high': high,
  1249. 'seed': 0,
  1250. 'dtype': core.VarDesc.VarType.INT64,
  1251. }
  1252. helper = LayerHelper("randint", **locals())
  1253. out = helper.create_variable_for_type_inference(
  1254. dtype=core.VarDesc.VarType.INT64
  1255. )
  1256. helper.append_op(
  1257. type='randint', inputs=inputs, outputs={'Out': out}, attrs=attrs
  1258. )
  1259. out.stop_gradient = True
  1260. out = paddle.cast(out, dtype)
  1261. return out
  1262. def randperm(n, dtype="int64", name=None):
  1263. """
  1264. Returns a 1-D Tensor filled with random permutation values from 0
  1265. to n-1, with ``dtype``.
  1266. Args:
  1267. n (int): The upper bound (exclusive), and it should be greater than 0.
  1268. dtype (str|np.dtype, optional): The data type of
  1269. the output Tensor. Supported data types: int32, int64, float32,
  1270. float64. Default is int64.
  1271. name (str, optional): The default value is None. Normally there is no
  1272. need for user to set this property. For more information, please
  1273. refer to :ref:`api_guide_Name`.
  1274. Returns:
  1275. Tensor: A 1-D Tensor filled with random permutation values from 0
  1276. to n-1, with ``dtype``.
  1277. Examples:
  1278. .. code-block:: python
  1279. >>> import paddle
  1280. >>> out1 = paddle.randperm(5)
  1281. >>> print(out1)
  1282. >>> # doctest: +SKIP("Random output")
  1283. Tensor(shape=[5], dtype=int64, place=Place(cpu), stop_gradient=True,
  1284. [3, 0, 1, 4, 2])
  1285. >>> #doctest: -SKIP
  1286. >>> out2 = paddle.randperm(7, 'int32')
  1287. >>> print(out2)
  1288. >>> # doctest: +SKIP("Random output")
  1289. Tensor(shape=[7], dtype=int32, place=Place(cpu), stop_gradient=True,
  1290. [3, 2, 0, 6, 5, 4, 1])
  1291. >>> #doctest: -SKIP
  1292. """
  1293. if not isinstance(dtype, (core.VarDesc.VarType, paddle.pir.core.DataType)):
  1294. dtype = convert_np_dtype_to_dtype_(dtype)
  1295. if in_dynamic_or_pir_mode():
  1296. return _C_ops.randperm(n, dtype, _current_expected_place())
  1297. else:
  1298. if n < 1:
  1299. raise ValueError(
  1300. "The input n should be greater than 0 in randperm op."
  1301. )
  1302. check_dtype(
  1303. dtype, 'dtype', ['int64', 'int32', 'float32', 'float64'], 'randperm'
  1304. )
  1305. helper = LayerHelper("randperm", **locals())
  1306. out = helper.create_variable_for_type_inference(dtype)
  1307. attrs = {'n': n, 'dtype': dtype, 'seed': 0}
  1308. helper.append_op(
  1309. type='randperm', inputs={}, outputs={'Out': out}, attrs=attrs
  1310. )
  1311. out.stop_gradient = True
  1312. return out
  1313. def rand(shape, dtype=None, name=None):
  1314. """
  1315. Returns a Tensor filled with random values sampled from a uniform
  1316. distribution in the range [0, 1), with ``shape`` and ``dtype``.
  1317. Args:
  1318. shape (tuple|list|Tensor): Shape of the Tensor to be created. The data type is ``int32`` or ``int64`` .
  1319. If ``shape`` is a list or tuple, each element of it should be integer or 0-D Tensor with shape [].
  1320. If ``shape`` is an Tensor, it should be an 1-D Tensor which represents a list.
  1321. dtype (str|np.dtype, optional): The data type of the output Tensor.
  1322. Supported data types: float32, float64.
  1323. Default is None, use global default dtype (see :ref:`get_default_dtype`
  1324. for details).
  1325. name (str, optional): The default value is None. Normally there is no
  1326. need for user to set this property. For more information, please
  1327. refer to :ref:`api_guide_Name`.
  1328. Returns:
  1329. Tensor: A Tensor filled with random values sampled from a uniform
  1330. distribution in the range [0, 1), with ``shape`` and ``dtype``.
  1331. Examples:
  1332. .. code-block:: python
  1333. >>> import paddle
  1334. >>> # example 1: attr shape is a list which doesn't contain Tensor.
  1335. >>> out1 = paddle.rand(shape=[2, 3])
  1336. >>> print(out1)
  1337. >>> # doctest: +SKIP("Random output")
  1338. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  1339. [[0.68532258, 0.69431782, 0.44835982],
  1340. [0.13204314, 0.48128194, 0.36574543]])
  1341. >>> # doctest: -SKIP
  1342. >>> # example 2: attr shape is a list which contains Tensor.
  1343. >>> dim1 = paddle.to_tensor(2, 'int64')
  1344. >>> dim2 = paddle.to_tensor(3, 'int32')
  1345. >>> out2 = paddle.rand(shape=[dim1, dim2, 2])
  1346. >>> print(out2)
  1347. >>> # doctest: +SKIP("Random output")
  1348. Tensor(shape=[2, 3, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  1349. [[[0.62102991, 0.45255184],
  1350. [0.81386960, 0.22463219],
  1351. [0.87946558, 0.28097662]],
  1352. [[0.36565998, 0.63203937],
  1353. [0.58640617, 0.92696166],
  1354. [0.85060406, 0.38138932]]])
  1355. >>> # doctest: -SKIP
  1356. >>> # example 3: attr shape is a Tensor, the data type must be int64 or int32.
  1357. >>> shape_tensor = paddle.to_tensor([2, 3])
  1358. >>> out3 = paddle.rand(shape_tensor)
  1359. >>> print(out3)
  1360. >>> # doctest: +SKIP("Random output")
  1361. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  1362. [[0.77650446, 0.12870903, 0.05153799],
  1363. [0.27029657, 0.03963696, 0.42487794]])
  1364. >>> # doctest: -SKIP
  1365. """
  1366. return uniform(shape, dtype, min=0.0, max=1.0, name=name)
  1367. def exponential_(x, lam=1.0, name=None):
  1368. r"""
  1369. This inplace OP fill input Tensor ``x`` with random number from a Exponential Distribution.
  1370. ``lam`` is :math:`\lambda` parameter of Exponential Distribution.
  1371. .. math::
  1372. f(x) = \lambda e^{-\lambda x}
  1373. Args:
  1374. x(Tensor): Input tensor. The data type should be float32, float64.
  1375. lam(float, optional): :math:`\lambda` parameter of Exponential Distribution. Default, 1.0.
  1376. name(str, optional): The default value is None. Normally there is no
  1377. need for user to set this property. For more information, please
  1378. refer to :ref:`api_guide_Name`.
  1379. Returns:
  1380. Tensor: Input Tensor ``x``.
  1381. Examples:
  1382. .. code-block:: python
  1383. >>> import paddle
  1384. >>> paddle.set_device('cpu')
  1385. >>> paddle.seed(100)
  1386. >>> x = paddle.empty([2,3])
  1387. >>> x.exponential_()
  1388. >>> # doctest: +SKIP("Random output")
  1389. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  1390. [[0.80643415, 0.23211166, 0.01169797],
  1391. [0.72520679, 0.45208144, 0.30234432]])
  1392. >>> # doctest: -SKIP
  1393. """
  1394. if in_dynamic_or_pir_mode():
  1395. return _C_ops.exponential_(x, lam)
  1396. else:
  1397. check_variable_and_dtype(
  1398. x, "x", ["float16", "float32", "float64", "uint16"], "exponential"
  1399. )
  1400. helper = LayerHelper("exponential", **locals())
  1401. helper.append_op(
  1402. type='exponential',
  1403. inputs={"X": x},
  1404. outputs={'Out': x},
  1405. attrs={"lambda": lam},
  1406. )
  1407. return x