我有:
我想做的是:
目前,我已经设法让这个工作使用循环,你可以看到下面。这对于一小部分模拟人生来说是很好的,但是在实践中,模拟人生的数量将是成千上万,这意味着我的代码太慢了。你知道吗
def allocate_N(N, var_index):
"""Make N choices from cats for a given variable, and return
the incides of each category
var_index is the position of the variable in n_choices"""
allocation = np.random.choice(cats, size=N, p=probs[:, var_index])
allocation_sorted = np.argsort(cats)
ypos = np.searchsorted(cats[allocation_sorted], allocation)
cat_indices = allocation_sorted[ypos]
return cat_indices
def add_to_sim(sims, cat_indices, var_index):
"""Takes the category indices from allocate_n and adds 1 to
sims at the corresponding location for each occurrence of
the category in cat_indices"""
from collections import Counter
a = Counter(list(cat_indices))
vals = [1*a[j] for j in cat_indices]
pos = [(var_index, x) for x in cat_indices]
sims[tuple(np.transpose(pos))] = vals
# For each variable and each row in sims, make N allocations
# and add results to 'sims'
for var_index in range(len(n_choices.T)):
sim_count = 0
# slice is (vars x cats), a single row of 'sims'
for slice in sims:
N = n_choices[sim_count, var_index]
if N > 0:
cat_indices = allocate_N(N, var_index)
add_to_sim(slice, cat_indices, var_index)
sim_count += 1
我肯定有办法把它矢量化?我能够使用方法here同时为每个变量做一个随机选择,但我不确定如何将其应用于我的特定问题。你知道吗
谢谢你的帮助!你知道吗
你所描述的似乎是multinomial distribution的样本。你可以直接从分发处取样。不幸的是,每个模拟和变量的分布参数(试验次数和概率)都会发生变化,
np.random.multinomial
和scipy.stats.multinomial
都不允许使用多组参数进行矢量化采样。这意味着,如果你想这样做,你必须用循环来做。至少,您的代码可以简化为:注意:如果您愿意使用Numba,您仍然可以更快地完成此操作,函数如下:
编辑:一个可能的替代解决方案,不使用多项式采样只有一个循环可以是:
我不确定这是否会更快,因为它会生成许多中间数组。我想这取决于问题的特定参数,但如果Numba解决方案不是最快的,我会感到惊讶。你知道吗
相关问题 更多 >
编程相关推荐