use common math library in java

11.3k views Asked by At

I am newbie to java and now I want to apply the ordinary linear regression to two series, say [1, 2, 3, 4, 5] and [2, 3, 4, 5, 6].

I learn that there is a library called common math. However, the documentation is difficult to understand, is there any example to do simple ordinary linear regression in java?

1

There are 1 answers

3
Dims On BEST ANSWER

With math3 library you can do the way below. Sample is based on SimpleRegression class:

import org.apache.commons.math3.stat.regression.SimpleRegression;

public class Try_Regression {

    public static void main(String[] args) {

        // creating regression object, passing true to have intercept term
        SimpleRegression simpleRegression = new SimpleRegression(true);

        // passing data to the model
        // model will be fitted automatically by the class 
        simpleRegression.addData(new double[][] {
                {1, 2},
                {2, 3},
                {3, 4},
                {4, 5},
                {5, 6}
        });

        // querying for model parameters
        System.out.println("slope = " + simpleRegression.getSlope());
        System.out.println("intercept = " + simpleRegression.getIntercept());

        // trying to run model for unknown data
        System.out.println("prediction for 1.5 = " + simpleRegression.predict(1.5));

    }

}