Search code examples
pythonlistnumpyrandomnumpy-ndarray

How to assign weights to numpy random choice based on largest values?


So given a numpy array of numbers, for example:

np.array([9, 4, 50, 6, 7, 19, 30])

I want to write a function that randomly chooses the index of one of the elements in the array. However, I want the indices with larger values (for example indices 2 and 6) to have a bigger probability to be chosen.

I have thought about using numpy.random.choice, however I do not know how I should predefine the weights. The numpy.random.choice function must be given a list of probabilities for each of the entries in the array, and it should sum to 1. But I really struggle with understanding how to calculate such probabilities for my problem. Does someone have some tips? I would really appreciate some help


Solution

  • Try this:

    import numpy as np
    
    
    a = np.array([9, 4, 50, 6, 7, 19, 30])
    
    weights = a/sum(a)
    print(sum(weights))  # 1.0
    
    np.random.choice(a,p=weights)