You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

random_ops.py 11 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  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. # ============================================================================
  15. """Operations for random number generators."""
  16. from mindspore.ops.primitive import constexpr
  17. from .. import operations as P
  18. from .. import functional as F
  19. from .multitype_ops import _constexpr_utils as const_utils
  20. from ...common import dtype as mstype
  21. from ...common import _get_seed
  22. @constexpr
  23. def get_seed(op_seed, kernel_name):
  24. "Get the graph-level seed."
  25. return _get_seed(op_seed, kernel_name)
  26. def normal(shape, mean, stddev, seed=None):
  27. """
  28. Generates random numbers according to the Normal (or Gaussian) random number distribution.
  29. Args:
  30. shape (tuple): The shape of random tensor to be generated.
  31. mean (Tensor): The mean μ distribution parameter, which specifies the location of the peak,
  32. with data type in [int8, int16, int32, int64, float16, float32].
  33. stddev (Tensor): The deviation σ distribution parameter. It should be greater than 0,
  34. with data type in [int8, int16, int32, int64, float16, float32].
  35. seed (int): Seed is used as entropy source for the Random number engines to generate pseudo-random numbers.
  36. must be non-negative. Default: None, which will be treated as 0.
  37. Returns:
  38. Tensor. The shape should be equal to the broadcasted shape between the input `shape` and shapes
  39. of `mean` and `stddev`.
  40. The dtype is float32.
  41. Examples:
  42. >>> shape = (2, 4)
  43. >>> mean = Tensor(1.0, mstype.float32)
  44. >>> stddev = Tensor(1.0, mstype.float32)
  45. >>> output = C.normal(shape, mean, stddev, seed=5)
  46. [[1.0996436 0.44371283 0.11127508 -0.48055804]
  47. [0.31989878 -1.0644426 1.5076542 1.2290289 ]]
  48. """
  49. mean_dtype = F.dtype(mean)
  50. stddev_dtype = F.dtype(stddev)
  51. const_utils.check_valid_type(mean_dtype, mstype.int_type + (mstype.float16, mstype.float32), 'normal')
  52. const_utils.check_valid_type(stddev_dtype, mstype.int_type + (mstype.float16, mstype.float32), 'normal')
  53. seed1, seed2 = get_seed(seed, "normal")
  54. stdnormal = P.StandardNormal(seed1, seed2)
  55. random_normal = stdnormal(shape)
  56. value = random_normal * stddev + mean
  57. return value
  58. def laplace(shape, mean, lambda_param, seed=None):
  59. r"""
  60. Generates random numbers according to the Laplace random number distribution.
  61. It is defined as:
  62. .. math::
  63. \text{f}(x;μ,λ) = \frac{1}{2λ}\exp(-\frac{|x-μ|}{λ}),
  64. Args:
  65. shape (tuple): The shape of random tensor to be generated.
  66. mean (Tensor): The mean μ distribution parameter, which specifies the location of the peak.
  67. With float32 data type.
  68. lambda_param (Tensor): The parameter used for controling the variance of this random distribution. The
  69. variance of Laplace distribution is equal to twice the square of lambda_param. With float32 data type.
  70. seed (int): Seed is used as entropy source for Random number engines generating pseudo-random numbers.
  71. Default: None, which will be treated as 0.
  72. Returns:
  73. Tensor. The shape should be the broadcasted shape of Input "shape" and shapes of mean and lambda_param.
  74. The dtype is float32.
  75. Examples:
  76. >>> shape = (4, 16)
  77. >>> mean = Tensor(1.0, mstype.float32)
  78. >>> lambda_param = Tensor(1.0, mstype.float32)
  79. >>> output = C.laplace(shape, mean, lambda_param, seed=5)
  80. """
  81. mean_dtype = F.dtype(mean)
  82. lambda_param_dtype = F.dtype(lambda_param)
  83. const_utils.check_tensors_dtype_same(mean_dtype, mstype.float32, "laplace")
  84. const_utils.check_tensors_dtype_same(lambda_param_dtype, mstype.float32, "laplace")
  85. seed1, seed2 = get_seed(seed, "laplace")
  86. stdlaplace = P.StandardLaplace(seed1, seed2)
  87. rnd = stdlaplace(shape)
  88. value = rnd * lambda_param + mean
  89. return value
  90. def uniform(shape, minval, maxval, seed=None, dtype=mstype.float32):
  91. """
  92. Generates random numbers according to the Uniform random number distribution.
  93. Note:
  94. The number in tensor minval should be strictly less than maxval at any position after broadcasting.
  95. Args:
  96. shape (tuple): The shape of random tensor to be generated.
  97. minval (Tensor): The distribution parameter `a`.
  98. It defines the minimum possible generated value, with int32 or float32 data type.
  99. If dtype is int32, only one number is allowed.
  100. maxval (Tensor): The distribution parameter `b`.
  101. It defines the maximum possible generated value, with int32 or float32 data type.
  102. If dtype is int32, only one number is allowed.
  103. seed (int): Seed is used as entropy source for the random number engines to generate pseudo-random numbers,
  104. must be non-negative. Default: None, which will be treated as 0.
  105. dtype (mindspore.dtype): type of the Uniform distribution. If it is int32, it generates numbers from discrete
  106. uniform distribution; if it is float32, it generates numbers from continuous uniform distribution. It only
  107. supports these two data types. Default: mstype.float32.
  108. Returns:
  109. Tensor. The shape should be equal to the broadcasted shape between the input `shape` and shapes
  110. of `minval` and `maxval`.
  111. The dtype is designated as the input `dtype`.
  112. Examples:
  113. >>> For discrete uniform distribution, only one number is allowed for both minval and maxval:
  114. >>> shape = (4, 2)
  115. >>> minval = Tensor(1, mstype.int32)
  116. >>> maxval = Tensor(2, mstype.int32)
  117. >>> output = C.uniform(shape, minval, maxval, seed=5)
  118. >>>
  119. >>> For continuous uniform distribution, minval and maxval can be multi-dimentional:
  120. >>> shape = (4, 2)
  121. >>> minval = Tensor([1.0, 2.0], mstype.float32)
  122. >>> maxval = Tensor([4.0, 5.0], mstype.float32)
  123. >>> output = C.uniform(shape, minval, maxval, seed=5)
  124. """
  125. minval_dtype = F.dtype(minval)
  126. maxval_dtype = F.dtype(maxval)
  127. const_utils.check_valid_type(dtype, [mstype.int32, mstype.float32], 'uniform')
  128. const_utils.check_tensors_dtype_same(minval_dtype, dtype, "uniform")
  129. const_utils.check_tensors_dtype_same(maxval_dtype, dtype, "uniform")
  130. seed1, seed2 = get_seed(seed, "uniform")
  131. if const_utils.is_same_type(dtype, mstype.int32):
  132. random_uniform = P.UniformInt(seed1, seed2)
  133. value = random_uniform(shape, minval, maxval)
  134. else:
  135. uniform_real = P.UniformReal(seed1, seed2)
  136. random_uniform = uniform_real(shape)
  137. value = random_uniform * (maxval - minval) + minval
  138. return value
  139. def gamma(shape, alpha, beta, seed=None):
  140. """
  141. Generates random numbers according to the Gamma random number distribution.
  142. Args:
  143. shape (tuple): The shape of random tensor to be generated.
  144. alpha (Tensor): The alpha α distribution parameter. It should be greater than 0 with float32 data type.
  145. beta (Tensor): The beta β distribution parameter. It should be greater than 0 with float32 data type.
  146. seed (int): Seed is used as entropy source for the random number engines to generate
  147. pseudo-random numbers, must be non-negative. Default: None, which will be treated as 0.
  148. Returns:
  149. Tensor. The shape should be equal to the broadcasted shape between the input "shape" and shapes
  150. of `alpha` and `beta`.
  151. The dtype is float32.
  152. Examples:
  153. >>> shape = (4, 16)
  154. >>> alpha = Tensor(1.0, mstype.float32)
  155. >>> beta = Tensor(1.0, mstype.float32)
  156. >>> output = C.gamma(shape, alpha, beta, seed=5)
  157. """
  158. seed1, seed2 = get_seed(seed, "gamma")
  159. random_gamma = P.Gamma(seed1, seed2)
  160. value = random_gamma(shape, alpha, beta)
  161. return value
  162. def poisson(shape, mean, seed=None):
  163. """
  164. Generates random numbers according to the Poisson random number distribution.
  165. Args:
  166. shape (tuple): The shape of random tensor to be generated.
  167. mean (Tensor): The mean μ distribution parameter. It should be greater than 0 with float32 data type.
  168. seed (int): Seed is used as entropy source for the random number engines to generate pseudo-random numbers
  169. and must be non-negative. Default: None, which will be treated as 0.
  170. Returns:
  171. Tensor. The shape should be equal to the broadcasted shape between the input "shape" and shapes of `mean`.
  172. The dtype is float32.
  173. Examples:
  174. >>> shape = (4, 16)
  175. >>> mean = Tensor(1.0, mstype.float32)
  176. >>> output = C.poisson(shape, mean, seed=5)
  177. """
  178. seed1, seed2 = get_seed(seed, "poisson")
  179. random_poisson = P.Poisson(seed1, seed2)
  180. value = random_poisson(shape, mean)
  181. return value
  182. def multinomial(inputs, num_sample, replacement=True, seed=0):
  183. r"""
  184. Returns a tensor sampled from the multinomial probability distribution located in the corresponding
  185. row of the input tensor.
  186. Note:
  187. The rows of input do not need to sum to one (in which case we use the values as weights),
  188. but must be non-negative, finite and have a non-zero sum.
  189. Args:
  190. inputs (Tensor): The input tensor containing probabilities, must be 1 or 2 dimensions, with
  191. float32 data type.
  192. num_sample (int): Number of samples to draw.
  193. replacement (bool, optional): Whether to draw with replacement or not, default True.
  194. seed (int, optional): Seed is used as entropy source for the random number engines to generate
  195. pseudo-random numbers, must be non-negative. Default: 0.
  196. Outputs:
  197. Tensor, has the same rows with input. The number of sampled indices of each row is `num_samples`.
  198. The dtype is float32.
  199. Examples:
  200. >>> input = Tensor([0, 9, 4, 0], mstype.float32)
  201. >>> output = C.multinomial(input, 2, True)
  202. """
  203. shape = P.Shape()
  204. reshape = P.Reshape()
  205. if inputs.dim() != 1 and inputs.dim() != 2:
  206. const_utils.raise_value_error("inputs dim must be 1d or 2d")
  207. if not replacement:
  208. if shape(inputs)[-1] < num_sample:
  209. const_utils.raise_value_error("num_sample must be less than shape(input)[-1] without replacement")
  210. n_dist = 1
  211. if len(shape(inputs)) > 1:
  212. n_dist = shape(inputs)[-2]
  213. random_uniform = P.UniformReal(seed=seed)((n_dist * shape(inputs)[-1],))
  214. if n_dist != 1:
  215. random_uniform = reshape(random_uniform, (n_dist, shape(inputs)[-1]))
  216. vals = P.RealDiv()(P.Log()(random_uniform), inputs + 1e-6)
  217. _, indices = P.TopK()(vals, num_sample)
  218. return indices
  219. return P.Multinomial(seed=seed)(inputs, num_sample)