判定系数
coefficient of determination 为估计的回归方程提供拟合优度的度量。
代码
1、demo
package com.math.demo;
import com.math.regression.RegressionEquation;
import com.math.regression.RegressionModel;
/***
*
* @author miaoyibo
*
*/
public class RegressionDemo {
public static void main(String[] args) {
double[] dependentValues= {58,105,88,118,117,137,157,169,149,202};
double[] independentValues= {2,6,8,8,12,16,20,20,22,26};
RegressionEquation re=new RegressionEquation(dependentValues, independentValues);
RegressionModel regressionModel = re.getRegressionModel();
System.out.println("b0=="+regressionModel.getB0());
System.out.println("b0=="+regressionModel.getB1());
System.out.println("coefficient of determination=="+regressionModel.getR());
}
}
2、model
package com.math.regression;
public class RegressionModel {
//y轴截距
private double b0;
//斜率
private double b1;
//判定系数
private double r;
public double getB0() {
return b0;
}
public void setB0(double b0) {
this.b0 = b0;
}
public double getB1() {
return b1;
}
public void setB1(double b1) {
this.b1 = b1;
}
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
}
3、方法类
package com.math.regression;
import org.apache.commons.math3.stat.descriptive.moment.Mean;
/***
* least squares method
* @author miaoyibo
*
*/
public class RegressionEquation {
private double[] dependentValues;
private double[] independentValues;
public RegressionEquation(double[] dependentValues, double[] independentValues) {
this.dependentValues = dependentValues;
this.independentValues = independentValues;
}
public double getMean(double[] dd) {
Mean meanUtil = new Mean();
return meanUtil.evaluate(dd);
}
public double[] calRegression() {
if(dependentValues.length!=independentValues.length) {
return null;
}
Mean meanUtil = new Mean();
double xmean=meanUtil.evaluate(independentValues);
double ymean=meanUtil.evaluate(dependentValues);
double numerator=0d;
double denominator=0d;
for(int i=0;i<dependentValues.length;i++) {
double x=independentValues[i];
double y=dependentValues[i];
numerator=numerator+(x-xmean)*(y-ymean);
denominator=denominator+(x-xmean)*(x-xmean);
}
double b1=numerator/denominator;
double b0=ymean-b1*xmean;
double[] model= {b0,b1};
return model;
}
//判定系数
public double getCoefficientOfDetermination() {
double[] model = calRegression();
double b0=model[0];
double b1=model[1];
//calculate SSE SST
double sse=0;
double sst=0;
Mean meanUtil = new Mean();
double mean=meanUtil.evaluate(dependentValues);
for(int i=0;i<dependentValues.length;i++) {
double yi=independentValues[i]*b1+b0;
double y=dependentValues[i];
sse=sse+(y-yi)*(y-yi);
sst=sst+(y-mean)*(y-mean);
}
return (sst-sse)/sst;
}
public RegressionModel getRegressionModel() {
RegressionModel model=new RegressionModel();
double[] regression = calRegression();
double coefficientOfDetermination = getCoefficientOfDetermination();
model.setB0(regression[0]);
model.setB0(regression[1]);
model.setR(coefficientOfDetermination);
return model;
}
}