Fit a polynomial curve by expanding x into powers

A straight line cannot follow a curved trend. The classic trick is to keep linear regression but feed it the powers of x as extra features. The model is still linear in its weights, so ordinary least squares still works.

Write poly_fit(x, y, degree). x and y are 1D arrays of length n. Build the design matrix with columns [1, x, x^2, ..., x^degree] (lowest power first), solve the least squares problem, and return the coefficient array of length degree + 1, constant term first.

degree = 0 means fitting only a constant, which gives the mean of y.

Signaturedef poly_fit(x, y, degree)

Example

x = [0, 1, 2, 3], y = [1, 3, 7, 13] (that is 1 + x + x^2) with degree 2 gives [1.0, 1.0, 1.0].

Understand the idea

Polynomial regression fits a curve by giving ordinary linear regression extra features: x, x squared, x cubed and so on. The model is still linear in its weights, so least squares still solves it. Like describing a ball's flight with a starting height, a speed term and a gravity term. Build the design matrix with columns [1, x, x^2, ..., x^degree], lowest power first, so the returned coefficients start with the constant. Worked example: x = [0, 1, 2], y = [2, 3, 6], degree 2. The design matrix rows are [1, 0, 0], [1, 1, 1] and [1, 2, 4]. Try coefficients [2, 0, 1]: predictions 2, 2 + 0 + 1 = 3, 2 + 0 + 4 = 6, an exact fit. With degree 0 the only column is ones and the answer is the mean of y. np.vander puts the highest power first unless increasing=True, a common source of reversed coefficients. Rule: V[:, j] = x^j for j = 0..degree; coefficients = least squares solution of V c = y (np.linalg.lstsq). Curve fitting for trends and calibration uses this.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplepoly_fit([0, 1, 2, 3], [1, 3, 7, 13], 2)
  • Sample 2: noisy cubicpoly_fit(_x, _y, 3)
  • Test 3: degree 0 is the meanpoly_fit(_x, _y, 0)
  • Test 4: straight linepoly_fit([1, 2, 3], [2, 4, 6], 1)