khanna-lab / cadre

Other
0 stars 0 forks source link

random.choices() #1

Closed khanna7 closed 2 years ago

khanna7 commented 2 years ago

https://github.com/khanna7/cadre/blob/0f7036c9898d89d6b7d0a660ed0036a171f7901c/python/simple-alc-use-transitions-oop.py#L9

How to take weighted samples in Python? I have

from numpy import random

race_distribution = [
    71.4/100, #white alone
    8.5/100, #black alone
    16.3/100, #hispanic alone
    3.7/100 #asian alone
]

race_cats = ["white", "black", "hispanic", "other"]

self.race = random.choice(race_cats, weights=race_distribution)

gives error:

AttributeError: module 'numpy.random' has no attribute 'choices'
yuruizhang9734 commented 2 years ago
  1. the sum of the race_distribution is not 1
  2. in the random.choice function , instead of using weights = race_distribution, use p=race_distribution

from numpy import random

race_distribution = [ 71.4/100, #white alone 8.5/100, #black alone 16.3/100, #hispanic alone 3.8/100 #asian alone ]

race_cats = ["white", "black", "hispanic", "other"]

self.race = random.choice(race_cats, p=race_distribution)

this should work

dsheeler commented 2 years ago

I concur

khanna7 commented 2 years ago

Thanks guys! 🙏🏾

On Sat, Jun 4, 2022 at 9:44 PM Daniel Sheeler @.***> wrote:

I concur

— Reply to this email directly, view it on GitHub https://github.com/khanna7/cadre/issues/1#issuecomment-1146721069, or unsubscribe https://github.com/notifications/unsubscribe-auth/AB6QUBHZOUONBDZF6OJ7HQDVNQA6VANCNFSM5XWJN6MQ . You are receiving this because you authored the thread.Message ID: @.***>

khanna7 commented 2 years ago

Works!