Reputation: 83
I'm learning linear regression and using OLSMultipleLinearRegression in the apache commons mathematics library 3.5. I ran the following sample code that calculates regression parameters.
// estimate weights from heights and waist
OLSMultipleLinearRegression regression = new OLSMultipleLinearRegression();
// weight
double[] y = new double[] { 50, 60, 65, 65, 70, 75, 80, 85, 90, 95 };
// height, waist
double[][] x = new double[10][];
x[0] = new double[] { 165, 65 };
x[1] = new double[] { 170, 68 };
x[2] = new double[] { 172, 70 };
x[3] = new double[] { 175, 65 };
x[4] = new double[] { 170, 80 };
x[5] = new double[] { 172, 85 };
x[6] = new double[] { 183, 78 };
x[7] = new double[] { 187, 79 };
x[8] = new double[] { 180, 95 };
x[9] = new double[] { 185, 97 };
regression.newSampleData(y, x);
double[] coe = regression.estimateRegressionParameters();
for (double p : coe) {
System.out.println(p);
}
I want to calculate estimate values for each row in order to plot them. But as long as I read the document, the library doesn't provide method to do it. Of course, it is not difficult and can be realized as follows,
double[] z = new double[10];
for (int i = 0; i < z.length; i++) {
z[i] = coe[0];
for (int j = 1; j < coe.length; j++) z[i] += coe[j] * x[i][j - 1];
}
but is there some better ways? I found calculateResiduals and it seems close to my purpose, but it is a protected method.
Upvotes: 4
Views: 1342
Reputation: 83
I decided to create MyOLSMultipleLinearRegression class by inheriting the OLSMultipleLinearRegression class and implement the following function.
public double[] calculateEstimatedValues() {
RealVector b = calculateBeta();
return getX().operate(b).toArray();
}
Upvotes: 3