首页 > 解决方案 > 如何使用 Apache Commons Math 从曲线中获取残差

问题描述

我正在尝试使用 Commons Math 将多项式曲线拟合到数据集。我有:

或多或少手动创建预测。

我的问题是,我怎样才能得到拟合值和原始观测值之间的残差?

我在 commons.math 代码中看到 PolynomialCurveFitter 创建了一个 LeastSquaresProblem,leastSquaresProblem 可以返回一个评估,并且评估有一个返回残差的方法。

但是,PolynomialCurveFitter 中的 getProblem() 方法是受保护的,所以我不能使用它。

有没有办法从 CurveFitter 获得适当的 LeastSquaresProblem 以便我可以获得残差?

或者我应该扩展 Fitter 以使 getProblem() 可访问?

还是完全有另一种方式?

到目前为止,这是我的代码:

public static double[] fitPolynomial(double[] xCol, double[] yCol, int degree) {

    Collection<WeightedObservedPoint> points = new ArrayList<>();

    for (int i = 0; i < xCol.length; i++) {
        points.add(new WeightedObservedPoint(1.0, xCol[i], yCol[i]));
    }

    PolynomialCurveFitter fitter = PolynomialCurveFitter.create(degree);

    double[] coeff = fitter.fit(points);

    PolynomialFunction function = new PolynomialFunction(coeff);

    double[] fitted = new double[xCol.length];

    for (int i = 0; i < xCol.length; i++) {
        fitted[i] = function.value(i);
    }

    return fitted;
}

标签: javaapache-commons-math

解决方案


推荐阅读