Apache Commons 中的 Least Squares 包使用 Gauss-Newton 和 Levenberg-Marquardt 等数值最小化算法进行非线性曲线拟合(非线性最小二乘法)。
numpy.linalg.lstsq 另一方面用于线拟合(线性最小二乘法)。 lstsq 在 Apache commons 中的等价物是 SimpleRegression。
在这两种情况下,您都会遇到线拟合问题y = mx + c,其中x 和y 是已知的等长向量,包含数据点(多对 x.y 标量值)。使用lstsq,您必须将问题转换为y = Ap,其中A = [[x 1]] 和p = [[m], [c]]。对于SimpleRegression,一种选择是将x 和y 连接到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