Weighted sampling without replacement

前端 未结 5 1935
没有蜡笔的小新
没有蜡笔的小新 2021-01-16 14:23

I have a population p of indices and corresponding weights in vector w. I want to get k samples from this population without repla

5条回答
  •  爱一瞬间的悲伤
    2021-01-16 15:15

    An alternative to the for loop approach of petrichor that performs well if the number of samples is much smaller than the number of elements is to compute a weighted random sample with replacement and then remove duplicates. Of course, this is a very bad idea if the number of samples k is near the number of elements n, as this will require many iterations, but by avoiding for loops, the wall clock performance is often better. Your mileage may vary.

    function I=randsample_noreplace(n,k,w)
    I = sort(randsample(n, k, true, w));
    while 1
        Idup = find( I(2:end)-I(1:end-1) ==0);
        if length(Idup) == 0
                break
        else
                I(Idup)=randsample(n, length(Idup), true, w);
                I = sort(I);
        end
    end
    

提交回复
热议问题