tensorflow 生成随机数 tf.random_normal 和 tf.random_uniform 和 tf.truncated_normal 和 tf.random_shuffle

____tz_zs

tf.random_normal

从正态分布中输出随机值。

.

[python]view plaincopy

  1. <span >random_normal(shape,mean=0.0,stddev=1.0,dtype=tf.float32,seed=None,name=None)</span>

.

  • shape:一个一维整数张量或Python数组。代表张量的形状。
  • mean:数据类型为dtype的张量值或Python值。是正态分布的均值。
  • stddev:数据类型为dtype的张量值或Python值。是正态分布的标准差。
  • dtype: 输出的数据类型。
  • seed:一个Python整数。是随机种子。
  • name: 操作的名称(可选)

官网api地址:https://www.tensorflow.org/versions/r1.3/api_docs/python/tf/random_normal

tf.random_uniform

从均匀分布中返回随机值。

.

[python]view plaincopy

  1. random_uniform(
  2. shape,# 生成的张量的形状
  3. minval=0,
  4. maxval=None,
  5. dtype=tf.float32,
  6. seed=None,
  7. name=None
  8. )

.

返回值的范围默认是0到1的左闭右开区间,即[0,1)。minval为指定最小边界,默认为1。maxval为指定的最大边界,如果是数据浮点型则默认为1,如果数据为整形则必须指定。

官网api地址:https://www.tensorflow.org/api_docs/python/tf/random_uniform

tf.truncated_normal

截断的正态分布函数。生成的值遵循一个正态分布,但不会大于平均值2个标准差。

.

[python]view plaincopy

  1. truncated_normal(
  2. shape,#一个一维整数张量或Python数组。代表张量的形状。
  3. mean=0.0,#数据类型为dtype的张量值或Python值。是正态分布的均值。
  4. stddev=1.0,#数据类型为dtype的张量值或Python值。是正态分布的标准差
  5. dtype=tf.float32,#输出的数据类型。
  6. seed=None,#一个Python整数。是随机种子。
  7. name=None#操作的名称(可选)
  8. )

.

官网api地址:https://www.tensorflow.org/api_docs/python/tf/truncated_normal

tf.random_shuffle

沿着要被洗牌的张量的第一个维度,随机打乱。

.

[python]view plaincopy

  1. random_shuffle(
  2. value,# 要被洗牌的张量
  3. seed=None,
  4. name=None
  5. )

即下面这种效果:

.

[python]view plaincopy

  1. [[1, 2], [[5, 6],
  2. [3, 4], ==> [1, 2],
  3. [5, 6]] [3, 4]]

.

官网api地址: https://www.tensorflow.org/api_docs/python/tf/random_shuffle

附录1:生成随机数的操作的源码random_ops.py

.

[python]view plaincopy

  1. # Copyright 2015 The TensorFlow 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. # ==============================================================================
  15. """Operations for generating random numbers."""
  16. from __future__ import absolute_import
  17. from __future__ import division
  18. from __future__ import print_function
  19. import numpy as np
  20. from tensorflow.python.framework import dtypes
  21. from tensorflow.python.framework import ops
  22. from tensorflow.python.framework import random_seed
  23. from tensorflow.python.ops import array_ops
  24. from tensorflow.python.ops import control_flow_ops
  25. from tensorflow.python.ops import gen_random_ops
  26. from tensorflow.python.ops import math_ops
  27. # go/tf-wildcard-import
  28. # pylint: disable=wildcard-import
  29. from tensorflow.python.ops.gen_random_ops import *
  30. # pylint: enable=wildcard-import
  31. def _ShapeTensor(shape):
  32. """Convert to an int32 or int64 tensor, defaulting to int32 if empty."""
  33. if isinstance(shape, (tuple, list)) and not shape:
  34. dtype = dtypes.int32
  35. else:
  36. dtype = None
  37. return ops.convert_to_tensor(shape, dtype=dtype, name="shape")
  38. # pylint: disable=protected-access
  39. def random_normal(shape,
  40. mean=0.0,
  41. stddev=1.0,
  42. dtype=dtypes.float32,
  43. seed=None,
  44. name=None):
  45. """Outputs random values from a normal distribution.
  46. Args:
  47. shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
  48. mean: A 0-D Tensor or Python value of type `dtype`. The mean of the normal
  49. distribution.
  50. stddev: A 0-D Tensor or Python value of type `dtype`. The standard deviation
  51. of the normal distribution.
  52. dtype: The type of the output.
  53. seed: A Python integer. Used to create a random seed for the distribution.
  54. See
  55. @{tf.set_random_seed}
  56. for behavior.
  57. name: A name for the operation (optional).
  58. Returns:
  59. A tensor of the specified shape filled with random normal values.
  60. """
  61. with ops.name_scope(name, "random_normal", [shape, mean, stddev]) as name:
  62. shape_tensor = _ShapeTensor(shape)
  63. mean_tensor = ops.convert_to_tensor(mean, dtype=dtype, name="mean")
  64. stddev_tensor = ops.convert_to_tensor(stddev, dtype=dtype, name="stddev")
  65. seed1, seed2 = random_seed.get_seed(seed)
  66. rnd = gen_random_ops._random_standard_normal(
  67. shape_tensor, dtype, seed=seed1, seed2=seed2)
  68. mul = rnd * stddev_tensor
  69. value = math_ops.add(mul, mean_tensor, name=name)
  70. return value
  71. ops.NotDifferentiable("RandomStandardNormal")
  72. def parameterized_truncated_normal(shape,
  73. means=0.0,
  74. stddevs=1.0,
  75. minvals=-2.0,
  76. maxvals=2.0,
  77. dtype=dtypes.float32,
  78. seed=None,
  79. name=None):
  80. """Outputs random values from a truncated normal distribution.
  81. The generated values follow a normal distribution with specified mean and
  82. standard deviation, except that values whose magnitude is more than 2 standard
  83. deviations from the mean are dropped and re-picked.
  84. Args:
  85. shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
  86. means: A 0-D Tensor or Python value of type `dtype`. The mean of the
  87. truncated normal distribution.
  88. stddevs: A 0-D Tensor or Python value of type `dtype`. The standard
  89. deviation of the truncated normal distribution.
  90. minvals: A 0-D Tensor or Python value of type `dtype`. The minimum value of
  91. the truncated normal distribution.
  92. maxvals: A 0-D Tensor or Python value of type `dtype`. The maximum value of
  93. the truncated normal distribution.
  94. dtype: The type of the output.
  95. seed: A Python integer. Used to create a random seed for the distribution.
  96. See
  97. @{tf.set_random_seed}
  98. for behavior.
  99. name: A name for the operation (optional).
  100. Returns:
  101. A tensor of the specified shape filled with random truncated normal values.
  102. """
  103. with ops.name_scope(name, "parameterized_truncated_normal",
  104. [shape, means, stddevs, minvals, maxvals]) as name:
  105. shape_tensor = _ShapeTensor(shape)
  106. means_tensor = ops.convert_to_tensor(means, dtype=dtype, name="means")
  107. stddevs_tensor = ops.convert_to_tensor(stddevs, dtype=dtype, name="stddevs")
  108. minvals_tensor = ops.convert_to_tensor(minvals, dtype=dtype, name="minvals")
  109. maxvals_tensor = ops.convert_to_tensor(maxvals, dtype=dtype, name="maxvals")
  110. seed1, seed2 = random_seed.get_seed(seed)
  111. rnd = gen_random_ops._parameterized_truncated_normal(
  112. shape_tensor,
  113. means_tensor,
  114. stddevs_tensor,
  115. minvals_tensor,
  116. maxvals_tensor,
  117. seed=seed1,
  118. seed2=seed2)
  119. return rnd
  120. def truncated_normal(shape,
  121. mean=0.0,
  122. stddev=1.0,
  123. dtype=dtypes.float32,
  124. seed=None,
  125. name=None):
  126. """Outputs random values from a truncated normal distribution.
  127. The generated values follow a normal distribution with specified mean and
  128. standard deviation, except that values whose magnitude is more than 2 standard
  129. deviations from the mean are dropped and re-picked.
  130. Args:
  131. shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
  132. mean: A 0-D Tensor or Python value of type `dtype`. The mean of the
  133. truncated normal distribution.
  134. stddev: A 0-D Tensor or Python value of type `dtype`. The standard deviation
  135. of the truncated normal distribution.
  136. dtype: The type of the output.
  137. seed: A Python integer. Used to create a random seed for the distribution.
  138. See
  139. @{tf.set_random_seed}
  140. for behavior.
  141. name: A name for the operation (optional).
  142. Returns:
  143. A tensor of the specified shape filled with random truncated normal values.
  144. """
  145. with ops.name_scope(name, "truncated_normal", [shape, mean, stddev]) as name:
  146. shape_tensor = _ShapeTensor(shape)
  147. mean_tensor = ops.convert_to_tensor(mean, dtype=dtype, name="mean")
  148. stddev_tensor = ops.convert_to_tensor(stddev, dtype=dtype, name="stddev")
  149. seed1, seed2 = random_seed.get_seed(seed)
  150. rnd = gen_random_ops._truncated_normal(
  151. shape_tensor, dtype, seed=seed1, seed2=seed2)
  152. mul = rnd * stddev_tensor
  153. value = math_ops.add(mul, mean_tensor, name=name)
  154. return value
  155. ops.NotDifferentiable("ParameterizedTruncatedNormal")
  156. ops.NotDifferentiable("TruncatedNormal")
  157. def random_uniform(shape,
  158. minval=0,
  159. maxval=None,
  160. dtype=dtypes.float32,
  161. seed=None,
  162. name=None):
  163. """Outputs random values from a uniform distribution.
  164. The generated values follow a uniform distribution in the range
  165. `[minval, maxval)`. The lower bound `minval` is included in the range, while
  166. the upper bound `maxval` is excluded.
  167. For floats, the default range is `[0, 1)`. For ints, at least `maxval` must
  168. be specified explicitly.
  169. In the integer case, the random integers are slightly biased unless
  170. `maxval - minval` is an exact power of two. The bias is small for values of
  171. `maxval - minval` significantly smaller than the range of the output (either
  172. `2**32` or `2**64`).
  173. Args:
  174. shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
  175. minval: A 0-D Tensor or Python value of type `dtype`. The lower bound on the
  176. range of random values to generate. Defaults to 0.
  177. maxval: A 0-D Tensor or Python value of type `dtype`. The upper bound on
  178. the range of random values to generate. Defaults to 1 if `dtype` is
  179. floating point.
  180. dtype: The type of the output: `float32`, `float64`, `int32`, or `int64`.
  181. seed: A Python integer. Used to create a random seed for the distribution.
  182. See @{tf.set_random_seed}
  183. for behavior.
  184. name: A name for the operation (optional).
  185. Returns:
  186. A tensor of the specified shape filled with random uniform values.
  187. Raises:
  188. ValueError: If `dtype` is integral and `maxval` is not specified.
  189. """
  190. dtype = dtypes.as_dtype(dtype)
  191. if maxval is None:
  192. if dtype.is_integer:
  193. raise ValueError("Must specify maxval for integer dtype %r" % dtype)
  194. maxval = 1
  195. with ops.name_scope(name, "random_uniform", [shape, minval, maxval]) as name:
  196. shape = _ShapeTensor(shape)
  197. minval = ops.convert_to_tensor(minval, dtype=dtype, name="min")
  198. maxval = ops.convert_to_tensor(maxval, dtype=dtype, name="max")
  199. seed1, seed2 = random_seed.get_seed(seed)
  200. if dtype.is_integer:
  201. return gen_random_ops._random_uniform_int(
  202. shape, minval, maxval, seed=seed1, seed2=seed2, name=name)
  203. else:
  204. rnd = gen_random_ops._random_uniform(
  205. shape, dtype, seed=seed1, seed2=seed2)
  206. return math_ops.add(rnd * (maxval - minval), minval, name=name)
  207. ops.NotDifferentiable("RandomUniform")
  208. def random_shuffle(value, seed=None, name=None):
  209. """Randomly shuffles a tensor along its first dimension.
  210. The tensor is shuffled along dimension 0, such that each `value[j]` is mapped
  211. to one and only one `output[i]`. For example, a mapping that might occur for a
  212. 3x2 tensor is:
  213. ```python
  214. [[1, 2], [[5, 6],
  215. [3, 4], ==> [1, 2],
  216. [5, 6]] [3, 4]]
  217. ```
  218. Args:
  219. value: A Tensor to be shuffled.
  220. seed: A Python integer. Used to create a random seed for the distribution.
  221. See
  222. @{tf.set_random_seed}
  223. for behavior.
  224. name: A name for the operation (optional).
  225. Returns:
  226. A tensor of same shape and type as `value`, shuffled along its first
  227. dimension.
  228. """
  229. seed1, seed2 = random_seed.get_seed(seed)
  230. return gen_random_ops._random_shuffle(
  231. value, seed=seed1, seed2=seed2, name=name)
  232. def random_crop(value, size, seed=None, name=None):
  233. """Randomly crops a tensor to a given size.
  234. Slices a shape `size` portion out of `value` at a uniformly chosen offset.
  235. Requires `value.shape >= size`.
  236. If a dimension should not be cropped, pass the full size of that dimension.
  237. For example, RGB images can be cropped with
  238. `size = [crop_height, crop_width, 3]`.
  239. Args:
  240. value: Input tensor to crop.
  241. size: 1-D tensor with size the rank of `value`.
  242. seed: Python integer. Used to create a random seed. See
  243. @{tf.set_random_seed}
  244. for behavior.
  245. name: A name for this operation (optional).
  246. Returns:
  247. A cropped tensor of the same rank as `value` and shape `size`.
  248. """
  249. # TODO(shlens): Implement edge case to guarantee output size dimensions.
  250. # If size > value.shape, zero pad the result so that it always has shape
  251. # exactly size.
  252. with ops.name_scope(name, "random_crop", [value, size]) as name:
  253. value = ops.convert_to_tensor(value, name="value")
  254. size = ops.convert_to_tensor(size, dtype=dtypes.int32, name="size")
  255. shape = array_ops.shape(value)
  256. check = control_flow_ops.Assert(
  257. math_ops.reduce_all(shape >= size),
  258. ["Need value.shape >= size, got ", shape, size],
  259. summarize=1000)
  260. shape = control_flow_ops.with_dependencies([check], shape)
  261. limit = shape - size + 1
  262. offset = random_uniform(
  263. array_ops.shape(shape),
  264. dtype=size.dtype,
  265. maxval=size.dtype.max,
  266. seed=seed) % limit
  267. return array_ops.slice(value, offset, size, name=name)
  268. def multinomial(logits, num_samples, seed=None, name=None):
  269. """Draws samples from a multinomial distribution.
  270. Example:
  271. ```python
  272. # samples has shape [1, 5], where each value is either 0 or 1 with equal
  273. # probability.
  274. samples = tf.multinomial(tf.log([[10., 10.]]), 5)
  275. ```
  276. Args:
  277. logits: 2-D Tensor with shape `[batch_size, num_classes]`. Each slice
  278. `[i, :]` represents the log-odds for all classes.
  279. num_samples: 0-D. Number of independent samples to draw for each row slice.
  280. seed: A Python integer. Used to create a random seed for the distribution.
  281. See
  282. @{tf.set_random_seed}
  283. for behavior.
  284. name: Optional name for the operation.
  285. Returns:
  286. The drawn samples of shape `[batch_size, num_samples]`.
  287. """
  288. with ops.name_scope(name, "multinomial", [logits]):
  289. logits = ops.convert_to_tensor(logits, name="logits")
  290. seed1, seed2 = random_seed.get_seed(seed)
  291. return gen_random_ops.multinomial(
  292. logits, num_samples, seed=seed1, seed2=seed2)
  293. ops.NotDifferentiable("Multinomial")
  294. def random_gamma(shape,
  295. alpha,
  296. beta=None,
  297. dtype=dtypes.float32,
  298. seed=None,
  299. name=None):
  300. """Draws `shape` samples from each of the given Gamma distribution(s).
  301. `alpha` is the shape parameter describing the distribution(s), and `beta` is
  302. the inverse scale parameter(s).
  303. Example:
  304. samples = tf.random_gamma([10], [0.5, 1.5])
  305. # samples has shape [10, 2], where each slice [:, 0] and [:, 1] represents
  306. # the samples drawn from each distribution
  307. samples = tf.random_gamma([7, 5], [0.5, 1.5])
  308. # samples has shape [7, 5, 2], where each slice [:, :, 0] and [:, :, 1]
  309. # represents the 7x5 samples drawn from each of the two distributions
  310. samples = tf.random_gamma([30], [[1.],[3.],[5.]], beta=[[3., 4.]])
  311. # samples has shape [30, 3, 2], with 30 samples each of 3x2 distributions.
  312. Note: Because internal calculations are done using `float64` and casting has
  313. `floor` semantics, we must manually map zero outcomes to the smallest
  314. possible positive floating-point value, i.e., `np.finfo(dtype).tiny`. This
  315. means that `np.finfo(dtype).tiny` occurs more frequently than it otherwise
  316. should. This bias can only happen for small values of `alpha`, i.e.,
  317. `alpha << 1` or large values of `beta`, i.e., `beta >> 1`.
  318. Args:
  319. shape: A 1-D integer Tensor or Python array. The shape of the output samples
  320. to be drawn per alpha/beta-parameterized distribution.
  321. alpha: A Tensor or Python value or N-D array of type `dtype`. `alpha`
  322. provides the shape parameter(s) describing the gamma distribution(s) to
  323. sample. Must be broadcastable with `beta`.
  324. beta: A Tensor or Python value or N-D array of type `dtype`. Defaults to 1.
  325. `beta` provides the inverse scale parameter(s) of the gamma
  326. distribution(s) to sample. Must be broadcastable with `alpha`.
  327. dtype: The type of alpha, beta, and the output: `float16`, `float32`, or
  328. `float64`.
  329. seed: A Python integer. Used to create a random seed for the distributions.
  330. See
  331. @{tf.set_random_seed}
  332. for behavior.
  333. name: Optional name for the operation.
  334. Returns:
  335. samples: a `Tensor` of shape `tf.concat(shape, tf.shape(alpha + beta))`
  336. with values of type `dtype`.
  337. """
  338. with ops.name_scope(name, "random_gamma", [shape, alpha, beta]):
  339. shape = ops.convert_to_tensor(shape, name="shape", dtype=dtypes.int32)
  340. alpha = ops.convert_to_tensor(alpha, name="alpha", dtype=dtype)
  341. beta = ops.convert_to_tensor(
  342. beta if beta is not None else 1, name="beta", dtype=dtype)
  343. alpha_broadcast = alpha + array_ops.zeros_like(beta)
  344. seed1, seed2 = random_seed.get_seed(seed)
  345. return math_ops.maximum(
  346. np.finfo(dtype.as_numpy_dtype).tiny,
  347. gen_random_ops._random_gamma(
  348. shape, alpha_broadcast, seed=seed1, seed2=seed2) / beta)
  349. ops.NotDifferentiable("RandomGamma")
  350. def random_poisson(lam, shape, dtype=dtypes.float32, seed=None, name=None):
  351. """Draws `shape` samples from each of the given Poisson distribution(s).
  352. `lam` is the rate parameter describing the distribution(s).
  353. Example:
  354. samples = tf.random_poisson([0.5, 1.5], [10])
  355. # samples has shape [10, 2], where each slice [:, 0] and [:, 1] represents
  356. # the samples drawn from each distribution
  357. samples = tf.random_poisson([12.2, 3.3], [7, 5])
  358. # samples has shape [7, 5, 2], where each slice [:, :, 0] and [:, :, 1]
  359. # represents the 7x5 samples drawn from each of the two distributions
  360. Args:
  361. lam: A Tensor or Python value or N-D array of type `dtype`.
  362. `lam` provides the rate parameter(s) describing the poisson
  363. distribution(s) to sample.
  364. shape: A 1-D integer Tensor or Python array. The shape of the output samples
  365. to be drawn per "rate"-parameterized distribution.
  366. dtype: The type of `lam` and the output: `float16`, `float32`, or
  367. `float64`.
  368. seed: A Python integer. Used to create a random seed for the distributions.
  369. See
  370. @{tf.set_random_seed}
  371. for behavior.
  372. name: Optional name for the operation.
  373. Returns:
  374. samples: a `Tensor` of shape `tf.concat(shape, tf.shape(lam))` with
  375. values of type `dtype`.
  376. """
  377. with ops.name_scope(name, "random_poisson", [lam, shape]):
  378. lam = ops.convert_to_tensor(lam, name="lam", dtype=dtype)
  379. shape = ops.convert_to_tensor(shape, name="shape", dtype=dtypes.int32)
  380. seed1, seed2 = random_seed.get_seed(seed)
  381. return gen_random_ops._random_poisson(shape, lam, seed=seed1, seed2=seed2)

.