TExcelTAD
Home › Classical ML Algorithms: Supervised & Unsupervised › Polynomial Regression and the Bias-Variance Trade-off

Polynomial Regression and the Bias-Variance Trade-off

Fuel consumption rises with speed, then falls, then rises again; crop yield grows with fertiliser and then drops when there is too much. A straight line cannot follow a curve. Polynomial regression keeps the machinery of linear regression and only changes the features: from one input xx it builds 1,x,x2,…,xp1, x, x^2, \dots, x^p and fits a linear model to those. The model is still linear in the weights, so the normal equation still applies. The Machine Learning course shows the idea with numpy.polyfit; here you meet its central problem: choosing the degree.

The model

y^=w0+w1x+w2x2+⋯+wpxp=w⊤ϕ(x),ϕ(x)=(1,x,…,xp)\hat{y} = w_0 + w_1 x + w_2 x^2 + \dots + w_p x^p = \mathbf{w}^\top \boldsymbol{\phi}(x), \qquad \boldsymbol{\phi}(x) = (1, x, \dots, x^p)

The rows ϕ(xi)\boldsymbol{\phi}(x_i) form a Vandermonde matrix VV, and w=arg⁡min⁡∥y−Vw∥2\mathbf{w} = \arg\min \lVert \mathbf{y} - V\mathbf{w} \rVert^2 is ordinary least squares on it. With several inputs, PolynomialFeatures also adds the products: for 3 inputs at degree 3 there are (3+33)=20\binom{3+3}{3} = 20 features, so the count explodes with the degree. Basis functions in general are covered in Basis Functions and Overfitting.

Too simple, too flexible

Twenty training points come from y=sin⁡2πxy = \sin 2\pi x plus noise (σ=0.25\sigma = 0.25), and 200 more from the same source serve as a validation set:

python · try it yourself
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression

rng = np.random.default_rng(1)
def make_data(n):
    x = rng.uniform(0, 1, n)
    return x, np.sin(2 * np.pi * x) + rng.normal(scale=0.25, size=n)
x_tr, y_tr = make_data(20)
x_va, y_va = make_data(200)

def fit_poly(x, y, degree):
    V = np.vander(x, degree + 1, increasing=True)     # columns 1, x, x^2, ..., x^degree
    return np.linalg.lstsq(V, y, rcond=None)[0]
def predict_poly(w, x):
    return np.vander(x, len(w), increasing=True) @ w

print("degree  train MSE  valid MSE")
for d in [0, 1, 3, 5, 9, 12]:
    w = fit_poly(x_tr, y_tr, d)
    tr = np.mean((predict_poly(w, x_tr) - y_tr) ** 2)
    va = np.mean((predict_poly(w, x_va) - y_va) ** 2)
    print(f"{d:6d}  {tr:9.4f}  {va:9.4f}")

w3 = fit_poly(x_tr, y_tr, 3)
sk = make_pipeline(PolynomialFeatures(3), LinearRegression()).fit(x_tr[:, None], y_tr)
print("degree 3, same predictions as sklearn:", np.allclose(predict_poly(w3, x_va), sk.predict(x_va[:, None])))
print("degree 3 coefficients:", w3.round(2))
degree  train MSE  valid MSE
     0     0.3499     0.6673
     1     0.1463     0.2923
     3     0.0593     0.0852
     5     0.0523     0.0984
     9     0.0426     0.2639
    12     0.0329    21.7835
degree 3, same predictions as sklearn: True
degree 3 coefficients: [  0.16   8.01 -25.5   17.59]

The training error falls with every extra degree, because a bigger model can always fit the same points at least as well. The validation error tells the real story: degrees 0 and 1 underfit (they cannot bend), degree 3 is best (0.0852, close to the noise variance 0.252=0.06250.25^2 = 0.0625), and from degree 9 on the curve overfits: it threads the 20 training points and swings wildly between them, so the validation error explodes to 21.8 at degree 12.

The trade-off

For a new point, the expected squared error of a model fitted on a random training set splits into three parts (Capacity, Overfitting and Generalization):

E[(y−f^(x))2]=(f(x)−E[f^(x)])2⏟bias2+E[(f^(x)−E[f^(x)])2]⏟variance+σ2⏟noise\mathbb{E}\big[(y - \hat{f}(x))^2\big] = \underbrace{\big(f(x) - \mathbb{E}[\hat{f}(x)]\big)^2}_{\text{bias}^2} + \underbrace{\mathbb{E}\big[(\hat{f}(x) - \mathbb{E}[\hat{f}(x)])^2\big]}_{\text{variance}} + \underbrace{\sigma^2}_{\text{noise}}

A low degree has high bias: even averaged over many training sets it misses the true curve. A high degree has high variance: it changes a lot from one training set to the next. The noise σ2\sigma^2 is a floor no model can go below. The lab draws the same experiment (15 points from the same sine, σ=0.25\sigma = 0.25, the exact least-squares fit). Press Play to sweep the degree and watch the U-shaped validation curve; then change the seed to see how much a degree-10 fit jumps between data sets, and raise the number of points to see overfitting start later.

−2−10120.00.20.40.60.81.0xy10−310−210−111002468101214polynomial degree dmean squared errorError vs model complexitybest d = 3off scale ↑trainingvalidationfittrue sin 2πxDegree 3: about right

Choosing the degree honestly

Picking the degree by looking at the validation set many times slowly fits the validation set too. The standard procedure is cross-validation inside the training data. Here the degree is a hyperparameter of a pipeline, and the features are standardised after expansion so that x10x^{10} and xx are on comparable scales:

python · try it yourself
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import GridSearchCV, KFold

rng = np.random.default_rng(1)
x = rng.uniform(0, 1, 60)
y = np.sin(2 * np.pi * x) + rng.normal(scale=0.25, size=60)

pipe = make_pipeline(PolynomialFeatures(), StandardScaler(), LinearRegression())
search = GridSearchCV(pipe, {"polynomialfeatures__degree": range(1, 11)},
                      cv=KFold(5, shuffle=True, random_state=0), scoring="neg_mean_squared_error")
search.fit(x[:, None], y)
for d, s in zip(range(1, 11), search.cv_results_["mean_test_score"]):
    print(f"degree {d:2d}  CV MSE {-s:.4f}")
print("best degree:", search.best_params_["polynomialfeatures__degree"])
print("features for 3 inputs at degree 3:", PolynomialFeatures(3).fit(np.zeros((1, 3))).n_output_features_)
degree  1  CV MSE 0.2537
degree  2  CV MSE 0.3214
degree  3  CV MSE 0.0440
degree  4  CV MSE 0.0516
degree  5  CV MSE 0.1281
degree  6  CV MSE 0.0762
degree  7  CV MSE 0.2970
degree  8  CV MSE 0.6368
degree  9  CV MSE 1.2214
degree 10  CV MSE 1.6276
best degree: 3
features for 3 inputs at degree 3: 20

Five-fold cross-validation on 60 points picks degree 3 again. scikit-learn scorers follow "higher is better", which is why the MSE comes back negated. The curve is not smooth (degree 2 is worse than degree 1, because a parabola fits one hump of the sine badly), a reminder that CV estimates are noisy.

Hyperparameters, strengths and weaknesses

The degree is the one hyperparameter; with several inputs, interaction_only=True keeps only products of distinct features. Polynomial features are cheap and keep a linear model's speed and closed form, and low degrees (2 or 3) capture gentle curvature and interactions. High degrees are unstable, the number of features grows combinatorially with the number of inputs, and polynomials extrapolate badly: outside the training range they shoot off to ±∞\pm\infty. Use them for smooth effects of a few inputs, always with scaling and usually with regularisation; for many inputs or sharp changes, trees and boosting do better.

Pitfalls

  • Unscaled powers. x10x^{10} for xx in the hundreds overflows and makes V⊤VV^\top V hopelessly ill-conditioned.
  • Extrapolation. A degree-5 fit on ages 20 to 60 can predict nonsense for age 80.
  • Choosing the degree on the test set. Then the test score is no longer an unbiased estimate.

Practice

  1. From the first output, which degree has the largest gap between training and validation error, and what does the gap measure?
Answer

Degree 12 (0.0329 versus 21.78). The gap is a rough measure of overfitting: how much better the model does on the points it was fitted to than on new points, which is driven mostly by variance.

  1. How many features does PolynomialFeatures(2) create for 10 inputs, including the constant?
Answer

(10+22)=66\binom{10+2}{2} = 66: the constant, 10 linear terms, 10 squares and 45 products of pairs. Without the constant (include_bias=False) it is 65, the number used in the next lesson.

Test yourself

Why can polynomial regression be solved with the normal equation?

  1. Because polynomials are convex
  2. Because the model is linear in the weights; only the features are nonlinear in xx
  3. Because the degree is small
  4. It cannot; it needs gradient descent

Training error keeps falling as the degree rises while validation error rises. The model is…

  1. underfitting
  2. overfitting
  3. well calibrated
  4. biased

Which part of the expected error can no model remove?

  1. bias squared
  2. variance
  3. the noise variance σ2\sigma^2
  4. the training error