A weighted version of random.choice

后端 未结 25 1973
闹比i
闹比i 2020-11-21 06:29

I needed to write a weighted version of random.choice (each element in the list has a different probability for being selected). This is what I came up with:



        
25条回答
  •  梦谈多话
    2020-11-21 06:50

    Here is another version of weighted_choice that uses numpy. Pass in the weights vector and it will return an array of 0's containing a 1 indicating which bin was chosen. The code defaults to just making a single draw but you can pass in the number of draws to be made and the counts per bin drawn will be returned.

    If the weights vector does not sum to 1, it will be normalized so that it does.

    import numpy as np
    
    def weighted_choice(weights, n=1):
        if np.sum(weights)!=1:
            weights = weights/np.sum(weights)
    
        draws = np.random.random_sample(size=n)
    
        weights = np.cumsum(weights)
        weights = np.insert(weights,0,0.0)
    
        counts = np.histogram(draws, bins=weights)
        return(counts[0])
    

提交回复
热议问题