lundi 6 novembre 2017

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

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

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_odds = [0.5, 0.5, 0.5, 0.5, 0.01, 0.01, 0.99, 0.99]
results = np.zeros(len(array_of_odds))
for i, odds in enumerate(array_of_odds):
  results[i] = np.random.choice([1, 0], 1, p=[odds, 1-odds])




Aucun commentaire:

Enregistrer un commentaire