PolyFit constructor

PolyFit(
  1. Array x,
  2. Array y,
  3. int degree
)

Performs a polynomial reggression on the data points (y[i], x[i]). x the values of the predictor variable y the corresponding values of the response variable degree the degree of the polynomial to fit

Implementation

PolyFit(Array x, Array y, int degree) {
  this.degree = degree;

  // check arguments.
  if (this.degree < 0) {
    throw FormatException('expected deg >= 0');
  }
  if (x.isEmpty) {
    throw FormatException('expected non-empty vector for x');
  }
  if (x.length != y.length) {
    throw FormatException('expected x and y to have same length');
  }

  var n = x.length;
  var order = this.degree + 1;
  QR qr;
  Array2d matrixX;

  // in case Vandermonde matrix does not have full rank, reduce degree until it does
  while (true) {
    // build Vandermonde matrix
    matrixX = matrixVander(x, N: order, increasing: true);

    // find least squares solution
    qr = QR(matrixX);
    if (qr.isFullRank()) break;

    // decrease degree and try again
    this.degree--;

    if (this.degree < 0) {
      throw FormatException('Matrix is rank deficient.');
    }
  }

  // create matrix from vector
  var matrixY = Array2d.fromVector(y, n);

  // linear regression coefficients
  beta = qr.solve(matrixY);

  // mean of y[] values
  var meany = mean(y);

  // total variation to be accounted for
  for (var i = 0; i < n; i++) {
    var dev = y[i] - meany;
    sst += dev * dev;
  }

  // variation not accounted for
  var residuals = matrixDot(matrixX, beta) - matrixY;
  sse = matrixNormTwo(residuals) * matrixNormTwo(residuals);
}