Using the Least Squares Method with Commons Math and Setting

I tried to use commons math to calculate constants in a polynomial. There seems to be a normal procedure, but I got this error. Does anyone see a problem?

I tried to convert this question to commons-math: https://math.stackexchange.com/questions/121212/how-to-find-curve-equation-from-data

From building your data (Wolfram | Alpha link) it does not look linear. Therefore, a polynomial is better. I assume you want to put data:

XY 1 4 2 8 3 13 4 18 5 24 .. using the quadratic polynomial y = ax2 + bx + c.

And tungsten alpha has provided great utility. I would like to receive the same answers as from tungsten.

http://www.wolframalpha.com/input/?i=fit+4%2C+8%2C+13%2C

eg. Entering this data, I would get: 4.5 x-0.666667 (linear)

Here is the code and the error:

import org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression;
import org.apache.commons.math3.stat.regression.SimpleRegression;
final OLSMultipleLinearRegression regression2 = new OLSMultipleLinearRegression();
double[] y = {
        4.0, 
        8, 
        13,                 
};      
double[][] x2 = 
    {
        { 1.0, 1, 1  },
        { 1.0, 2, 4  },
        { 0.0, 3, 9  },             
    };
regression2.newSampleData(y, x2);
regression2.setNoIntercept(true);
regression2.newSampleData(y, x2);       
double[] beta = regression2.estimateRegressionParameters();
for (double d : beta) {
    System.out.println("D: " + d);
}

An exception in the main flow org.apache.commons.math3.exception.MathIllegalArgumentException: not enough data (3 rows) for this set of predictors (3 predictors) at org.apache.commons.math3.stat.regression.AbstractMultipleLinearRegression.validateSampleData (AbstractMultipleLinearararlearararLine .java: 236) at org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression.newSampleData (OLSMultipleLinearRegression.java:70) at org.berlin.bot.algo.BruteForceSort.main (BruteForceSort.java:108)

+5
source share
2 answers
Ryuk was right. I provided an extra line (test case) and created the same answer as tungsten / alpha.

D: 0,24999999999999822 D: 3.4500000000000033 D: 0,24999999999999914

0.25x ^ 2 + 3.45x + 0.25

final OLSMultipleLinearRegression regression2 = new OLSMultipleLinearRegression();
        double[] y = {
                4, 
                8, 
                13,         
                18
        };              
        double[][] x2 = 
            {
                { 1, 1, 1  },
                { 1, 2, 4  },
                { 1, 3, 9  },                                                               
                { 1, 4, 16  },
            };

        regression2.newSampleData(y, x2);
        regression2.setNoIntercept(true);
        regression2.newSampleData(y, x2);       
        double[] beta = regression2.estimateRegressionParameters();
        for (double d : beta) {
            System.out.println("D: " + d);
        }
0

All Articles