Monday, July 5, 2010

Sampling Indices From Weight Vector

Here is the code
def w_choice(lst):
n = random.uniform(0, 1)
for item, weight in enumerate(lst):
if n < weight:
n = n - weight
return item

# testing
prob = [0.1, 0.2, 0.5, 0.2]
print w_choice(prob)
This function will return the indeces from a sequence depending on the weights present in that sequence. We modified this code here to get the function above.

The code above assumes normalized weight vector, that is, all probability values in the vector should add to one. If the parameter passed into w_choice is not normalized, then this normalization can be performed with a single line of Python code at the beginning of w_choice:
lst = lst / sum(lst)

No comments:

Post a Comment