【发布时间】:2015-10-22 04:19:11
【问题描述】:
我有一个整数,需要根据概率分布分成多个 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 和我的 bin 数量非常大,因此循环并不是一个真正可行的选择。有什么方法可以矢量化此操作以加快速度?
【问题讨论】:
标签: python numpy random vectorization probability-density