Search code examples
javaregressioncoefficientsolsmultiplelinearregression

Multiple linear Regression calculate coefficients Java


I am currently trying to perform an Multiple linear regression within my Java Project. I already tried many different classes like the OLSMultipleLinearRegression Class. But those classes don't return the parameters I need. For example these are the parameters which are possible to be calculated and those methods work fine.

calculateBeta()
calculateBetaVariance()
calculateHat()
calculateResidualSumOfSquares()
calculateRSquared()
calculateTotalSumOfSquares()

But I am trying to calculate the coefficients!

Here you can see my parameters and the expected results:
Here you can see my parameters and the expected results

Maybe someone has an idea how to perform an MLR that includes the calculation of the coefficients... Thanks guys!


Solution

  • You can just use calculateBeta() (which is protected, unfortunately)

    class Test {
        public static void main(String[] args)  {
            System.out.println(new TestData());
        }
    }
    

    so you have to use a trick...

    import org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression;
    
    public class TestData extends OLSMultipleLinearRegression {
        public TestData() {
            double[] y = {5.6, 5.44, 4.57, 4.78, 4.25, 5.31, 5.24, 5.12, 4.58, 5.18};
            double[][] x = {{3.17, 26.348}, {3.65, 24.198}, {3.28, 25.085}, {3.37, 22.461},
                    {2.57, 23.740}, {3.60, 24.786}, {3.50, 23.374}, {2.98, 23.725},
                    {2.54, 23.227}, {3.41, 26.920}};
            this.newSampleData(y,x);
        }
    
        @Override
        public String toString() {
            return this.calculateBeta().toString();
        }
    }