java实现加权抽样_用Java替换加权采样

Java或类似Apache MATLAB Commons function randsample的库(例如Apache Commons Math)中是否存在函数?

更具体地说,我想找到一个函数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表示替换后的采样.

如果不存在这样的功能,该怎么写?

注意:我知道在堆栈溢出中已询问similar question,但不幸的是它尚未得到回答.

解决方法:

我敢肯定一个人不存在,但是创建一个可以产生这样的样本的函数很容易.首先,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

cdf[i] = cdf[i-1] + pdf[i];

}

然后,您可以构建适当大小的整数数组来存储结果并开始查找随机结果:

int[] results = new int[numsamples];

for(int i=0; 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!");

}

}

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

标签:random-sample,random,matlab,java

来源: https://codeday.me/bug/20191122/2058706.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值