You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mxnet.apache.org by GitBox <gi...@apache.org> on 2018/08/23 01:14:21 UTC

[GitHub] szha closed pull request #12156: Add randn to random module

szha closed pull request #12156: Add randn to random module
URL: https://github.com/apache/incubator-mxnet/pull/12156
 
 
   

This is a PR merged from a forked repository.
As GitHub hides the original diff on merge, it is displayed below for
the sake of provenance:

As this is a foreign pull request (from a fork), the diff is supplied
below (as it won't show otherwise due to GitHub magic):

diff --git a/python/mxnet/ndarray/random.py b/python/mxnet/ndarray/random.py
index d0c83c10e6b..1e941f79aa1 100644
--- a/python/mxnet/ndarray/random.py
+++ b/python/mxnet/ndarray/random.py
@@ -23,8 +23,9 @@
 from .ndarray import NDArray
 
 
-__all__ = ['uniform', 'normal', 'poisson', 'exponential', 'gamma', 'multinomial',
-           'negative_binomial', 'generalized_negative_binomial', 'shuffle']
+__all__ = ['uniform', 'normal', 'randn', 'poisson', 'exponential', 'gamma',
+           'multinomial', 'negative_binomial', 'generalized_negative_binomial',
+           'shuffle']
 
 
 def _random_helper(random, sampler, params, shape, dtype, ctx, out, kwargs):
@@ -151,6 +152,58 @@ def normal(loc=0, scale=1, shape=_Null, dtype=_Null, ctx=None, out=None, **kwarg
                           [loc, scale], shape, dtype, ctx, out, kwargs)
 
 
+def randn(*shape, **kwargs):
+    """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 or NDArray
+        Mean (centre) of the distribution.
+    scale : float or NDArray
+        Standard deviation (spread or width) of the distribution.
+    shape : int or tuple of ints
+        The number of samples to draw. If shape is, e.g., `(m, n)` and `loc` and
+        `scale` are scalars, output shape will be `(m, n)`. If `loc` and `scale`
+        are NDArrays with shape, e.g., `(x, y)`, then output will have shape
+        `(x, y, m, n)`, where `m*n` samples are drawn for each `[loc, scale)` pair.
+    dtype : {'float16','float32', 'float64'}
+        Data type of output samples. Default is 'float32'
+    ctx : Context
+        Device context of output. Default is current context. Overridden by
+        `loc.context` when `loc` is an NDArray.
+    out : NDArray
+        Store output to an existing NDArray.
+
+
+    Examples
+    --------
+    >>> mx.nd.random.randn()
+    2.21220636
+    <NDArray 1 @cpu(0)>
+    >>> mx.nd.random.randn(2, 2)
+    [[-1.856082   -1.9768796 ]
+    [-0.20801921  0.2444218 ]]
+    <NDArray 2x2 @cpu(0)>
+    >>> mx.nd.random.randn(2, 3, loc=5, scale=1)
+    [[4.19962   4.8311777 5.936328 ]
+    [5.357444  5.7793283 3.9896927]]
+    <NDArray 2x3 @cpu(0)>
+    """
+    loc = kwargs.pop('loc', 0)
+    scale = kwargs.pop('scale', 1)
+    dtype = kwargs.pop('dtype', _Null)
+    ctx = kwargs.pop('ctx', None)
+    out = kwargs.pop('out', None)
+    assert isinstance(loc, (int, float))
+    assert isinstance(scale, (int, float))
+    return _random_helper(_internal._random_normal, _internal._sample_normal,
+                          [loc, scale], shape, dtype, ctx, out, kwargs)
+
+
 def poisson(lam=1, shape=_Null, dtype=_Null, ctx=None, out=None, **kwargs):
     """Draw random samples from a Poisson distribution.
 
diff --git a/tests/python/unittest/test_random.py b/tests/python/unittest/test_random.py
index 43e9608934e..75c9b7432d8 100644
--- a/tests/python/unittest/test_random.py
+++ b/tests/python/unittest/test_random.py
@@ -45,6 +45,15 @@ def check_with_device(device, dtype):
                 ('std',  lambda x, params: np.std(x.astype(np.float64)) - params['scale'], tol)
             ]
         },
+        {
+            'name': 'randn',
+            'ndop': mx.nd.random.randn,
+            'params': { 'loc': 10.0, 'scale': 0.5 },
+            'checks': [
+                ('mean', lambda x, params: np.mean(x.astype(np.float64) - params['loc']),  tol),
+                ('std',  lambda x, params: np.std(x.astype(np.float64)) - params['scale'], tol)
+            ]
+        },
         {
             'name': 'uniform',
             'symbol': mx.sym.random.uniform,
@@ -123,10 +132,14 @@ def check_with_device(device, dtype):
         # check directly
         params = symbdic['params'].copy()
         params.update(shape=shape, dtype=dtype, ctx=device)
+        args = ()
+        if name == 'randn':
+            params.pop('shape')  # randn does not accept shape param
+            args = shape
         mx.random.seed(128)
-        ret1 = ndop(**params).asnumpy()
+        ret1 = ndop(*args, **params).asnumpy()
         mx.random.seed(128)
-        ret2 = ndop(**params).asnumpy()
+        ret2 = ndop(*args, **params).asnumpy()
         assert same(ret1, ret2), \
                 "ndarray test: `%s` should give the same result with the same seed" % name
 
@@ -134,12 +147,14 @@ def check_with_device(device, dtype):
             assert np.abs(check_func(ret1, params)) < tol, "ndarray test: %s check for `%s` did not pass" % (check_name, name)
 
         # check multi-distribution sampling
+        if 'inputs' not in symbdic: continue  # randn does not support multi-distribution sampling
+
         params = {'shape': shape, 'dtype': dtype, 'ctx': device}
         params.update({k : mx.nd.array(v, ctx=device, dtype=dtype) for k, v in symbdic['inputs']})
         mx.random.seed(128)
-        ret1 = ndop(**params).asnumpy()
+        ret1 = ndop(*args, **params).asnumpy()
         mx.random.seed(128)
-        ret2 = ndop(**params).asnumpy()
+        ret2 = ndop(*args, **params).asnumpy()
         assert same(ret1, ret2), \
                 "ndarray test: `%s` should give the same result with the same seed" % name
         for i in range(2):
@@ -149,6 +164,8 @@ def check_with_device(device, dtype):
                     err = np.abs(check_func(ret2[i,j], stats))
                     assert err < tol, "%f vs %f: symbolic test: %s check for `%s` did not pass" % (err, tol, check_name, name)
 
+        if 'symbol' not in symbdic: continue  # randn does not have symbol
+
         # check symbolic
         symbol = symbdic['symbol']
         X = mx.sym.Variable("X")


 

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services