首页 > 解决方案 > 如何根据分布选择样本?

问题描述

我有一个元素数组 [a_1, a_2, ... a_n] 和与此元素 [p_1, p_2, ..., p_n] 关联的概率数组。

我想根据概率 [p_1,p_2,...,p_n] 从 [a_1,...a_n], k << n 中选择“k”个元素。

如何在 python 中编写代码?非常感谢,我没有编程经验

标签: pythonrandomsampling

解决方案


利用numpy.random.choice

例子:

from numpy.random import choice

sample_space = np.array([a_1, a_2, ... a_n]) # substitute the a_i's 
discrete_probability_distribution = np.array([p_1, p_2, ..., p_n]) # substitute the p_i's 

# picking N samples
N = 10
for _ in range(N): 
    print(choice(sample_space, discrete_probability_distribution) 

推荐阅读