用Apache Math3实现多元线性回归

1.引用

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-math3</artifactId>
            <version>3.6.1</version>
        </dependency>

2.示例

    public static void main(String[] args) {

        String[] arr = {"", "a", "b", "c"};

        OLSMultipleLinearRegression regression = new OLSMultipleLinearRegression();

        /**
         * y=β0+β1*a+β2*b+β3*c  目标表达式,β为常数,就是这次计算的结果
         */

        double[] y = new double[]{27, 29, 23, 20, 21};//y

        double[][] x = new double[5][3];
        x[0] = new double[]{4, 0, 1};//a b c
        x[1] = new double[]{7, 1, 1};
        x[2] = new double[]{6, 1, 0};
        x[3] = new double[]{2, 0, 0};
        x[4] = new double[]{3, 0, 1};

        //计算
        regression.newSampleData(y, x);

        //查看结果
        double[] doubles = regression.estimateRegressionParameters();
        for (double aDouble : doubles) {
            System.out.println(aDouble);
        }

        String fun = "y = ";
        for (int i = 0; i < doubles.length; i++) {
            double d = new BigDecimal(doubles[i]).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            String s = arr[i];
            if (!s.isEmpty()) {
                fun += d < 0 ? d + "*" + s : "+" + d + "*" + s;
            } else {
                fun += d < 0 ? d : "-" + d;
            }
        }
        System.out.println(fun);
    }

3.结果打印

9.250000000000004
4.749999999999996
-13.499999999999979
-1.2499999999999944
y = -9.25+4.75*a-13.5*b-1.25*c

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值