以下,是我在写一个算法时中的一小部分,程序给了一个简单的算例。
计算残差平方和的均值。
以下是残差平方和公式。
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;
}
}