用java实现matlab的随机函数randsrc(m,n,[alphabet; prob])
在機器學習中,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(m,n,[alphabet; prob])的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: error TS1323: Dynami
- 下一篇: 波数与波长 matlab,Matlab求