Reputation: 9
I have two lists, both the same size, let's call them values and possibility. I want to choose of the values list with discrete probability distribution given by possibility. possibility[i] corresponds to the probability of choosing value[i].
How can I do this in the simplest way in Python?
Upvotes: 0
Views: 1664
Reputation: 176
Take a look into package SciPy, namely scipy.stats.rv_discrete (https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_discrete.html).
>>> from scipy import stats
>>> import numpy as np
>>> xk = np.arange(7)
>>> pk = (0.1, 0.2, 0.3, 0.1, 0.1, 0.0, 0.2)
>>> myRV = stats.rv_discrete(name="MyRandomVar", values=(xk, pk))
>>> sample = myRV.rvs(size=5) # sample == array([2, 2, 0, 6, 1])
Upvotes: 1
Reputation: 1228
Here's a solution that generates a random number (0, 1) and then subtracts the probabilities to find which value to return.
import random
def choose_with_probability(probs, values):
val = random.random()
for x in enumerate(values):
val -= probs[x[0]]
if(val < 0):
return x[1]
# probs = [0.5, 0.2, 0.1, 0.1, 0.05, 0.05]
# values = ['a', 'b', 'c', 'd', 'e', 'f']
The result is 'a' being returned 50% of the time, 'b' 20%, 'c' 10% etc.
random.random()
returns a number from 0 to 1.
enumerate()
creates a numbered list from the argument list. e.g. ['a', 'b', 'c']
becomes [[0, 'a'], [1, 'b'], [2, 'c']]
.
I used the enumeration index to find the probability of each value since both lists correspond 1:1.
Upvotes: 0