# [Math] Calculate R-Square for PolynomialCurveFitter

3 messages
Open this post in threaded view
|

## [Math] Calculate R-Square for PolynomialCurveFitter

 Cross-posting from stackoverflow . OLSMultipleLinearRegression, SimpleRegression provide a method that returns calculateRSquared(), getRSquare(). But I am not able to find any such method for PolynomialCurveFitter ? Right now I am doing it myself like below :- Is there any such method in common-math which does this? private PolynomialFunction getPolynomialFitter(List> pointlist) {     final PolynomialCurveFitter fitter = PolynomialCurveFitter.create(2);     final WeightedObservedPoints obs = new WeightedObservedPoints();     for (List point : pointlist) {         obs.add(point.get(0), point.get(1));     }     double[] fit = fitter.fit(obs.toList());     System.out.printf("\nCoefficient %f, %f, %f", fit[0], fit[1], fit[2]);     final PolynomialFunction fitted = new PolynomialFunction(fit);     return fitted; } private double getRSquare(PolynomialFunction fitter, List> pointList) {     final double[] coefficients = fitter.getCoefficients();     double[] predictedValues = new double[pointList.size()];     double residualSumOfSquares = 0;     final DescriptiveStatistics descriptiveStatistics = new DescriptiveStatistics();     for (int i=0; i< pointList.size(); i++) {         predictedValues[i] = predict(coefficients, pointList.get(i).get(0));         double actualVal = pointList.get(i).get(1);         double t = Math.pow((predictedValues[i] - actualVal), 2);         residualSumOfSquares  += t;         descriptiveStatistics.addValue(actualVal);     }     final double avgActualValues = descriptiveStatistics.getMean();     double totalSumOfSquares = 0;     for (int i=0; i