在给定一系列箱子概率的情况下,如何生成箱子计数的随机样本?

2024-04-24 12:21:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个整数,它需要根据概率分布分成若干个箱子。例如,如果我让N=100对象进入[0.02, 0.08, 0.16, 0.29, 0.45],那么您可能得到[1, 10, 20, 25, 44]。在

import numpy as np
# sample distribution
d = np.array([x ** 2 for x in range(1,6)], dtype=float)
d = d / d.sum()
dcs = d.cumsum()
bins = np.zeros(d.shape)
N = 100
for roll in np.random.rand(N):
    # grab the first index that the roll satisfies
    i = np.where(roll < dcs)[0][0]  
    bins[i] += 1

实际上,N和我的垃圾箱数量非常大,所以循环并不是一个可行的选择。我有什么方法可以使这个操作加速吗?在


Tags: thesample对象inimportnumpyforas
2条回答

您可以通过求累计数将PDF转换为CDF,使用此函数定义一组介于0和1之间的存储单元,然后使用这些存储单元计算N长随机均匀向量的直方图:

cdf = np.cumsum([0, 0.02, 0.08, 0.16, 0.29, 0.45])     # leftmost bin edge = 0
counts, edges = np.histogram(np.random.rand(100), bins=cdf)

print(counts)
# [ 4,  8, 16, 30, 42]

您可以将^{}与{a2}一起用于binning操作,以执行roll < dcs操作的等效操作。以下是实现这些承诺的方法-

bins = np.bincount(np.searchsorted(dcs,np.random.rand(N),'right'))

使用给定参数的运行时测试-

^{pr2}$

相关问题 更多 >