Numpy: Generate multiple random samples from parameter arrays

Ayam :

I have three parameter arrays, each containing n parameter values. Now I need to draw m independent samples using the same parameter settings, and I was wondering if there is an efficient way of doing this?

Example:

p1 = [1, 2, 3, 4], p2 = [4,4,4,4], p3 = [6,7,7,5]

One sample would be generated as:

np.random.triangular(left=p1, mode=p2, right=p3)

resulting in

[3, 6, 3, 4.5]

But I would like to get m of those, in a single ndarray ideally.

A solution could of course be to initiate a sample ndarray of size [n, m] and fill each column using a loop. However, generating all random values simultaneously is generally quicker, hence I would like to figure out if that's possible.

NOTE: adding the parameter 'size=(n,m)' does not work for array valued parameter values

senderle :

It's true that strictly speaking, adding the parameter size=(n, m) doesn't work. But size=(m, n) does!

In general, in numpy sizes, the number of rows comes first.

>>> numpy.random.triangular(left=p1, mode=p2, right=p3, size=(10, 4))
array([[2.90526206, 3.90549642, 4.17820463, 4.49103927],
       [4.128539  , 5.64750789, 4.2343925 , 4.14951323],
       [4.55117141, 4.18380231, 4.94283228, 4.17310084],
       [3.7047425 , 6.19969199, 3.9318881 , 4.73317286],
       [5.0613046 , 4.88435654, 4.04345036, 4.41236136],
       [3.6946254 , 2.28868213, 4.29268451, 4.61406735],
       [4.26315216, 3.84219428, 4.79651309, 4.02510467],
       [3.1213574 , 3.87407067, 4.20976142, 4.11963155],
       [2.89005644, 4.43081604, 5.96604977, 4.0194683 ],
       [5.28800737, 3.80200832, 4.45966515, 4.46419704]])

This can be generalized for arrays that broadcast in more complex ways. Here's an example that creates four distinct samples of a 2x2x2 array based on broadcasted parameters. Note that again, the first value is the number of samples, and the remaining ones describe the shape of each sample:

>>> numpy.random.triangular(a[:, None, None],
...                         a[None, :, None] + 2,
...                         a[None, None, :] + 4,
...                         size=(4, 2, 2, 2))
array([[[[1.96335621, 1.88351682],
         [2.27347214, 3.23075503]],

        [[2.53612351, 2.33322979],
         [2.73651868, 2.7414705 ]]],


       [[[3.80046148, 3.83468891],
         [3.43258814, 3.33174839]],

        [[3.05200913, 4.47039698],
         [2.89013357, 1.99638614]]],


       [[[1.91325759, 2.64773446],
         [1.73132514, 3.47843725]],

        [[1.88526414, 2.86937885],
         [3.12001437, 1.58742945]]],


       [[[0.58692663, 1.08249125],
         [3.4744866 , 1.95300333]],

        [[1.72887756, 2.68527515],
         [1.95189437, 4.49416249]]]])

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=361048&siteId=1