【问题标题】:Weighted sampling with replacement in JavaJava中带替换的加权采样
【发布时间】:2013-12-31 22:02:03
【问题描述】:

在 Java 或 Apache Commons Math 等库中是否有与 MATLAB 函数 randsample 等效的函数? 更具体地说,我想找到一个函数randSample,它根据我指定的概率分布返回一个独立且相同分布的随机变量向量。 例如:

int[] a = randSample(new int[]{0, 1, 2}, 5, new double[]{0.2, 0.3, 0.5})
//        { 0 w.p. 0.2
// a[i] = { 1 w.p. 0.3
//        { 2 w.p. 0.5

输出与 MATLAB 代码 randsample([0 1 2], 5, true, [0.2 0.3 0.5]) 相同,其中 true 表示带替换采样。

如果没有这样的函数,我怎么写?

注意:我知道有人在 Stack Overflow 上询问过 similar question,但很遗憾没有得到答复。

【问题讨论】:

    标签: java matlab random random-sample


    【解决方案1】:

    我很确定它不存在,但是很容易制作一个会产生这样的样本的函数。首先,Java 确实带有一个随机数生成器,特别是一个带有 Random.nextDouble() 函数的随机数生成器,它可以生成 0.0 到 1.0 之间的随机双精度数。

    import java.util.Random;
    
    double someRandomDouble = Random.nextDouble();
         // This will be a uniformly distributed
         // random variable between 0.0 and 1.0.
    

    如果您有替换抽样,如果您将作为输入的 pdf 转换为 cdf,您可以使用 Java 提供的随机双精度数来创建随机数据集,通过查看它落在 cdf 的哪个部分。所以首先你需要将pdf转换成cdf。

    int [] randsample(int[] values, int numsamples, 
            boolean withReplacement, double [] pdf) {
    
        if(withReplacement) {
            double[] cdf = new double[pdf.length];
            cdf[0] = pdf[0];
            for(int i=1; i<pdf.length; i++) {
                cdf[i] = cdf[i-1] + pdf[i];
            }
    

    然后你制作适当大小的整数数组来存储结果并开始查找随机结果:

            int[] results = new int[numsamples];
            for(int i=0; i<numsamples; i++) {
                int currentPosition = 0;
    
                while(randomValue > cdf[currentPosition] && currentPosition < cdf.length) {
                    currentPosition++; //Check the next one.
                }
    
                if(currentPosition < cdf.length) { //It worked!
                    results[i] = values[currentPosition];
                } else { //It didn't work.. let's fail gracefully I guess.
                    results[i] = values[cdf.length-1]; 
                         // And assign it the last value.
                }
            }
    
            //Now we're done and can return the results!
            return results;
        } else { //Without replacement.
            throw new Exception("This is unimplemented!");
        }
    }
    

    有一些错误检查(确保 value 数组和 pdf 数组大小相同)和一些其他功能,您可以通过重载 this 来提供其他功能来实现,但希望这足以让您开始。干杯!

    【讨论】:

      猜你喜欢
      • 2012-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-28
      • 1970-01-01
      • 1970-01-01
      • 2021-08-20
      • 1970-01-01
      相关资源
      最近更新 更多