0

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])
2
  • 1
    A note about terminology: "odds" conventionally means a ratio of probabilities. Odds of A against B = p(A)/p(B). Odds can be any nonnegative number while probabilities are between 0 and 1 inclusive. Obviously if you have odds you can calculate probabilities and vice versa. Looks like you have probabilities and not odds in this case, maybe you want to adjust the title and text. Commented Nov 6, 2017 at 18:03
  • @robertdodier you're right, thanks, I'll fix it Commented Nov 6, 2017 at 18:05

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

I think you want < rather than > here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.