【问题标题】:Solve least squares regression in java在java中解决最小二乘回归
【发布时间】:2016-12-04 11:04:55
【问题描述】:

我正在用 Java 实现 pandas DataFrame 克隆,我需要的功能之一是重采样。我找到了一个很好的方法来做到这一点here。在引用的链接中,他们使用 python,特别是来自 numpy 的 lstsq 函数,它采用矩阵 A 和向量 b,与我需要实现的公式完全相同。

现在我转到Apache Commons math website on Least squares,API 似乎与Least_squares(A, b) 完全不同,而且非常复杂。

我想知道如何仅通过传递矩阵A 和向量b 来解决java 中的最小二乘非线性回归问题,就像在python 中一样。

【问题讨论】:

    标签: java apache-commons-math


    【解决方案1】:

    Apache Commons 中的 Least Squares 包使用 Gauss-NewtonLevenberg-Marquardt 等数值最小化算法进行非线性曲线拟合(非线性最小二乘法)。

    numpy.linalg.lstsq 另一方面用于线拟合(线性最小二乘法)。 lstsq 在 Apache commons 中的等价物是 SimpleRegression

    在这两种情况下,您都会遇到线拟合问题y = mx + c,其中xy 是已知的等长向量,包含数据点(多对 x.y 标量值)。使用lstsq,您必须将问题转换为y = Ap,其中A = [[x 1]]p = [[m], [c]]。对于SimpleRegression,一种选择是将xy 连接到double[][] 矩阵中,每行2 列和1 个数据点。

    这是lstsq docs 中提到的为SimpleRegression 编写的相同示例:

    import org.apache.commons.math3.stat.regression.SimpleRegression;
    
    public class StackOverflow {
        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[][]{
                    {0, -1},
                    {1, 0.2},
                    {2, 0.9},
                    {3, 2.1}
            });
    
            // querying for model parameters
            System.out.println("slope = " + simpleRegression.getSlope());
            System.out.println("intercept = " + simpleRegression.getIntercept());
        }
    }
    

    当然你会得到同样的结果

    坡度 = 1.0
    截距 = -0.95

    【讨论】:

      猜你喜欢
      • 2015-05-15
      • 2015-10-31
      • 1970-01-01
      • 2017-03-25
      • 1970-01-01
      • 1970-01-01
      • 2015-09-16
      • 1970-01-01
      • 2013-10-11
      相关资源
      最近更新 更多