I'm trying to use Commons Math to fit polynomial curves to a dataset. I have:
- created a PolynomialCurveFitter,
- got the coefficients,
- created a polynomial function with those coefficients, and
- created an array of values generated by the function.
more or less manually creating the predictions.
My question is, how can I get the residuals between the fitted values and the original observations?
I see in the commons.math code that the PolynomialCurveFitter creates a LeastSquaresProblem, the leastSquaresProblem can return an Evaluation, and the evaluation has a method to return the residuals.
However, the getProblem() method in PolynomialCurveFitter is protected so I can't use it.
Is there a way get an appropriate LeastSquaresProblem from a CurveFitter so I can get residuals?
Or should I extend the Fitter to make getProblem() accessible?
Or is there another way entirely?
Here is my code so far:
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;
}