Search code examples
pythonnumpyprobability

Is there a function similar to np.random.choice that has a higher probability of choosing the lower values in the probability distribution?


I have an array of objects with a corresponding probability for each, say

sample = [a, b, c, d, e, f]
probability = [0.1, 0.15, 0.6, 0.05, 0.03, 0.07]

For most functions in my class this is perfect to use with np.random.choice as I want to select the values with the highest percentage chance.

On one of the functions though, I need it to be biased to the values with a lower probability (i.e. more likely to pick e and d in the sample than c).

Is there a function that can do this or do I need to consider converting the probability to some inverse probability like

inverse_probability = [(1-x) for x in probability]
inverse_probability = [x/sum(inverse_probability) for x in probability]

and then use this in the np.random.choice function?

Thanks in advance!


Solution

  • This is a simple solution but should solve your problem:

    sample = ['a', 'b', 'c', 'd', 'e', 'f']
    probability = [0.1, 0.15, 0.6, 0.05, 0.03, 0.07]
    np.random.choice(a=sample, p=probability)
    
    

    Solution 1:

    inverse_probability = [(1-x) for x in probability]
    inverse_probability = [x/sum(inverse_probability) for x in inverse_probability]
    np.random.choice(a=sample, p=inverse_probability)
    

    Solution 2:

    inverse_probability = [1/x for x in probability]
    inverse_probability = [x/sum(inverse_probability) for x in inverse_probability]
    np.random.choice(a=sample, p=inverse_probability)