Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polynomial regression with Apache Maths (Java)

Could anybody help me make a polynomial regression (order 2) with the Apache Math library.

The following data should give this equation: 39.79 x^2 - 497.66 x + 997.45 (computed by Excel with r2 = 0.9998)

// coding style from http://commons.apache.org/proper/commons-math/userguide/fitting.html    

double[] y = { 540.0, 160.0, -140.0, -360.0, -480.0, -560.0, -540.0, -440.0, -260.0, 0.0, 340.0};              
        final WeightedObservedPoints obs = new WeightedObservedPoints();
        for (double figure:y){
            obs.add(1.0, figure);
        }
        final PolynomialCurveFitter fitter = PolynomialCurveFitter.create(2);
        final double[] coeff = fitter.fit(obs.toList());
        System.out.println("coef="+Arrays.toString(coeff));

Here are the regression coefficients provided by the previous code:

coef=[-53.73522460839947, -52.22329678670934, -52.22329678670934]

Obviously, there's something I'm missing...

Thanks for your kind help

Dom

like image 432
Dominique Avatar asked Mar 18 '23 00:03

Dominique


1 Answers

All your data points are at x = 1.

obs.add(1.0, figure);!!!!

instead of 1.0 there should be x value, if they are evenly spaced from zero than use for loop and ix instead of 1.0.

like image 84
Zielu Avatar answered Mar 19 '23 13:03

Zielu