给定一系列bin概率,如何生成bin计数的随机样本?

问题描述 投票:6回答:3

我有一个整数,需要根据概率分布将其拆分为bin。例如,如果我有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和我的箱数非常大,因此循环并不是一个切实可行的选择。有什么方法可以向量化此操作以加快速度吗?

python numpy random vectorization probability-density
3个回答
4
投票

您可以通过累加来将PDF转换为CDF,使用它来定义0到1之间的一组bin,然后使用这些bin来计算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]

2
投票

您可以将np.bincountnp.bincount一起用于合并操作,以执行与np.searchsorted操作等效的操作。这是实现这些承诺的实现-


0
投票

另一种方法:

© www.soinside.com 2019 - 2024. All rights reserved.