polynomialRegression function

PolynomialRegressionResult polynomialRegression(
  1. List<double> x,
  2. List<double> y, {
  3. required int degree,
})

Computes polynomial regression for the given data points.

degree is the degree of the polynomial to fit.

Implementation

PolynomialRegressionResult polynomialRegression(
  List<double> x,
  List<double> y, {
  required int degree,
}) {
  if (x.length != y.length) {
    throw ArgumentError('x and y must have the same length');
  }
  if (x.length <= degree) {
    throw ArgumentError('Need more points than the polynomial degree');
  }

  final n = x.length;
  final m = degree + 1;

  // Build the Vandermonde matrix
  final matrix = List.generate(n, (i) {
    return List.generate(m, (j) => math.pow(x[i], j).toDouble());
  });

  // Solve using normal equations: (X^T X) * coeffs = X^T * y
  // Compute X^T X
  final xtx = List.generate(m, (i) {
    return List.generate(m, (j) {
      double sum = 0;
      for (int k = 0; k < n; k++) {
        sum += matrix[k][i] * matrix[k][j];
      }
      return sum;
    });
  });

  // Compute X^T y
  final xty = List.generate(m, (i) {
    double sum = 0;
    for (int k = 0; k < n; k++) {
      sum += matrix[k][i] * y[k];
    }
    return sum;
  });

  // Solve the system using Gaussian elimination
  final coefficients = _solveLinearSystem(xtx, xty);

  // Calculate R-squared
  double sumY = 0;
  for (final yi in y) {
    sumY += yi;
  }
  final meanY = sumY / n;

  double ssTot = 0;
  double ssRes = 0;

  for (int i = 0; i < n; i++) {
    double predicted = 0;
    double xPower = 1;
    for (final coef in coefficients) {
      predicted += coef * xPower;
      xPower *= x[i];
    }
    ssTot += (y[i] - meanY) * (y[i] - meanY);
    ssRes += (y[i] - predicted) * (y[i] - predicted);
  }

  final rSquared = ssTot > 0 ? 1 - (ssRes / ssTot) : 0.0;

  return PolynomialRegressionResult(
    coefficients: coefficients,
    rSquared: rSquared,
  );
}