def random_normal(shape, mean=0.0, stddev=1.0, dtype=dtypes.float32, seed=None, name=None): """Outputs random values from a normal distribution. Args: shape: A 1-D integer Tensor or Python array. The shape of the output tensor. mean: A Tensor or Python value of type `dtype`, broadcastable with `stddev`. The mean of the normal distribution. stddev: A Tensor or Python value of type `dtype`, broadcastable with `mean`. The standard deviation of the normal distribution. dtype: The type of the output. seed: A Python integer. Used to create a random seed for the distribution. See `tf.compat.v1.set_random_seed` for behavior. name: A name for the operation (optional). Returns: A tensor of the specified shape filled with random normal values. """ with ops.name_scope(name, "random_normal", [shape, mean, stddev]) as name: shape_tensor = tensor_util.shape_tensor(shape) mean_tensor = ops.convert_to_tensor(mean, dtype=dtype, name="mean") stddev_tensor = ops.convert_to_tensor(stddev, dtype=dtype, name="stddev") seed1, seed2 = random_seed.get_seed(seed) rnd = gen_random_ops.random_standard_normal(shape_tensor, dtype, seed=seed1, seed2=seed2) mul = rnd * stddev_tensor value = math_ops.add(mul, mean_tensor, name=name) tensor_util.maybe_set_static_shape(value, shape) return value
def truncated_normal(shape, mean=0.0, stddev=1.0, dtype=dtypes.float32, seed=None, name=None): """Outputs random values from a truncated normal distribution. The generated values follow a normal distribution with specified mean and standard deviation, except that values whose magnitude is more than 2 standard deviations from the mean are dropped and re-picked. Args: shape: A 1-D integer Tensor or Python array. The shape of the output tensor. mean: A 0-D Tensor or Python value of type `dtype`. The mean of the truncated normal distribution. stddev: A 0-D Tensor or Python value of type `dtype`. The standard deviation of the normal distribution, before truncation. dtype: The type of the output. seed: A Python integer. Used to create a random seed for the distribution. See `tf.random.set_seed` for behavior. name: A name for the operation (optional). Returns: A tensor of the specified shape filled with random truncated normal values. """ with ops.name_scope(name, "truncated_normal", [shape, mean, stddev]) as name: shape_tensor = tensor_util.shape_tensor(shape) mean_tensor = ops.convert_to_tensor(mean, dtype=dtype, name="mean") stddev_tensor = ops.convert_to_tensor(stddev, dtype=dtype, name="stddev") seed1, seed2 = random_seed.get_seed(seed) rnd = gen_random_ops.truncated_normal( shape_tensor, dtype, seed=seed1, seed2=seed2) mul = rnd * stddev_tensor value = math_ops.add(mul, mean_tensor, name=name) tensor_util.maybe_set_static_shape(value, shape) return value
def stateless_random_normal(shape, seed, mean=0.0, stddev=1.0, dtype=dtypes.float32, name=None): """Outputs deterministic pseudorandom values from a normal distribution. This is a stateless version of `tf.random.normal`: if run twice with the same seeds and shapes, it will produce the same pseudorandom numbers. The output is consistent across multiple runs on the same hardware (and between CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU hardware. Args: shape: A 1-D integer Tensor or Python array. The shape of the output tensor. seed: A shape [2] Tensor, the seed to the random number generator. Must have dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.) mean: A 0-D Tensor or Python value of type `dtype`. The mean of the normal distribution. stddev: A 0-D Tensor or Python value of type `dtype`. The standard deviation of the normal distribution. dtype: The type of the output. name: A name for the operation (optional). Returns: A tensor of the specified shape filled with random normal values. """ with ops.name_scope(name, "stateless_random_normal", [shape, seed, mean, stddev]) as name: shape = tensor_util.shape_tensor(shape) mean = ops.convert_to_tensor(mean, dtype=dtype, name="mean") stddev = ops.convert_to_tensor(stddev, dtype=dtype, name="stddev") key, counter, alg = _get_key_counter_alg(seed) rnd = gen_stateless_random_ops_v2.stateless_random_normal_v2( shape, key=key, counter=counter, dtype=dtype, alg=alg) result = math_ops.add(rnd * stddev, mean, name=name) tensor_util.maybe_set_static_shape(result, shape) return result
def testConversion(self): """Make sure fully known TensorShape objects convert to Tensors.""" shape = tensor_shape.TensorShape([1, tensor_shape.Dimension(2)]) shape_tensor = tensor_util.shape_tensor(shape) self.assertAllEqual((1, 2), shape_tensor)
def stateless_parameterized_truncated_normal(shape, seed, means=0.0, stddevs=1.0, minvals=-2.0, maxvals=2.0, name=None): """Outputs random values from a truncated normal distribution. The generated values follow a normal distribution with specified mean and standard deviation, except that values whose magnitude is more than 2 standard deviations from the mean are dropped and re-picked. Examples: Sample from a Truncated normal, with deferring shape parameters that broadcast. >>> means = 0. >>> stddevs = tf.math.exp(tf.random.uniform(shape=[2, 3])) >>> minvals = [-1., -2., -1000.] >>> maxvals = [[10000.], [1.]] >>> y = tf.random.stateless_parameterized_truncated_normal( ... shape=[10, 2, 3], seed=[7, 17], ... means=means, stddevs=stddevs, minvals=minvals, maxvals=maxvals) >>> y.shape TensorShape([10, 2, 3]) Args: shape: A 1-D integer `Tensor` or Python array. The shape of the output tensor. seed: A shape [2] Tensor, the seed to the random number generator. Must have dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.) means: A `Tensor` or Python value of type `dtype`. The mean of the truncated normal distribution. This must broadcast with `stddevs`, `minvals` and `maxvals`, and the broadcasted shape must be dominated by `shape`. stddevs: A `Tensor` or Python value of type `dtype`. The standard deviation of the truncated normal distribution. This must broadcast with `means`, `minvals` and `maxvals`, and the broadcasted shape must be dominated by `shape`. minvals: A `Tensor` or Python value of type `dtype`. The minimum value of the truncated normal distribution. This must broadcast with `means`, `stddevs` and `maxvals`, and the broadcasted shape must be dominated by `shape`. maxvals: A `Tensor` or Python value of type `dtype`. The maximum value of the truncated normal distribution. This must broadcast with `means`, `stddevs` and `minvals`, and the broadcasted shape must be dominated by `shape`. name: A name for the operation (optional). Returns: A tensor of the specified shape filled with random truncated normal values. """ with ops.name_scope(name, "stateless_parameterized_truncated_normal", [shape, means, stddevs, minvals, maxvals]) as name: shape_tensor = tensor_util.shape_tensor(shape) means_tensor = ops.convert_to_tensor(means, name="means") stddevs_tensor = ops.convert_to_tensor(stddevs, name="stddevs") minvals_tensor = ops.convert_to_tensor(minvals, name="minvals") maxvals_tensor = ops.convert_to_tensor(maxvals, name="maxvals") rnd = gen_stateless_random_ops.stateless_parameterized_truncated_normal( shape_tensor, seed, means_tensor, stddevs_tensor, minvals_tensor, maxvals_tensor) tensor_util.maybe_set_static_shape(rnd, shape) return rnd
def stateless_random_gamma(shape, seed, alpha, beta=None, dtype=dtypes.float32, name=None): """Outputs deterministic pseudorandom values from a gamma distribution. The generated values follow a gamma distribution with specified concentration (`alpha`) and inverse scale (`beta`) parameters. This is a stateless version of `tf.random.gamma`: if run twice with the same seeds and shapes, it will produce the same pseudorandom numbers. The output is consistent across multiple runs on the same hardware (and between CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU hardware. A slight difference exists in the interpretation of the `shape` parameter between `stateless_gamma` and `gamma`: in `gamma`, the `shape` is always prepended to the shape of the broadcast of `alpha` with `beta`; whereas in `stateless_gamma` the `shape` parameter must always encompass the shapes of each of `alpha` and `beta` (which must broadcast together to match the trailing dimensions of `shape`). Note: Because internal calculations are done using `float64` and casting has `floor` semantics, we must manually map zero outcomes to the smallest possible positive floating-point value, i.e., `np.finfo(dtype).tiny`. This means that `np.finfo(dtype).tiny` occurs more frequently than it otherwise should. This bias can only happen for small values of `alpha`, i.e., `alpha << 1` or large values of `beta`, i.e., `beta >> 1`. The samples are differentiable w.r.t. alpha and beta. The derivatives are computed using the approach described in (Figurnov et al., 2018). Example: ```python samples = tf.random.stateless_gamma([10, 2], seed=[12, 34], alpha=[0.5, 1.5]) # samples has shape [10, 2], where each slice [:, 0] and [:, 1] represents # the samples drawn from each distribution samples = tf.random.stateless_gamma([7, 5, 2], seed=[12, 34], alpha=[.5, 1.5]) # samples has shape [7, 5, 2], where each slice [:, :, 0] and [:, :, 1] # represents the 7x5 samples drawn from each of the two distributions alpha = tf.constant([[1.], [3.], [5.]]) beta = tf.constant([[3., 4.]]) samples = tf.random.stateless_gamma( [30, 3, 2], seed=[12, 34], alpha=alpha, beta=beta) # samples has shape [30, 3, 2], with 30 samples each of 3x2 distributions. with tf.GradientTape() as tape: tape.watch([alpha, beta]) loss = tf.reduce_mean(tf.square(tf.random.stateless_gamma( [30, 3, 2], seed=[12, 34], alpha=alpha, beta=beta))) dloss_dalpha, dloss_dbeta = tape.gradient(loss, [alpha, beta]) # unbiased stochastic derivatives of the loss function alpha.shape == dloss_dalpha.shape # True beta.shape == dloss_dbeta.shape # True ``` Args: shape: A 1-D integer Tensor or Python array. The shape of the output tensor. seed: A shape [2] Tensor, the seed to the random number generator. Must have dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.) alpha: Tensor. The concentration parameter of the gamma distribution. Must be broadcastable with `beta`, and broadcastable with the rightmost dimensions of `shape`. beta: Tensor. The inverse scale parameter of the gamma distribution. Must be broadcastable with `alpha` and broadcastable with the rightmost dimensions of `shape`. dtype: Floating point dtype of `alpha`, `beta`, and the output. name: A name for the operation (optional). Returns: samples: A Tensor of the specified shape filled with random gamma values. For each i, each `samples[..., i] is an independent draw from the gamma distribution with concentration alpha[i] and scale beta[i]. """ with ops.name_scope(name, "stateless_random_gamma", [shape, seed, alpha, beta]) as name: shape = tensor_util.shape_tensor(shape) alpha = ops.convert_to_tensor(alpha, dtype=dtype, name="alpha") beta = ops.convert_to_tensor(beta if beta is not None else 1, name="beta", dtype=dtype) broadcast_shape = array_ops.broadcast_dynamic_shape( array_ops.shape(alpha), array_ops.shape(beta)) alpha_broadcast = array_ops.broadcast_to(alpha, broadcast_shape) result = math_ops.maximum( np.finfo(alpha.dtype.as_numpy_dtype).tiny, gen_stateless_random_ops.stateless_random_gamma_v2( shape, seed=seed, alpha=alpha_broadcast) / beta) tensor_util.maybe_set_static_shape(result, shape) return result
def stateless_random_binomial(shape, seed, counts, probs, output_dtype=dtypes.int32, name=None): """Outputs deterministic pseudorandom values from a binomial distribution. The generated values follow a binomial distribution with specified count and probability of success parameters. This is a stateless version of `tf.random.Generator.binomial`: if run twice with the same seeds and shapes, it will produce the same pseudorandom numbers. The output is consistent across multiple runs on the same hardware (and between CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU hardware. Example: ```python counts = [10., 20.] # Probability of success. probs = [0.8] binomial_samples = tf.random.stateless_binomial( shape=[2], seed=[123, 456], counts=counts, probs=probs) counts = ... # Shape [3, 1, 2] probs = ... # Shape [1, 4, 2] shape = [3, 4, 3, 4, 2] # Sample shape will be [3, 4, 3, 4, 2] binomial_samples = tf.random.stateless_binomial( shape=shape, seed=[123, 456], counts=counts, probs=probs) ``` Args: shape: A 1-D integer Tensor or Python array. The shape of the output tensor. seed: A shape [2] Tensor, the seed to the random number generator. Must have dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.) counts: Tensor. The counts of the binomial distribution. Must be broadcastable with `probs`, and broadcastable with the rightmost dimensions of `shape`. probs: Tensor. The probability of success for the binomial distribution. Must be broadcastable with `counts` and broadcastable with the rightmost dimensions of `shape`. output_dtype: The type of the output. Default: tf.int32 name: A name for the operation (optional). Returns: samples: A Tensor of the specified shape filled with random binomial values. For each i, each samples[..., i] is an independent draw from the binomial distribution on counts[i] trials with probability of success probs[i]. """ with ops.name_scope(name, "stateless_random_binomial", [shape, seed, counts, probs]) as name: shape = tensor_util.shape_tensor(shape) probs = ops.convert_to_tensor(probs, dtype_hint=dtypes.float32, name="probs") counts = ops.convert_to_tensor(counts, dtype_hint=probs.dtype, name="counts") result = gen_stateless_random_ops.stateless_random_binomial( shape=shape, seed=seed, counts=counts, probs=probs, dtype=output_dtype) tensor_util.maybe_set_static_shape(result, shape) return result
def stateless_random_uniform(shape, seed, minval=0, maxval=None, dtype=dtypes.float32, name=None, alg="auto_select"): """Outputs deterministic pseudorandom values from a uniform distribution. This is a stateless version of `tf.random.uniform`: if run twice with the same seeds and shapes, it will produce the same pseudorandom numbers. The output is consistent across multiple runs on the same hardware (and between CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU hardware. The generated values follow a uniform distribution in the range `[minval, maxval)`. The lower bound `minval` is included in the range, while the upper bound `maxval` is excluded. For floats, the default range is `[0, 1)`. For ints, at least `maxval` must be specified explicitly. In the integer case, the random integers are slightly biased unless `maxval - minval` is an exact power of two. The bias is small for values of `maxval - minval` significantly smaller than the range of the output (either `2**32` or `2**64`). For full-range (i.e. inclusive of both max and min) random integers, pass `minval=None` and `maxval=None` with an integer `dtype`. For an integer dtype either both `minval` and `maxval` must be `None` or neither may be `None`. For example: ```python ints = tf.random.stateless_uniform( [10], seed=(2, 3), minval=None, maxval=None, dtype=tf.int32) ``` Args: shape: A 1-D integer Tensor or Python array. The shape of the output tensor. seed: A shape [2] Tensor, the seed to the random number generator. Must have dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.) minval: A Tensor or Python value of type `dtype`, broadcastable with `shape` (for integer types, broadcasting is not supported, so it needs to be a scalar). The lower bound on the range of random values to generate. Pass `None` for full-range integers. Defaults to 0. maxval: A Tensor or Python value of type `dtype`, broadcastable with `shape` (for integer types, broadcasting is not supported, so it needs to be a scalar). The upper bound on the range of random values to generate. Defaults to 1 if `dtype` is floating point. Pass `None` for full-range integers. dtype: The type of the output: `float16`, `bfloat16`, `float32`, `float64`, `int32`, or `int64`. For unbounded uniform ints (`minval`, `maxval` both `None`), `uint32` and `uint64` may be used. Defaults to `float32`. name: A name for the operation (optional). alg: The RNG algorithm used to generate the random numbers. Valid choices are `"philox"` for [the Philox algorithm](https://www.thesalmons.org/john/random123/papers/random123sc11.pdf), `"threefry"` for [the ThreeFry algorithm](https://www.thesalmons.org/john/random123/papers/random123sc11.pdf), and `"auto_select"` (default) for the system to automatically select an algorithm based the device type. Values of `tf.random.Algorithm` can also be used. Note that with `"auto_select"`, the outputs of this function may change when it is running on a different device. Returns: A tensor of the specified shape filled with random uniform values. Raises: ValueError: If `dtype` is integral and only one of `minval` or `maxval` is specified. """ dtype = dtypes.as_dtype(dtype) accepted_dtypes = (dtypes.float16, dtypes.bfloat16, dtypes.float32, dtypes.float64, dtypes.int32, dtypes.int64, dtypes.uint32, dtypes.uint64) if dtype not in accepted_dtypes: raise ValueError( f"Argument `dtype` got invalid value {dtype}. Accepted dtypes are " f"{accepted_dtypes}.") if dtype.is_integer: if (minval is None) != (maxval is None): raise ValueError( f"For integer `dtype` argument {dtype}, argument `minval` and " f"`maxval` must be both None or not None. Got `minval`={minval} and " f"`maxval`={maxval}.") if minval is not None and dtype in (dtypes.uint32, dtypes.uint64): raise ValueError( f"Argument `dtype` got invalid value {dtype} when argument `minval` " f"is not None. Please don't use unsigned integers in this case." ) elif maxval is None: maxval = 1 with ops.name_scope(name, "stateless_random_uniform", [shape, seed, minval, maxval]) as name: shape = tensor_util.shape_tensor(shape) if dtype.is_integer and minval is None: key, counter, alg = _get_key_counter_alg(seed, alg) result = (gen_stateless_random_ops_v2. stateless_random_uniform_full_int_v2(shape, key=key, counter=counter, dtype=dtype, alg=alg, name=name)) else: minval = ops.convert_to_tensor(minval, dtype=dtype, name="min") maxval = ops.convert_to_tensor(maxval, dtype=dtype, name="max") if dtype.is_integer: key, counter, alg = _get_key_counter_alg(seed, alg) result = gen_stateless_random_ops_v2.stateless_random_uniform_int_v2( shape, key=key, counter=counter, minval=minval, maxval=maxval, alg=alg, name=name) else: key, counter, alg = _get_key_counter_alg(seed, alg) rnd = gen_stateless_random_ops_v2.stateless_random_uniform_v2( shape, key=key, counter=counter, dtype=dtype, alg=alg) result = math_ops.add(rnd * (maxval - minval), minval, name=name) tensor_util.maybe_set_static_shape(result, shape) return result
def random_uniform(shape, minval=0, maxval=None, dtype=dtypes.float32, seed=None, name=None): """Outputs random values from a uniform distribution. The generated values follow a uniform distribution in the range `[minval, maxval)`. The lower bound `minval` is included in the range, while the upper bound `maxval` is excluded. For floats, the default range is `[0, 1)`. For ints, at least `maxval` must be specified explicitly. In the integer case, the random integers are slightly biased unless `maxval - minval` is an exact power of two. The bias is small for values of `maxval - minval` significantly smaller than the range of the output (either `2**32` or `2**64`). Examples: >>> tf.random.uniform(shape=[2]) <tf.Tensor: shape=(2,), dtype=float32, numpy=array([..., ...], dtype=float32)> >>> tf.random.uniform(shape=[], minval=-1., maxval=0.) <tf.Tensor: shape=(), dtype=float32, numpy=-...> >>> tf.random.uniform(shape=[], minval=5, maxval=10, dtype=tf.int64) <tf.Tensor: shape=(), dtype=int64, numpy=...> The `seed` argument produces a deterministic sequence of tensors across multiple calls. To repeat that sequence, use `tf.random.set_seed`: >>> tf.random.set_seed(5) >>> tf.random.uniform(shape=[], maxval=3, dtype=tf.int32, seed=10) <tf.Tensor: shape=(), dtype=int32, numpy=2> >>> tf.random.uniform(shape=[], maxval=3, dtype=tf.int32, seed=10) <tf.Tensor: shape=(), dtype=int32, numpy=0> >>> tf.random.set_seed(5) >>> tf.random.uniform(shape=[], maxval=3, dtype=tf.int32, seed=10) <tf.Tensor: shape=(), dtype=int32, numpy=2> >>> tf.random.uniform(shape=[], maxval=3, dtype=tf.int32, seed=10) <tf.Tensor: shape=(), dtype=int32, numpy=0> Without `tf.random.set_seed` but with a `seed` argument is specified, small changes to function graphs or previously executed operations will change the returned value. See `tf.random.set_seed` for details. Args: shape: A 1-D integer Tensor or Python array. The shape of the output tensor. minval: A Tensor or Python value of type `dtype`, broadcastable with `maxval`. The lower bound on the range of random values to generate (inclusive). Defaults to 0. maxval: A Tensor or Python value of type `dtype`, broadcastable with `minval`. The upper bound on the range of random values to generate (exclusive). Defaults to 1 if `dtype` is floating point. dtype: The type of the output: `float16`, `float32`, `float64`, `int32`, or `int64`. seed: A Python integer. Used in combination with `tf.random.set_seed` to create a reproducible sequence of tensors across multiple calls. name: A name for the operation (optional). Returns: A tensor of the specified shape filled with random uniform values. Raises: ValueError: If `dtype` is integral and `maxval` is not specified. """ dtype = dtypes.as_dtype(dtype) if dtype not in (dtypes.float16, dtypes.bfloat16, dtypes.float32, dtypes.float64, dtypes.int32, dtypes.int64): raise ValueError("Invalid dtype %r" % dtype) if maxval is None: if dtype.is_integer: raise ValueError("Must specify maxval for integer dtype %r" % dtype) maxval = 1 with ops.name_scope(name, "random_uniform", [shape, minval, maxval]) as name: shape = tensor_util.shape_tensor(shape) # TODO(b/143079601): Remove this once the compatible window is passed. if compat.forward_compatible(2019, 12, 3): # In case of [0,1) floating results, minval and maxval is unused. We do an # `is` comparison here since this is cheaper than isinstance or __eq__. minval_is_zero = minval is 0 # pylint: disable=literal-comparison maxval_is_one = maxval is 1 # pylint: disable=literal-comparison if not minval_is_zero or not maxval_is_one or dtype.is_integer: minval = ops.convert_to_tensor(minval, dtype=dtype, name="min") maxval = ops.convert_to_tensor(maxval, dtype=dtype, name="max") seed1, seed2 = random_seed.get_seed(seed) if dtype.is_integer: result = gen_random_ops.random_uniform_int(shape, minval, maxval, seed=seed1, seed2=seed2, name=name) else: result = gen_random_ops.random_uniform(shape, dtype, seed=seed1, seed2=seed2) if minval_is_zero: if not maxval_is_one: result = result * maxval else: result = math_ops.add(result * (maxval - minval), minval, name=name) else: minval = ops.convert_to_tensor(minval, dtype=dtype, name="min") maxval = ops.convert_to_tensor(maxval, dtype=dtype, name="max") seed1, seed2 = random_seed.get_seed(seed) if dtype.is_integer: result = gen_random_ops.random_uniform_int(shape, minval, maxval, seed=seed1, seed2=seed2, name=name) else: rnd = gen_random_ops.random_uniform(shape, dtype, seed=seed1, seed2=seed2) result = math_ops.add(rnd * (maxval - minval), minval, name=name) # TODO(b/132092188): C++ shape inference inside functional ops does not # cross FuncGraph boundaries since that information is only available in # python. So we manually get the static shape using # `constant_value_as_shape` which *does* cross function boundaries. tensor_util.maybe_set_static_shape(result, shape) return result
def stateless_random_uniform(shape, seed, minval=0, maxval=None, dtype=dtypes.float32, name=None): """Outputs deterministic pseudorandom values from a uniform distribution. This is a stateless version of `tf.random.uniform`: if run twice with the same seeds, it will produce the same pseudorandom numbers. The output is consistent across multiple runs on the same hardware (and between CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU hardware. The generated values follow a uniform distribution in the range `[minval, maxval)`. The lower bound `minval` is included in the range, while the upper bound `maxval` is excluded. For floats, the default range is `[0, 1)`. For ints, at least `maxval` must be specified explicitly. In the integer case, the random integers are slightly biased unless `maxval - minval` is an exact power of two. The bias is small for values of `maxval - minval` significantly smaller than the range of the output (either `2**32` or `2**64`). For full-range (i.e. inclusive of both max and min) random integers, pass `minval=None` and `maxval=None` with an integer `dtype`. For an integer dtype either both `minval` and `maxval` must be `None` or neither may be `None`. For example: ```python ints = tf.random.stateless_uniform( [10], seed=(2, 3), minval=None, maxval=None, dtype=tf.int32) ``` Args: shape: A 1-D integer Tensor or Python array. The shape of the output tensor. seed: A shape [2] Tensor, the seed to the random number generator. Must have dtype `int32` or `int64`. (When using XLA, only `int32` is allowed.) minval: A Tensor or Python value of type `dtype`, broadcastable with `shape` (for integer types, broadcasting is not supported, so it needs to be a scalar). The lower bound on the range of random values to generate. Pass `None` for full-range integers. Defaults to 0. maxval: A Tensor or Python value of type `dtype`, broadcastable with `shape` (for integer types, broadcasting is not supported, so it needs to be a scalar). The upper bound on the range of random values to generate. Defaults to 1 if `dtype` is floating point. Pass `None` for full-range integers. dtype: The type of the output: `float16`, `float32`, `float64`, `int32`, or `int64`. For unbounded uniform ints (`minval`, `maxval` both `None`), `uint32` and `uint64` may be used. name: A name for the operation (optional). Returns: A tensor of the specified shape filled with random uniform values. Raises: ValueError: If `dtype` is integral and only one of `minval` or `maxval` is specified. """ dtype = dtypes.as_dtype(dtype) if dtype not in (dtypes.float16, dtypes.bfloat16, dtypes.float32, dtypes.float64, dtypes.int32, dtypes.int64, dtypes.uint32, dtypes.uint64): raise ValueError("Invalid dtype %r" % dtype) if dtype.is_integer: if (minval is None) != (maxval is None): raise ValueError("For integer dtype {}, minval and maxval must be both " "`None` or both non-`None`.".format(dtype)) if minval is not None and dtype in (dtypes.uint32, dtypes.uint64): raise ValueError("Invalid dtype for bounded uniform integers: %r" % dtype) elif maxval is None: maxval = 1 with ops.name_scope(name, "stateless_random_uniform", [shape, seed, minval, maxval]) as name: shape = tensor_util.shape_tensor(shape) if dtype.is_integer and minval is None: result = gen_stateless_random_ops.stateless_random_uniform_full_int( shape, seed=seed, dtype=dtype, name=name) else: minval = ops.convert_to_tensor(minval, dtype=dtype, name="min") maxval = ops.convert_to_tensor(maxval, dtype=dtype, name="max") if dtype.is_integer: result = gen_stateless_random_ops.stateless_random_uniform_int( shape, seed=seed, minval=minval, maxval=maxval, name=name) else: rnd = gen_stateless_random_ops.stateless_random_uniform( shape, seed=seed, dtype=dtype) result = math_ops.add(rnd * (maxval - minval), minval, name=name) tensor_util.maybe_set_static_shape(result, shape) return result
def random_uniform(shape, minval=0, maxval=None, dtype=dtypes.float32, seed=None, name=None): """Outputs random values from a uniform distribution. The generated values follow a uniform distribution in the range `[minval, maxval)`. The lower bound `minval` is included in the range, while the upper bound `maxval` is excluded. For floats, the default range is `[0, 1)`. For ints, at least `maxval` must be specified explicitly. In the integer case, the random integers are slightly biased unless `maxval - minval` is an exact power of two. The bias is small for values of `maxval - minval` significantly smaller than the range of the output (either `2**32` or `2**64`). Args: shape: A 1-D integer Tensor or Python array. The shape of the output tensor. minval: A 0-D Tensor or Python value of type `dtype`. The lower bound on the range of random values to generate. Defaults to 0. maxval: A 0-D Tensor or Python value of type `dtype`. The upper bound on the range of random values to generate. Defaults to 1 if `dtype` is floating point. dtype: The type of the output: `float16`, `float32`, `float64`, `int32`, or `int64`. seed: A Python integer. Used to create a random seed for the distribution. See `tf.compat.v1.set_random_seed` for behavior. name: A name for the operation (optional). Returns: A tensor of the specified shape filled with random uniform values. Raises: ValueError: If `dtype` is integral and `maxval` is not specified. """ dtype = dtypes.as_dtype(dtype) if dtype not in (dtypes.float16, dtypes.bfloat16, dtypes.float32, dtypes.float64, dtypes.int32, dtypes.int64): raise ValueError("Invalid dtype %r" % dtype) if maxval is None: if dtype.is_integer: raise ValueError("Must specify maxval for integer dtype %r" % dtype) maxval = 1 with ops.name_scope(name, "random_uniform", [shape, minval, maxval]) as name: shape = tensor_util.shape_tensor(shape) minval = ops.convert_to_tensor(minval, dtype=dtype, name="min") maxval = ops.convert_to_tensor(maxval, dtype=dtype, name="max") seed1, seed2 = random_seed.get_seed(seed) if dtype.is_integer: result = gen_random_ops.random_uniform_int(shape, minval, maxval, seed=seed1, seed2=seed2, name=name) else: rnd = gen_random_ops.random_uniform(shape, dtype, seed=seed1, seed2=seed2) result = math_ops.add(rnd * (maxval - minval), minval, name=name) # TODO(b/132092188): C++ shape inference inside functional ops does not # cross FuncGraph boundaries since that information is only available in # python. So we manually get the static shape using # `constant_value_as_shape` which *does* cross function boundaries. tensor_util.maybe_set_static_shape(result, shape) return result
def stateless_random_uniform(shape, seed, minval=0, maxval=None, dtype=dtypes.float32, name=None): """Outputs deterministic pseudorandom values from a uniform distribution. This is a stateless version of `tf.random.uniform`: if run twice with the same seeds, it will produce the same pseudorandom numbers. The output is consistent across multiple runs on the same hardware (and between CPU and GPU), but may change between versions of TensorFlow or on non-CPU/GPU hardware. The generated values follow a uniform distribution in the range `[minval, maxval)`. The lower bound `minval` is included in the range, while the upper bound `maxval` is excluded. For floats, the default range is `[0, 1)`. For ints, at least `maxval` must be specified explicitly. In the integer case, the random integers are slightly biased unless `maxval - minval` is an exact power of two. The bias is small for values of `maxval - minval` significantly smaller than the range of the output (either `2**32` or `2**64`). Args: shape: A 1-D integer Tensor or Python array. The shape of the output tensor. seed: A shape [2] integer Tensor of seeds to the random number generator. minval: A 0-D Tensor or Python value of type `dtype`. The lower bound on the range of random values to generate. Defaults to 0. maxval: A 0-D Tensor or Python value of type `dtype`. The upper bound on the range of random values to generate. Defaults to 1 if `dtype` is floating point. dtype: The type of the output: `float16`, `float32`, `float64`, `int32`, or `int64`. name: A name for the operation (optional). Returns: A tensor of the specified shape filled with random uniform values. Raises: ValueError: If `dtype` is integral and `maxval` is not specified. """ dtype = dtypes.as_dtype(dtype) if dtype not in (dtypes.float16, dtypes.bfloat16, dtypes.float32, dtypes.float64, dtypes.int32, dtypes.int64): raise ValueError("Invalid dtype %r" % dtype) if maxval is None: if dtype.is_integer: raise ValueError("Must specify maxval for integer dtype %r" % dtype) maxval = 1 with ops.name_scope(name, "stateless_random_uniform", [shape, seed, minval, maxval]) as name: shape = tensor_util.shape_tensor(shape) minval = ops.convert_to_tensor(minval, dtype=dtype, name="min") maxval = ops.convert_to_tensor(maxval, dtype=dtype, name="max") if dtype.is_integer: result = gen_stateless_random_ops.stateless_random_uniform_int( shape, seed=seed, minval=minval, maxval=maxval, name=name) else: rnd = gen_stateless_random_ops.stateless_random_uniform( shape, seed=seed, dtype=dtype) result = math_ops.add(rnd * (maxval - minval), minval, name=name) tensor_util.maybe_set_static_shape(result, shape) return result