Generating random numbers with weighted probabilities in python

Given a positive integer array a , the goal is to generate 5 random numbers depending on the weight they have in the array.

For instance:

 a = [2,3,4,4,4,4,4,6,7,8,9] 

In this case, the number 4 appeared 5 times, in this case, the number 4 should have a probability of 5/11.

Numbers should not be repeated.

+5
source share
3 answers

Given a , an array of positive integers, you first need to calculate the frequency of each integer. For example, using bincount :

 >>> a = [2,3,4,4,4,4,4,4,5,6,7,8,9,4,9,2,3,6,3,1] >>> b = np.bincount(a) 

b indicates the frequency of each integer in a . The corresponding set of weights is therefore an array of b/len(a) . Using np.random.choice with these weights and replace=False , you should give you what you need:

 >>> np.random.choice(np.arange(len(b)), 5, p=b/len(a), replace=False) array([5, 9, 4, 3, 8]) >>> np.random.choice(np.arange(len(b)), 5, p=b/len(a), replace=False) array([7, 4, 6, 9, 1]) >>> np.random.choice(np.arange(len(b)), 5, p=b/len(a), replace=False) array([3, 7, 4, 9, 6]) 

If you are not working only with positive integers or working with large positive integers, @ user2357112 indicates in the comments below that np.unique provides a different solution. Here you should write:

 >>> choices, counts = np.unique(a, return_counts=True) >>> np.random.choice(choices, 5, p=counts/len(a), replace=False) array([9, 8, 2, 4, 5]) 
+5
source

You are numpy.random.multinomial looking for numpy.random.multinomial For example, np.random.multinomial(1, [1/6.]*6, size=1) rolls honest bones once. After you get the result, you can update the probability vector (should be summed to 1) as you wish. For example numpy.random.multinomial(1, [1/2., 1/2., 0., 0., 0., 0.], size=1) .

0
source

The simplest solution (and possibly the most inefficient) might be the following:

 import random def get_randoms(n, a): a = a[:] r = [] for i in range(n): r.append(random.choice(a)) a = [y for y in a if y != r[-1]] return r print get_randoms(5, [2,3,4,4,4,4,4,4,5,6,7,8,9,4,9,2,3,6,3,1]) 

The output may be something like

 [8, 2, 3, 6, 9] 
0
source

Source: https://habr.com/ru/post/1241042/


All Articles