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?
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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With