Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use common math library in java

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?

like image 424
epx Avatar asked Aug 22 '26 21:08

epx


1 Answers

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));

    }

}
like image 135
Dims Avatar answered Aug 25 '26 10:08

Dims



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!