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.
def 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.