Swier
Swier

Reputation: 4186

python numpy: evaluate list of probabilities to randomly generated binary values

I have an array of probabilities, and I want to use those probabilities to generate an array of picked values, each value picked with the corresponding probability.

Example:

in:  [ 0.5,  0.5,  0.5,  0.5, 0.01, 0.01, 0.99, 0.99]
out: [   0,    1,    1,    0,    0,    0,    1,    1]

I'd like to use numpy native functions for this, rather than the following loop:

array_of_probs = [0.5, 0.5, 0.5, 0.5, 0.01, 0.01, 0.99, 0.99]
results = np.zeros(len(array_of_probs))
for i, probs in enumerate(array_of_probs):
  results[i] = np.random.choice([1, 0], 1, p=[probs, 1-probs])

Upvotes: 0

Views: 353

Answers (1)

Erwin Haas
Erwin Haas

Reputation: 46

You can easily calculate this by comparing the array with a random generated array, as the probability that a random number between 0 and 1 is smaller than 0.3 is 0.3.

E.g.

np.random.rand(len(odds)) < odds

Upvotes: 2

Related Questions