在机器学习中,matlab作为一个比较强大的工具,它的语言对矩阵运算支持比较完善。
而生成随机数的randsrc(m,n,[alphabet; prob])方法可以对矩阵生成指定选择集合并且指定集合元素概率的随机数矩阵。
而我在使用java实现一些机器学习算法的时候需要生成类似随机数矩阵没有matlab提供的方法,只能自己实现了。
我们看看randsrc(m,n,[alphabet; prob])的定义如下:
out = randsrc(m,n,[alphabet; prob]) generates an m-by-n matrix, each of whose entries is independently chosen from the entries in the row vector alphabet. Duplicate values in alphabetare ignored. The row vector prob lists corresponding probabilities, so that the symbol alphabet(k) occurs with probability prob(k), where k is any integer between one and the number of columns of alphabet. The elements of prob must add up to 1.
这个函数返回的是一个m*n的矩阵,其中,每个元素是从alphabet数组里面选取,最后元素alphabet[i]出现在矩阵中的概率符合概率prob[i]。
我们用java实现如下:
private static DenseMatrix64F randsrc(int m,int n,double[] alphabet,double[] prob) {
DenseMatrix64F rs = new DenseMatrix64F(m,n);
List<Double> items = new LinkedList<Double>();
Random r=new Random();
int allnum = m * n;
int rest = allnum;
for(int i=0;i<alphabet.length;i++) {
if(i != alphabet.length-1) {
int alpNum = (int)(allnum*prob[i]);
rest -= alpNum;
for(int j=0;j<alpNum;j++)
items.add(alphabet[i]);
}else {
for(int j=0;j<rest;j++)
items.add(alphabet[i]);
}
}
for(int i=0;i<m;i++) {
for(int j=0;j<n;j++) {
rs.set(i, j, items.remove(r.nextInt(items.size())));
}
}
return rs;
}
我们测试如下:
double[] a1= new double[]{1,2,3};
double[] a2= new double[]{0.6,0.3,0.1};
DenseMatrix64F test = randsrc(5,2,a1,a2);
System.out.println(test);
结果如下:

符合指定概率分布

本文介绍如何在Java中实现Matlab的randsrc函数,该函数用于生成指定概率分布的随机数矩阵。文章详细解释了函数的工作原理,并提供了一个具体的Java实现示例。
7902

被折叠的 条评论
为什么被折叠?



