java回归中的残差平方和的均值

以下,是我在写一个算法时中的一小部分,程序给了一个简单的算例。

计算残差平方和的均值
以下是残差平方和公式。
这里写图片描述

package sampling.method;

import java.util.HashMap;
import java.util.Map;
import org.apache.commons.math3.linear.Array2DRowRealMatrix;
import org.apache.commons.math3.linear.RealMatrix;
public class Test {

    public static void main(String[] args) {
        Map<Integer,RealMatrix > ymatrix=new HashMap<Integer,RealMatrix >();
        double[][] y1={{1,2,3,4}};
        RealMatrix y1matrix = new Array2DRowRealMatrix(y1);
        double[][] y2={{2,3,3,5,7}};
        RealMatrix y2matrix = new Array2DRowRealMatrix(y2);
        //这里的1和2分别表示类别
        ymatrix.put(1, y1matrix);
        ymatrix.put(2, y2matrix);
        //
        Map<Integer,RealMatrix > xMatrixList=new  HashMap<Integer,RealMatrix >();
        double[][] x1={{1,2},{3,4},{2,4},{2,4}};
        double[][] x2={{1,2},{3,4},{0,0},{5,4},{2,6}};
        RealMatrix x1mat = new Array2DRowRealMatrix(x1);
        RealMatrix x2mat = new Array2DRowRealMatrix(x2);
        xMatrixList.put(1, x1mat);
        xMatrixList.put(2, x2mat);
        //
        Map<Integer,RealMatrix > wMatrixList=new  HashMap<Integer,RealMatrix >();
        double[][] w1={{1,2}};
        double[][] w2={{2,3}};
        RealMatrix w1mat = new Array2DRowRealMatrix(w1);
        RealMatrix w2mat = new Array2DRowRealMatrix(w2);
        wMatrixList.put(1, w1mat);
        wMatrixList.put(2, w2mat);
        double sum=0.0;
        int dimension=0;
        for( int itemnumber : ymatrix.keySet() ){
            RealMatrix yscore=ymatrix.get(itemnumber) ;
            dimension+=yscore.getColumnDimension();
            RealMatrix wxscore=wMatrixList.get(itemnumber).multiply(xMatrixList.get(itemnumber).transpose()) ;
            RealMatrix ysbuwxscore =yscore.add(wxscore.scalarMultiply(-1.0));
            System.out.println(yscore.add(wxscore.scalarMultiply(-1.0)));
            System.out.println(ysbuwxscore.multiply(ysbuwxscore.transpose()));
            sum+=sumarray(ysbuwxscore.multiply(ysbuwxscore.transpose()));

        }
        System.out.println("残差平方和均值为:"+sum/dimension);
    }
    private static double sumarray(RealMatrix a){
        double[][] arr=a.getData();
        double sum = 0.0; 
        for (int i = 0; i < arr.length; i++) {  
            for (int j = 0; j < arr[i].length; j++) {  
                sum += arr[i][j];  
            }  
        } 
        return sum;
    }
}

这里写图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值