在java中使用通用数学库

时间:2015-06-16 04:49:20

标签: java linear-regression

我是java的新手,现在我想将普通线性回归应用于两个系列,比如说[1,2,3,4,5]和[2,3,4,5] ,6]。

我了解到有一个名为common math的库。但是,文档难以理解,是否有任何示例在java中进行简单的普通线性回归?

1 个答案:

答案 0 :(得分:6)

使用math3 library,您可以按照以下方式执行操作。示例基于SimpleRegression类:

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

    }

}