Probabilistic selection from a numpy array

Does Numpy have any built-in functions for randomly selecting values ​​from a 1D numpy array with a higher weight value given for values ​​at the end of the array? Is there an easier way to do this than to define a malformed distribution and fetch from it to get array indices?

+4
source share
1 answer

You can give weight np.choiceas shown below:

a = np.random.random(100)    # an array to draw from
n = 10                       # number of values to draw
i = np.arange(a.size)        # an array of the index value for weighting
w = np.exp(i/10.)            # higher weights for larger index values
w /= w.sum()                 # weight must be normalized

Now you can access your values:

np.random.choice(a, size=n, p=w)

, , , 10; :

np.exp(i/50.):

In [38]: np.random.choice(a, size=n, p=w)
Out[38]: array([37, 53, 45, 22, 88, 69, 56, 86, 96, 24])

np.exp(i):

In [41]: np.random.choice(a, size=n, p=w)
Out[41]: array([99, 99, 98, 99, 99, 99, 99, 97, 99, 98])

, replace=False, ( , ). . :

In [33]: np.random.choice(a, size=n, replace=False, p=w)
Out[33]: array([99, 84, 86, 91, 87, 81, 96, 89, 97, 95])

In [34]: np.random.choice(a, size=n, replace=True, p=w)
Out[34]: array([94, 98, 99, 98, 97, 99, 91, 96, 97, 93])

:

, - :

idx = np.random.poisson(size=10)

:

a[-idx-1]
+6

All Articles