加权随机样本,无需在python中进行替换 [英] Weighted random sample without replacement in python
问题描述
我需要获取一个 k大小的样本,而无需从种群中进行替换,种群中的每个成员都有相关的权重(W).
I need to obtain a k-sized sample without replacement from a population, where each member of the population has a associated weight (W).
Numpy的 random.choices 未经替换将无法执行此任务,并且 random.sample 不会接受加权输入.
Numpy's random.choices will not perform this task without replacement, and random.sample won't take a weighted input.
当前,这是我正在使用的:
Currently, this is what I am using:
P = np.zeros((1,Parent_number))
n=0
while n < Parent_number:
draw = random.choices(population,weights=W,k=1)
if draw not in P:
P[0,n] = draw[0]
n=n+1
P=np.asarray(sorted(P[0]))
虽然可行,但需要从数组来回切换到列表再回到数组,因此不理想.
While this works, it reqires switching back and forth from arrays, to lists and back to arrays and is, therefore, less than ideal.
我正在寻找最简单易懂的解决方案,因为此代码将与他人共享.
I am looking for the simplest and easiest to understand solution as this code will be shared with others.
推荐答案
您可以将np.random.choice
与replace=False
结合使用,如下所示:
You can use np.random.choice
with replace=False
as follows:
np.random.choice(vec,size,replace=False, p=P)
其中vec
是人口,P
是权重向量.
where vec
is your population and P
is the weight vector.
例如:
import numpy as np
vec=[1,2,3]
P=[0.5,0.2,0.3]
np.random.choice(vec,size=2,replace=False, p=P)
这篇关于加权随机样本,无需在python中进行替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!