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 it builds 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
The rows form a Vandermonde matrix , and is ordinary least squares on it. With several inputs, PolynomialFeatures also adds the products: for 3 inputs at degree 3 there are 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 plus noise (), and 200 more from the same source serve as a validation set:
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 ), 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):
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 is a floor no model can go below. The lab draws the same experiment (15 points from the same sine, , 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.
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 and are on comparable scales:
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 . 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. for in the hundreds overflows and makes 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
- 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.
- How many features does
PolynomialFeatures(2)create for 10 inputs, including the constant?
Answer
: 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?
- Because polynomials are convex
- Because the model is linear in the weights; only the features are nonlinear in
- Because the degree is small
- It cannot; it needs gradient descent
Training error keeps falling as the degree rises while validation error rises. The model is…
- underfitting
- overfitting
- well calibrated
- biased
Which part of the expected error can no model remove?
- bias squared
- variance
- the noise variance
- the training error