Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cumulative weights in random.choices

I am confused using the new random.choices in Python 3.6.

Here is the doc:

random.choices(population, weights=None, *, cum_weights=None, k=1)

-- Return a k sized list of elements chosen from the population with replacement. If the population is empty, raises IndexError.

They give an example: weights=[10, 5, 30, 5] and I don't know what this means. Why don't they sum to 100? If my population is [1, 2, 3, 4] -- does this mean that a choice of '10' occurs with probability 0.1?

like image 904
Henry P. Avatar asked Mar 31 '19 12:03

Henry P.


People also ask

What is weight in random choices?

Weighted random choices mean selecting random elements from a list or an array by the probability of that element. We can assign a probability to each element and according to that element(s) will be selected. By this, we can select one or more than one element from the list, And it can be achieved in two ways.

What are cumulative weights?

cumulative weights is just the prefix sum of the weight by definition.

What is random choice method?

Python Random choice() Method The choice() method returns a randomly selected element from the specified sequence. The sequence can be a string, a range, a list, a tuple or any other kind of sequence.


1 Answers

The total weight is 10+5+30+5=50.

Suppose the population is [1,2,3,4].

It returns 1 with probability 10/50 = 0.2

It returns 2 with probability 5/50 = 0.1

It returns 3 with probability 30/50 = 0.6

It returns 4 with probability 5/50 = 0.1

like image 155
Siong Thye Goh Avatar answered Sep 23 '22 08:09

Siong Thye Goh