Hikmat
Hikmat

Reputation: 57

Numpy random choice function gives weird results

I have a list of numbers and other list of probabilities which corresponds to these numbers. I am trying to select a number from numbers list based on probability. For this purpose I use random.choice function from NumPy library. As far as i know random.choice function doesn't have to select 1st entry based on its probability(it is equals to zero). However after several iteration it selects first entry.

>>>  import numpy as np
>>> a = [1, 2, 3, 4, 5]
>>>  p = [0.0, 0.97, 0.97, 0.030000000000000027, 0.030000000000000027]
>>>  np.random.choice(a, 1, p)[0]
1

Can anybody help me out?

Upvotes: 0

Views: 843

Answers (1)

Mike Müller
Mike Müller

Reputation: 85622

You are using it wrong. The signature ofchoice is:

choice(a, size=None, replace=True, p=None)

Therefore use it with a keyword argument:

>>> a = np.arange(1, 6)
>>> p = [0, 0.04, 0.9, 0.03, 0.03]
>>> np.random.choice(a, p=p)
3

You do:

np.random.choice(a, 1, p)

That means your p is the argument replace, not actually p.

Furthermore, your probabilities p need to sum to 1.

Upvotes: 3

Related Questions