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

____tz_zs

tf.random_normal

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

.

[python]  view plain  copy
 
  1. <span style="font-size:16px;">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 plain  copy
 
  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 plain  copy
 
  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 plain  copy
 
  1. random_shuffle(  
  2.     value,# 要被洗牌的张量  
  3.     seed=None,  
  4.     name=None  
  5. )  

即下面这种效果:

.

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

.

猜你喜欢

转载自www.cnblogs.com/Ph-one/p/9234513.html