【问题标题】:Weighed numpys random.choice for intervals间隔的加权 numpys random.choice
【发布时间】:2020-11-05 10:25:30
【问题描述】:

我想从半开区间(例如[1,5), [5,10), [10,25) 等)伪随机地创建一个交易值数组。区间中的每个数字都有相同的机会被选中,但我想调整获得某些区间而不是其他区间的概率。流程应该是这样的:

1: Pick any of the defined intervals > Pick a random number in the interval > Append number in array
2: Pick any of the defined intervals > Pick a random number in the interval > Append number in array
...
n: Pick any of the defined intervals > Pick a random number in the interval > Append number in array

我的代码是:

import numpy as np
# set interval limits
a,b,c,d,e,f,g,h,i,j = 1,5,10,25,50,100,200,300,500,1000
# start picking random numbers
np.random.seed(33)
trx_value = np.random.choice([np.random.uniform(a,b), 
                              np.random.uniform(b,c),
                              np.random.uniform(c,d),
                              np.random.uniform(d,e),
                              np.random.uniform(e,f),
                              np.random.uniform(f,g),
                              np.random.uniform(g,h),
                              np.random.uniform(h,i),
                              np.random.uniform(i,j)], 20, 
                              p=[0.1, 0.15, 0.2, 0.2, 0.15, 0.1, 0.05, 0.03, 0.02])
trx_value

它似乎以不同的方式工作,因为结果没有显示我期望的值的唯一性:

> array([  8.22611761,   8.22611761, 127.05325134,   8.22611761,
>        266.53172436,  35.43526485,  35.43526485,  88.57366253,
>        127.05325134,  12.38946805, 266.53172436, 127.05325134,
>         12.38946805,  35.43526485, 127.05325134,  12.38946805,
>        266.53172436,   8.22611761])

它似乎在做这样的事情:

1: For each interval, pick a random number > Store this number in a pool
2: Pick a random number from the pool > Append number in array
...
n: Pick a random number from the pool > Append number in array

我确定这是一个思考问题,但我想知道不使用 for 循环是否可行

【问题讨论】:

    标签: python numpy random


    【解决方案1】:

    由于您希望选择的所有发行版都是统一的,我建议您进行以下设置。

    interval_p = np.array([0.1, 0.15, 0.2, 0.2, 0.15, 0.1, 0.05, 0.03, 0.02])
    interval_lo = np.array([1,5,10,25,50,100,200,300,500])
    interval_hi = np.concatenate([lo[1:], [1000]])
    interval_width = interval_hi - interval_lo
    
    n = 20
    c = np.random.choice(len(interval_p), p=interval_p, size=n)
    results = interval_lo[c] + np.random.uniform(size=n) * interval_width[c]
    

    这是可行的,因为我们可以使用 a + r*(b-a) 将 [0, 1] 上的均匀分布 r 重新缩放为 [a, b] 上的任何均匀分布。

    【讨论】:

    • 您可以只创建interval = np.array([1,5,10,25,50,100,200,300,500,1000]),然后使用interval_width = np.diff(interval),然后使用interval[:-1] 而不是interval_lo。使其更具可读性。
    • 谢谢!它有效,并且使用@DanielF 建议更具可读性。你可以说当你与具有强大数学背景的人打交道时:)
    猜你喜欢
    • 2022-01-19
    • 2013-08-15
    • 1970-01-01
    相关资源
    最近更新 更多