mxnet.numpy_extension.random¶
Namespace for ops used in imperative programming.
Functions
|
Creates a Bernoulli distribution parameterized by |
|
Concurrent sampling from multiple categorical distributions. |
|
Concurrent sampling from multiple multinomial distributions. |
|
Draw random samples from a normal (Gaussian) distribution. |
|
Seeds the random number generators in MXNet. |
|
Draw samples from a uniform distribution. |
- mxnet.numpy_extension.random.bernoulli(prob=None, logit=None, size=None, dtype=None, device=None, out=None)[source]¶
Creates a Bernoulli distribution parameterized by
proborlogit(but not both).Samples are binary (0 or 1). They take the value 1 with probability p and 0 with probability 1 - p.
- Parameters:
prob (float, ndarray) – The probability of sampling ‘1’. Only one of prob or logit should be passed in.
logit (float, ndarray) – The log-odds of sampling ‘1’. Only one of prob or logit should be passed in.
size (int or tuple of ints, optional) – Output shape. If the given shape is, e.g.,
(m, n, k), thenm * n * ksamples are drawn. Default is None, in which case a single value is returned.dtype (dtype, optional) – Desired dtype of the result. All dtypes are determined by their name, i.e., ‘int64’, ‘int’, etc, so byteorder is not available and a specific precision may have different C types depending on the platform. The default value is ‘np.float32’.
device (Device, optional) – Device context of output. Default is current device.
out (symbol, optional) – The output symbol (default is None).
- Returns:
out – Drawn samples from the parameterized bernoulli distribution.
- Return type:
Examples
>>> prob = np.random.uniform(size=(4,4)) >>> logit = np.log(prob) - np.log(1 - prob) >>> npx.random.bernoulli(logit=logit) array([[0., 1., 1., 1.], [0., 1., 1., 1.], [0., 1., 0., 0.], [1., 0., 1., 0.]])
>>> npx.random.bernoulli(prob=prob) array([[0., 1., 0., 1.], [1., 1., 1., 1.], [1., 1., 1., 0.], [1., 0., 1., 0.]])
- mxnet.numpy_extension.random.categorical(data=None, shape=_Null, get_prob=_Null, dtype=_Null, out=None, name=None, **kwargs)¶
Concurrent sampling from multiple categorical distributions.
data is an n dimensional array whose last dimension has length k, where k is the number of possible outcomes of each categorical distribution. This operator will draw shape samples from each distribution. If shape is empty one sample will be drawn from each distribution.
If get_prob is true, a second array containing log likelihood of the drawn samples will also be returned. This is usually used for reinforcement learning where you can provide reward as head gradient for this array to estimate gradient.
Note that the input distribution must be normalized, i.e. data must sum to 1 along its last axis.
Examples:
probs = [[0, 0.1, 0.2, 0.3, 0.4], [0.4, 0.3, 0.2, 0.1, 0]] // Draw a single sample for each distribution sample_categorical(probs) = [3, 0] // Draw a vector containing two samples for each distribution sample_categorical(probs, shape=(2)) = [[4, 2], [0, 0]] // requests log likelihood sample_categorical(probs, get_prob=True) = [2, 1], [0.2, 0.3]
- Parameters:
data (ndarray) – Distribution probabilities. Must sum to one on the last axis.
shape (Shape(tuple), optional, default=[]) – Shape to be sampled from each random distribution.
get_prob (boolean, optional, default=0) – Whether to also return the log probability of sampled result. This is usually used for differentiating through stochastic variables, e.g. in reinforcement learning.
dtype ({'float16', 'float32', 'float64', 'int32', 'uint8'},optional, default='int32') – DType of the output in case this can’t be inferred.
out (ndarray, optional) – The output ndarray to hold the result.
- Returns:
out – The output of this function.
- Return type:
- mxnet.numpy_extension.random.multinomial(n=None, p=None, shape=_Null, ctx=_Null, dtype=_Null, out=None, name=None, **kwargs)¶
Concurrent sampling from multiple multinomial distributions.
Samples are distributed according to a multinomial distribution parametrized by n (number of experiments) and p (success probabilities of the k possible outcomes in each experiment). Samples will always be returned as a floating point data type.
Note that the input distribution must be normalized, i.e. p must sum to 1 along its last axis.
Examples:
n = [5., 6.] probs = [[0., 0.1, 0.2, 0.3, 0.4], [0.4, 0.3, 0.2, 0.1, 0.]] multinomial(n, probs) = [[0., 0., 0., 3., 2.], [0., 3., 1., 2., 0.]]
- Parameters:
n (ndarray) – Number of experiments
p (ndarray) – Probability of every outcome in each experiment. Must sum to 1 on the last axis
shape (Shape(tuple), optional, default=[]) – Shape to be sampled from each random distribution.
ctx (string, optional, default='') – Context of output, in format [cpu|gpu|cpu_pinned](n). Only used for imperative calls.
dtype ({'float16', 'float32', 'float64', 'int32', 'uint8'},optional, default='int32') – DType of the output in case this can’t be inferred.
out (ndarray, optional) – The output ndarray to hold the result.
- Returns:
out – The output of this function.
- Return type:
- mxnet.numpy_extension.random.normal_n(loc=0.0, scale=1.0, batch_shape=None, dtype=None, device=None)[source]¶
Draw random samples from a normal (Gaussian) distribution.
Samples are distributed according to a normal distribution parametrized by loc (mean) and scale (standard deviation).
- Parameters:
loc (float, optional) – Mean (centre) of the distribution.
scale (float, optional) – Standard deviation (spread or “width”) of the distribution.
batch_shape (int or tuple of ints, optional) – Batch shape. If the given shape is, e.g.,
(m, n, k), thenm * n * k * broadcast(low, high).sizesamples are drawn. If size isNone(default), a scalar tensor containing a single value is returned iflowandhighare both scalars. Otherwise,np.broadcast(loc, scale).sizesamples are drawn.dtype ({'float16', 'float32', 'float64'}, optional) – Data type of output samples. Default is ‘float32’
device (Device, optional) – Device context of output, default is current device.
- Returns:
out – Drawn samples from the parameterized normal distribution.
- Return type:
Notes
The probability density for the Gaussian distribution is
\[p(x) = \frac{1}{\sqrt{ 2 \pi \sigma^2 }} e^{ - \frac{ (x - \mu)^2 } {2 \sigma^2} },\]where \(\mu\) is the mean and \(\sigma\) the standard deviation. The square of the standard deviation, \(\sigma^2\), is called the variance.
The function has its peak at the mean, and its “spread” increases with the standard deviation (the function reaches 0.607 times its maximum at \(x + \sigma\) and \(x - \sigma\) [2]). This implies that numpy.random.normal is more likely to return samples lying close to the mean, rather than those far away.
References
Examples
>>> mu, sigma = 0, 0.1 # mean and standard deviation >>> s = np.random.normal(mu, sigma, 1000)
Verify the mean and the variance:
>>> np.abs(mu - np.mean(s)) < 0.01 array(True)
- mxnet.numpy_extension.random.seed(seed, device='all')[source]¶
Seeds the random number generators in MXNet.
This affects the behavior of modules in MXNet that uses random number generators, like the dropout operator and ndarray’s random sampling operators.
- Parameters:
Notes
Random number generators in MXNet are device specific. npx.random.seed(seed) sets the state of each generator using seed and the device id. Therefore, random numbers generated from different devices can be different even if they are seeded using the same seed.
To produce identical random number sequences independent of the device id, set optional device argument. This produces the same sequence of random numbers independent of the device id, but the sequence can be different on different kind of devices as MXNet’s random number generators for CPU and GPU use different algorithms.
Example
>>> from mxnet import np, npx >>> npx.set_np() >>> npx.random.seed(0) >>> np.random.uniform() array(0.5488135) >>> npx.random.seed(128) >>> np.random.uniform() array(0.03812965) >>> npx.random.seed(128) >>> np.random.uniform() array(0.03812965) >>> npx.random.seed(128) >>> np.random.uniform(device=npx.gpu(0)) array(0.9894903, device=gpu(0)) >>> npx.random.seed(128) >>> np.random.uniform(device=npx.gpu(0)) array(0.9894903, device=gpu(0))
- mxnet.numpy_extension.random.uniform_n(low=0.0, high=1.0, batch_shape=None, dtype=None, device=None)[source]¶
Draw samples from a uniform distribution.
Samples are uniformly distributed over the half-open interval
[low, high)(includes low, but excludes high). In other words, any value within the given interval is equally likely to be drawn by uniform.- Parameters:
low (float, ndarray, optional) – Lower boundary of the output interval. All values generated will be greater than or equal to low. The default value is 0.
high (float, ndarray, optional) – Upper boundary of the output interval. All values generated will be less than high. The default value is 1.0.
batch_shape (int or tuple of ints, optional) – Batch shape. If the given shape is, e.g.,
(m, n, k), thenm * n * k * broadcast(low, high).sizesamples are drawn. If size isNone(default), a scalar tensor containing a single value is returned iflowandhighare both scalars. Otherwise,np.broadcast(low, high).sizesamples are drawn.dtype ({'float16', 'float32', 'float64'}, optional) – Data type of output samples. Default is ‘float32’
device (Device, optional) – Device context of output. Default is current device.
- Returns:
out – Drawn samples from the parameterized uniform distribution.
- Return type:
See also
randintDiscrete uniform distribution, yielding integers.
randConvenience function that accepts dimensions as input, e.g.,
rand(2,2)would generate a 2-by-2 array of floats, uniformly distributed over[0, 1).
Notes
The probability density function of the uniform distribution is
\[p(x) = \frac{1}{b - a}\]anywhere within the interval
[a, b), and zero elsewhere.When
high==low, values oflowwill be returned. Ifhigh<low, the results are officially undefined and may eventually raise an error, i.e. do not rely on this function to behave when passed arguments satisfying that inequality condition.