Lecture 2

Polynomial regression and regularisation

Introduction to Machine Learning
KU Leuven, campuses Diepenbeek and Geel
Academic year 2026–2027

Where we left off

A model scored

  • \(R^2 = 0.95\) on its training data
  • \(R^2 = 0.40\) on its test data

Today

Why this happens, how to measure it honestly, and what to do about it.

Today in three choices

Model

\(\yhat = \vw\T\phi(\vx)\)

linear in the weights, curved in the input

Loss

\(\frac{1}{n}\lVert \vy - \mPhi\vw \rVert^2 + \lambda \lVert \vw \rVert^2\)

the squared error, plus a penalty

Optimiser

normal equations or gradient descent

unchanged from lecture 1

The plan

  1. More flexible models, and how they fail
  2. Measuring honestly: validation
  3. Regularisation, and choosing its strength

Exercise 1 follows this lecture and uses all three.

Block 1

More flexible models

A line cannot saturate

The turbine produces no power below the cut-in speed, then rises, then holds at its rated power.

A straight line cannot do all three.

Fifty turbine measurements with the best straight line, which is above the data at low wind speeds and below the rated power at high wind speeds.

Curved in the input, straight in the weights

\[ \yhat = w_0 + w_1 x + w_2 x^2 + \dots + w_p x^p \]

The model is nonlinear in \(x\), while it stays linear in \(\vw\).

Therefore everything from lecture 1 still applies.

Only the design matrix changes

\[ \mPhi = \begin{bmatrix} 1 & x^{(1)} & \dots & (x^{(1)})^p \\ \vdots & \vdots & & \vdots \\ 1 & x^{(n)} & \dots & (x^{(n)})^p \end{bmatrix} \]
\[ \vw^\ast = \left( \mPhi\T\mPhi \right)^{-1} \mPhi\T\vy \]

With \(\mPhi\) in place of \(\mX\), these are the normal equations of lecture 1.

Any fixed functions will do

  • Powers: \(1, x, x^2, \dots\)
  • Sines and cosines, for something periodic
  • Bumps placed along the range

The functions are chosen in advance. Lecture 5 lets the model learn them instead.

Scale before taking powers

At 20 m/s, \(v^{12}\) is about \(4 \cdot 10^{15}\).

Map 0 to 20 m/s onto \([-1, 1]\) first, i.e. \(x = v/10 - 1\).

Otherwise the columns of \(\mPhi\) differ by fifteen orders of magnitude, and the solution of the normal equations loses its accuracy.

Three degrees on the same fifty points

  • Degree 1: misses the shape
  • Degree 5: follows the curve
  • Degree 12: follows the points
Turbine measurements with polynomials of degree 1, 5 and 12; the degree 12 curve swings far outside the data range.

Both errors, against the degree

Training error falling steadily with the degree, while the test error falls to a minimum at degree 5 and then rises steeply.
The training error never rises. The test error has a minimum, here at degree 5.

Two ways to be wrong

Underfitting

The model is too rigid for the pattern.

Both errors are large.

Overfitting

The model follows the noise of its training data.

The training error is small and the test error is large.

The same model, twenty different samples

Three panels, each with twenty fitted curves: degree 1 curves lie on top of each other away from the truth, degree 5 curves hug the true curve, degree 12 curves agree in the middle and fly apart near the edges.
Each curve is the same method, trained on twenty measurements from the same source.

Bias and variance

Bias

Wrong in the same way every time.

The rigid model, left panel.

Variance

A different answer for every sample.

The flexible model, right panel.

Checkpoint

Which of the three models would more measurements help, and which would they not?

Block 2

Measuring honestly

Back to the workflow

The machine learning workflow from task and data through feature engineering, model learning, validation and test to a trained model.
Today: model validation, the box lecture 1 passed over.

The test set cannot choose the degree

  • Fitting twelve models and reporting the best test error is a choice made on the test data
  • That error is then optimistic: the test set has become part of the training
  • It is spent, and there is no honest number left to report

A third part of the data is needed.

Three parts, three jobs

The measurements split into a training part of sixty per cent, a validation part of twenty per cent and a test part of twenty per cent, with the role of each part underneath.

One split is a noisy measurement

  • With fifty measurements, a validation part holds about ten
  • Ten points give a noisy estimate
  • A different split gives a different winner

Use every point for validation, in turn.

k-fold cross-validation

Five rows; in each row a different one of the five parts is the validation part and the other four are training, with one error per row and their average at the bottom.
Every point is used for validation exactly once. The score is the average.

Cross-validation

Pseudocode

input: data, model, k
split data into k parts
for i in 1..k:
    train on all parts except i
    e[i] ← error on part i
return average of e

scikit-learn

from sklearn.model_selection import (
    KFold, cross_val_score)

folds = KFold(n_splits=5, shuffle=True,
              random_state=0)
scores = cross_val_score(
    model, X, y, cv=folds,
    scoring="neg_mean_squared_error")
error = -scores.mean()

Choosing the degree without the test data

Cross-validated training and validation error against the polynomial degree; the validation error is lowest at a low degree and rises steeply for high degrees.
The degree with the lowest validation error is chosen, and only then is the test set opened.

Does more data help?

Validation error against the number of training samples, on a logarithmic scale; the degree 1 curve is nearly flat while the degree 12 curve falls steeply and ends below it.
The answer to the checkpoint: more data cures variance, and it does not cure bias.

Putting features on a common scale

\[ z = \frac{x - \mu}{\sigma} \]

\(\mu\) and \(\sigma\) are computed on the training data only.

Every other part of the data is then transformed with those same two numbers.

Data leakage

Standardising all the data before splitting lets the validation part influence the training.

The reported error is then no longer an honest measurement.

Other common cases

  • The same measurement in both parts
  • A feature computed from the future

The pipeline keeps preprocessing inside the fold

A pipeline of polynomial features, standardisation and ridge, fitted on the training folds and applied unchanged to the validation fold.

One object, refitted on every fold

make_pipeline(
    PolynomialFeatures(degree),
    StandardScaler(),
    Ridge(alpha=a))

Passed to cross_val_score, every step is refitted on each training fold.

The scaler never sees the validation fold, so its mean and its standard deviation cannot leak into the score.

Checkpoint

A third of the turbine measurements were logged twice. A colleague runs five-fold cross-validation without removing the copies. Is the reported error optimistic, pessimistic or fair?

Break

Ten minutes

Block 3

Regularisation

Look at what the flexible model is made of

degree 5degree 12
largest weight50 3942 114 140
signsalternatingalternating
training MSE15 5848 842
test MSE11 893353 303

The wiggles are built from enormous weights that nearly cancel.

So penalise large weights.

Ridge regression

\[ \loss(\vw) = \frac{1}{n} \lVert \vy - \mPhi\vw \rVert^2 + \lambda \lVert \vw_{1:p} \rVert^2 \]

The first term wants to fit the data, while the second wants small weights.

\(\lambda\) sets the exchange rate between them.

The intercept is not penalised: shifting the target by a constant should not be a crime.

It still has a closed form

\[ \nabla \loss(\vw) = \frac{2}{n} \mPhi\T (\mPhi\vw - \vy) + 2 \lambda I_0 \vw \]
\[ \left( \mPhi\T\mPhi + n \lambda I_0 \right) \vw = \mPhi\T\vy \]

Adding \(n\lambda I_0\) makes the matrix invertible, whatever the features.

\(I_0\) is the identity with its first diagonal entry set to zero, so the intercept is left unpenalised.

This repairs the failure of lecture 1: correlated features no longer break the solution.

What the penalty does to the weights

The eight weights of a degree 8 model against the penalty on a logarithmic scale; all of them shrink towards zero as the penalty grows.
Every weight shrinks towards zero, and none of them reaches it.

What the penalty does to the model

The same degree 12 model under three penalties: a wiggly curve, a curve following the data, and a nearly flat line.
Too small: the wiggles remain. Too large: the model underfits. \(\lambda\) is a hyperparameter, so block 2 chooses it.

The same penalty, three scalings

These slides:

\[ \frac{1}{n}\lVert \vy - \mPhi\vw \rVert^2 + \lambda \lVert \vw \rVert^2 \]

the mean squared error, plus a penalty

Ridge(alpha=a) minimises

\[ \lVert \vy - \mPhi\vw \rVert^2 + \alpha \lVert \vw \rVert^2 \]

so \(\alpha = n\lambda\). Lasso divides the first term by \(2n\) instead.

Why the scale of the features matters

  • Wind speed in m/s, or the same speed in km/h
  • The second weight is 3.6 times smaller for the same model
  • One \(\lambda\) then penalises the two features differently

Standardise first, as in block 2. The penalty then treats every feature equally.

The lasso

\[ \loss(\vw) = \frac{1}{n} \lVert \vy - \mPhi\vw \rVert^2 + \lambda \lVert \vw \rVert_1 \]

The sum of absolute values, instead of the sum of squares.

This drives weights to exactly zero, so the lasso also selects features.

Why zero, and not merely small

Loss contours with a circular budget region on the left and a diamond one on the right; the best allowed point is away from the axes on the circle and exactly on a corner of the diamond.
A budget on the weights: a disc for ridge, a diamond for the lasso. The lowest allowed loss sits on a corner of the diamond, where one weight is zero.

Ridge or lasso

RidgeLasso
Penalty\(\lVert \vw \rVert^2\)\(\lVert \vw \rVert_1\)
Weightssmallsome exactly zero
Correlated featuresshares the weight between themkeeps one, drops the rest
Solutionclosed formiterative

Ridge when every feature plausibly matters, lasso when a short list is wanted.

Choosing the degree and the penalty together

The search

for each degree:
    for each penalty:
        score by cross-validation
keep the best pair
refit on all training data

scikit-learn

search = GridSearchCV(
    pipeline,
    {"polynomialfeatures__degree": degrees,
     "ridge__alpha": alphas},
    cv=folds,
    scoring="neg_mean_squared_error")
search.fit(X_train, y_train)

The whole recipe

  1. Split off the test data and leave them alone
  2. Build a pipeline of every preprocessing step and the model
  3. Search the hyperparameters by cross-validation on the training data
  4. Refit the best setting on all the training data
  5. Measure on the test data, once, and report that number

Every later lecture of this course uses these five steps.

Checkpoint

As \(\lambda\) grows without bound, what does a ridge model predict?

Takeaways

  1. A model linear in its weights can be curved in its inputs: only the design matrix changes.
  2. Flexibility is bought with variance, and rigidity is paid for with bias.
  3. Validation data choose the degree and the penalty. Test data are opened once.
  4. Preprocessing belongs inside the pipeline, so that it is refitted on every fold.
  5. A penalty on the weights buys back the flexible model, and its strength is tuned, never guessed.

Lecture 2 in three choices

Model

\(\yhat = \vw\T\phi(\vx)\)

linear in the weights, curved in the input

Loss

\(\frac{1}{n}\lVert \vy - \mPhi\vw \rVert^2 + \lambda \lVert \vw \rVert^2\)

the change from lecture 1: a penalty

Optimiser

normal equations or gradient descent

unchanged

Further reading

All three books are free to read online.

Next

Exercise 1, now

Regression on a wind turbine power curve: least squares, gradient descent, polynomial features and a ridge pipeline.

Bring a laptop and a Google account for Colab.

Lecture 3

Classification and logistic regression: what changes when the target is a class instead of a number.