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?
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.
cumulative weights is just the prefix sum of the weight by definition.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With