Part II · Chapter 10

Feature engineering & overfitting

How to make a straight-line model fit a curve without changing the model at all — and the exact price you pay for overdoing it.

Essentials

How a model that is only ever linear in its parameters fits curves — and the exact price of overdoing it.

Everything below is the explanation and the practice. If you are short on time, read this box, then go to the problems.

1. The premise: simple models, complex data

Key idea

If your dataset is complex — meaning the input values have complicated relationships with the output values — then simple models may be unable to fit it. Feature engineering is the tool that lets simple models fit complex distributions of data.

Note what it does not say: "use a more complex model." It says keep the simple model and change the data. That is the whole chapter.

The simple model, from chapter 8, for a one-dimensional input $x \in \R$:

$$ h(x) = wx + b $$

$w$ is the slope, $b$ the intercept or bias; you fit it by minimising squared error, in closed form via the normal equations. Interpretable, easy to optimise, two parameters. Now watch it fail.

1.1 When linear regression works

On a dataset $\D = \{(x^{(i)}, y^{(i)})\}_{i=1}^{N}$ that follows a linear trend, a linear model fits beautifully.

Common mistake

Notation, immediately. $x^{(i)}$ means the $i$-th sample: the parenthesised superscript is an index, not an exponent. $x^{(3)}$ is the third data point; $x^3$ is $x$ cubed. Check for parentheses before you do anything else — this chapter builds a table containing both at once.

Figure 1 (reconstructed) — a linear dataset with a linear model
Reconstruction note: the figures in the professor's PDF did not survive text extraction, so every plot on this page is rebuilt from scratch — real points, real least-squares fits computed in your browser. Here the residuals (the short vertical stubs) are small and have no pattern: some above the line, some below, no systematic drift. That is what "the model choice makes sense" looks like.

1.2 When linear regression fails

Now take non-linear data: the five samples of Table 1 (§3), which the notes use too, so every number on this page lines up. Sorted, $x = 0, 2, 3, 6, 7$ with $y = 15, 5, 1, 5, 12$ — falls, bottoms out, rises. A parabola.

Figure 2 (reconstructed) — a linear model fitted to non-linear data
The least-squares line is $h(x) = 8.66 - 0.295x$ — almost flat, slightly downward, and wrong everywhere. Mean squared error $= 25.66$. Notice the residuals now have a pattern: positive at both ends, negative in the middle. Patterned residuals are the diagnostic signature of a model that is too simple.

The line captures essentially nothing, and its slope is negative, so reading the coefficient as chapter 8 taught you — "$y$ decreases as $x$ increases" — gives the wrong conclusion about half the data.

Intuition

The linearity constraint is both what makes linear regression good and what makes it a poor model for non-linear data, so you would expect to trade one for the other. Feature engineering refuses the trade: keep the interpretability, the closed form and the simplicity, and still fit the curve.

2. The trick: linear in the parameters, not in the input

The data "strongly resembles a quadratic curve," as the notes put it. Suppose we could learn optimal parameters $[b, w_1, w_2]^\top$ for

$$ h(x) = b + w_1 x + w_2 x^2 $$

But how? We only know how to fit lines. The answer is the most important sentence on this page:

Key idea

$h(x) = b + w_1x + w_2x^2$ is non-linear with respect to the input $x$, but it is still a linear function with respect to the parameters $(b, w_1, w_2)$.

Linear regression cares only that the prediction is a weighted sum of the parameters, not what the inputs are. So we can apply it — we just hand it an extra column.

2.1 Why "linear in the parameters" is the property that matters

Take that apart, because linear regression is an optimisation problem:

$$ \theta^* = \argmin_{\theta} \; \sum_{i=1}^{N}\big(y^{(i)} - \theta^\top z^{(i)}\big)^2 $$

$\theta \in \R^M$ is the parameter vector, $z^{(i)} \in \R^M$ whatever numbers we put in row $i$, $N$ the number of samples, $M$ the entries per row, and $\theta^\top z^{(i)} = \sum_{j} \theta_j z^{(i)}_j$ the prediction.

What makes this solvable in closed form? Two facts, and only two:

  1. The prediction $\theta^\top z^{(i)}$ is a linear function of $\theta$.
  2. The loss is the square of (target − prediction), so the objective is a quadratic in $\theta$, hence convex, hence its gradient is linear in $\theta$, hence setting the gradient to zero gives a linear system you can solve.

Note what is absent: any requirement on $z^{(i)}$. Its entries are constants to the optimiser, computed before it ran. The algebra is identical whether $z^{(i)} = [1, x^{(i)}]^\top$, $[1, x^{(i)}, (x^{(i)})^2]^\top$, or $[1, \sin(x^{(i)}), e^{x^{(i)}}, \log(1 + (x^{(i)})^2)]^\top$.

Analogy

A vending machine is linear in the coins and does not care where they came from. Linear regression is the machine, $\theta$ the quantities combined linearly, the features $z$ denominations you mint in advance — one worth $x^2$ dollars is still a coin. Where it breaks: choosing the denominations is the job here, and choosing badly is how you overfit.

Common mistake

"Linear regression can only fit straight lines." False. It fits any linear combination of features you supply; "linear" refers to linearity in the parameters, not to the shape of the curve in $x$.

Genuinely not linear in its parameters: $h(x) = b + w_1 e^{w_2 x}$. With $w_2$ inside the exponential the objective stops being quadratic in the parameters and no normal-equation trick saves you. That is the boundary of what this chapter buys you.

3. Building $\D'$ by hand

Given the non-linear dataset $\D$, we construct (or engineer) new features to create a dataset $\D'$ that can express the more complex distribution. Concretely: add one column, $x^2$.

Original dataset $\D$

$y$$x$
56
127
13
52
150
⋮⋮

Feature-engineered dataset $\D'$

$y$$x$$x^2$
5636
12749
139
524
1500
⋮⋮⋮

Table 1 — Original dataset $\D$ (left) and feature-engineered dataset $\D'$ (right). The new column is just $6^2=36$, $7^2=49$, $3^2=9$, $2^2=4$, $0^2=0$. No model and no optimiser was touched; we typed a column of numbers.

Train a linear regression model on $\D'$: two features ($z_1 = x$, $z_2 = x^2$) plus a bias, three parameters, and the hypothesis is exactly the quadratic we wanted:

$$ h(x) = b + w_1 x + w_2 x^2 $$

The normal equations on these five rows give

$$ b = 15.354, \qquad w_1 = -7.712, \qquad w_2 = 1.021 $$
The result of training on $\D'$ (reconstructed)
MSE drops from 25.66 (line) to 0.465 (parabola) — a 55× improvement — on the same five points, with the same algorithm, the same loss and the same solver. The only thing that changed was one extra column in the spreadsheet. The dashed grey line is the old linear fit, kept for comparison.
Key idea

We reached a whole new family of hypothesis functions by changing the dataset from $\D$ to $\D'$, with the model untouched. That is what feature engineering brings, and it is everywhere in the field.

3.1 The warning: the same transformation at prediction time

The transformation is part of the model now. The model's inputs are samples of the original $\D$, so to predict on a new $x \in \R$ you must first engineer $x^2$, and only then feed $[1, x, x^2]$ in.

Example

Serving code gets $\theta = [15.354,\; -7.712,\; 1.021]$ and the note "it takes $x$." A request arrives, $x = 4$; the correct answer is

$$ h(4) = 15.354 - 7.712(4) + 1.021(16) = 15.354 - 30.849 + 16.334 = \mathbf{0.840} $$

Column missing. Build $[1, 4]$, the framework pads a zero, and you get $15.354 - 30.849 + 0 = \mathbf{-15.50}$ where the truth near $x=4$ is about $1$ — and negative, which for a count or a price is impossible.

Column wrong. [1, x, x] instead of [1, x, x*x] gives $15.354 - 30.849 + 4.084 = \mathbf{-11.41}$. And it does not crash: the shapes match, the code runs, the dashboard shows numbers. Subtler versions (training standardises $x$ before squaring, serving does not) are wrong by a plausible-looking amount.

The fix: one $\phi$, called by both code paths, never re-implemented — which is why libraries save the transform and the model as a single "pipeline" object.

Guided problemEngineer the feature, fit the model, predict

You are given three samples of $\D$: $(x, y) = (0, 15),\ (2, 5),\ (6, 5)$. Fit $h(x) = b + w_1x + w_2x^2$ exactly (three parameters, three points — expect an exact fit), then predict at $x = 3$.

Step 1 — Build $\D'$

Add the $x^2$ column: $(x, x^2, y) = (0, 0, 15),\ (2, 4, 5),\ (6, 36, 5)$.

The design matrix, with the column of ones for the bias, is

$$ \Phi = \begin{bmatrix} 1 & 0 & 0 \\ 1 & 2 & 4 \\ 1 & 6 & 36 \end{bmatrix}, \qquad y = \begin{bmatrix} 15 \\ 5 \\ 5 \end{bmatrix} $$

Three rows, three columns — square. With three distinct $x$ values this matrix is invertible, so we can solve $\Phi\theta = y$ directly rather than going through the normal equations. (This is the special case $M = N$; §7 says what happens when it goes further.)

Step 2 — Solve the linear system

Row 1: $b + 0 + 0 = 15 \Rightarrow b = 15$.

Row 2: $15 + 2w_1 + 4w_2 = 5 \Rightarrow 2w_1 + 4w_2 = -10 \Rightarrow w_1 + 2w_2 = -5$.

Row 3: $15 + 6w_1 + 36w_2 = 5 \Rightarrow 6w_1 + 36w_2 = -10 \Rightarrow 3w_1 + 18w_2 = -5$.

Multiply the second equation by 3: $3w_1 + 6w_2 = -15$. Subtract from the third: $12w_2 = 10 \Rightarrow w_2 = \tfrac{5}{6} \approx 0.8333$.

Back-substitute: $w_1 = -5 - 2(\tfrac56) = -5 - \tfrac{5}{3} = -\tfrac{20}{3} \approx -6.6667$.

Step 3 — Predict at $x = 3$, correctly and incorrectly

Correctly. Engineer first: $x = 3 \Rightarrow x^2 = 9$. Then

$$ h(3) = 15 - \tfrac{20}{3}(3) + \tfrac56(9) = 15 - 20 + 7.5 = \mathbf{2.5} $$

The true $y$ at $x=3$ in the full dataset is $1$, so we are off by $1.5$ — reasonable, given we fitted on only three points.

Incorrectly. Forget the transform and feed $[1, 3, 0]$: $15 - 20 + 0 = -5$. Feed $[1,3,3]$ by mistake: $15 - 20 + 2.5 = -2.5$. Both are negative; the data never goes below $1$.

Answer & the takeaway

$b = 15$, $w_1 = -20/3$, $w_2 = 5/6$, and $h(3) = 2.5$.

Takeaway: fitting a "curve" required zero new machinery — one extra column and a $3\times3$ linear solve. And the model you shipped is not $\theta$ alone; it is the pair $(\phi, \theta)$. Lose $\phi$ and $\theta$ is meaningless numbers.

4. Another perspective: you are fitting a plane, not a curve

$\D$ had one feature; the model was trained on the two of $\D'$. Two inputs plus one output still fits in a drawing, in three dimensions — and with two features the model is not fitting a line. It is fitting a plane.

Intuition

A second coordinate equal to $x^2$ lifts each point off the $x$–$y$ page onto the sheet $x_2 = x^2$. The lifted points are no longer U-shaped: they lie flat, and a plane passes through all of them. The curvature was absorbed into the position of the points in the new coordinate, leaving the relationship linear. The curve in 1-D is a plane in 2-D feature space.

Figure 3 (reconstructed) — lifting $\D$ into $(x, x^2, y)$ space
x x² y 51015 246 2040 the five points of $D$, lifted fitted plane purple dashes: the curve x₂ = x² that all lifted points must sit on
Reconstruction of the notes' Figure 3. The floor is the feature space $(x, x^2)$; height is $y$. Every sample is forced onto the purple parabola on the floor — that is the only place a point with coordinates $(x, x^2)$ can be. Lift each one to its $y$ value (orange dots) and they line up on a flat teal sheet: the plane $y = 15.354 - 7.712x + 1.021x_2$. The orange curve is nothing but the plane's height read off along the purple parabola — i.e. the parabola you saw in the previous figure. We only draw the strip of the plane near the data; the real plane extends forever.
Common mistake

"So the model can also predict at $(x, x_2) = (3, 100)$?" Algebraically yes; meaningfully no. Engineered features are not free coordinates: a real sample always satisfies $x_2 = x^2$, so all genuine data lies on the purple parabola, a one-dimensional curve inside a two-dimensional space. The plane is defined everywhere, evaluated only on that curve, and fitted only near it. Hence the danger of high-degree features: the data occupies a thin, curved sliver of a huge space, and almost all of that space is unconstrained.

In the lifted picture, what geometric object is the trained model?
Why: The model is $y = b + w_1x + w_2x_2$ — an affine function of two variables, which is a flat plane, full stop. Nothing about it is curved. The curvature you see when you plot $h$ against $x$ comes entirely from the constraint $x_2 = x^2$ that real inputs obey, which traces a parabolic path across the flat plane. Flat surface, curved path along it.

5. Generalising: polynomial feature transforms

To model a quadratic we engineered $x^2$. For a cubic,

$$ h(x) = b + w_1x + w_2x^2 + w_3x^3 $$

engineer $x^3$ as well; for a quartic, $x^4$ too. In general, for a degree-$M$ polynomial on a one-feature $\D$, add the columns below, plus a column of ones for the bias $b$ — from here on the bias is just the weight on a feature that is always 1.

$y$−$x$$x^2$$x^3$…$x^M$
$y^{(1)}$1$x^{(1)}$$\big(x^{(1)}\big)^2$$\big(x^{(1)}\big)^3$…$\big(x^{(1)}\big)^M$
$y^{(2)}$1$x^{(2)}$$\big(x^{(2)}\big)^2$$\big(x^{(2)}\big)^3$…$\big(x^{(2)}\big)^M$
$y^{(3)}$1$x^{(3)}$$\big(x^{(3)}\big)^2$$\big(x^{(3)}\big)^3$…$\big(x^{(3)}\big)^M$
$y^{(4)}$1$x^{(4)}$$\big(x^{(4)}\big)^2$$\big(x^{(4)}\big)^3$…$\big(x^{(4)}\big)^M$
$y^{(5)}$1$x^{(5)}$$\big(x^{(5)}\big)^2$$\big(x^{(5)}\big)^3$…$\big(x^{(5)}\big)^M$
⋮⋮⋮⋮⋮⋱⋮

Table 2 — Original dataset $\D$ (the $y, x$ columns) and feature-engineered dataset $\D'$ (all of it).

Common mistake

The cell $\big(x^{(3)}\big)^2$ holds both kinds of superscript at once: the parenthesised $(3)$ says "third sample", the bare $2$ says "squared". The outer parentheses keep them apart — without them $x^{(3)2}$ is unreadable.

The test: is the superscript in parentheses? Parentheses ⇒ index, no parentheses ⇒ power. So $x^{(2)}$ is sample two, $x^2$ is $x$ squared, $\big(x^{(2)}\big)^2$ is sample two squared. Rows are indexed by $(i)$, columns by powers.

Definition

Polynomial feature transform. Feature engineering generalised to degree $M$: the dataset is augmented with the polynomial terms $1, x, x^2, \dots, x^M$, so each sample of $\D$ contributes one row of $M+1$ numbers.

Two counts to remember. A degree-$M$ transform on a one-dimensional input costs $M+1$ parameters; on $K$ features, taking all monomials up to degree $M$ costs $\binom{K+M}{M}$, which explodes — degree 3 on 100 features is 176,851 columns.

6. Abstract feature transforms: $\phi$ and $\Phi$

Raising to a power is only a special case: any function you desire will do.

The only rule: apply the same transformation to every sample, at training time and at prediction time (§3.1).

6.1 The notation

Given a dataset $X \in \R^{N\times K}$ — $N$ samples, $K$ features each — define a feature transformation function

$$ \phi : \R^{K} \to \R^{M} $$

where $M$ is the number of features $\phi$ produces. The transformed dataset $\Phi$ is stacked row by row:

$$ X = \begin{bmatrix} \text{---}\;\; {x^{(1)}}^{\!\top} \;\;\text{---} \\ \text{---}\;\; {x^{(2)}}^{\!\top} \;\;\text{---} \\ \text{---}\;\; {x^{(3)}}^{\!\top} \;\;\text{---} \\ \vdots \\ \text{---}\;\; {x^{(N)}}^{\!\top} \;\;\text{---} \end{bmatrix} \qquad \Phi = \begin{bmatrix} \text{---}\;\; \phi\big(x^{(1)}\big)^{\!\top} \;\;\text{---} \\ \text{---}\;\; \phi\big(x^{(2)}\big)^{\!\top} \;\;\text{---} \\ \text{---}\;\; \phi\big(x^{(3)}\big)^{\!\top} \;\;\text{---} \\ \vdots \\ \text{---}\;\; \phi\big(x^{(N)}\big)^{\!\top} \;\;\text{---} \end{bmatrix} $$

(often just renamed $X$)

Each $x^{(i)} \in \R^K$ is a column vector, so ${x^{(i)}}^\top$ is a row — row $i$ of the matrix (the long dashes mean "this row is that whole vector laid flat"). Applying $\phi$ turns a $K$-vector into an $M$-vector, so row $i$ of $\Phi$ has $M$ entries and $\Phi \in \R^{N \times M}$. $\phi$ itself you may define to be anything at all.

Common mistake

"Often just renamed $X$" is not a typo. Most texts stop distinguishing the two after the transform and write $X$ for the transformed matrix, $\theta^* = (X^\top X)^{-1}X^\top y$. So always ask which $X$ — raw or transformed? In code that is X_raw versus X_poly; in exams it is $K$ versus $M$ columns.

Example

Example 1 from the notes. A polynomial feature transform of degree 3 is

$$ \phi(x) = [\,1,\ x,\ x^2,\ x^3\,]^\top $$

$K = 1$ raw feature, $M = 4$ engineered ones including the constant, so $\phi: \R^1 \to \R^4$ and $\Phi \in \R^{N\times 4}$.

Numerically, on our dataset with $x^{(1)}=0,\ x^{(2)}=2,\ x^{(3)}=3,\ x^{(4)}=6,\ x^{(5)}=7$:

$$ \Phi = \begin{bmatrix} 1 & 0 & 0 & 0\\ 1 & 2 & 4 & 8\\ 1 & 3 & 9 & 27\\ 1 & 6 & 36 & 216\\ 1 & 7 & 49 & 343\end{bmatrix} \in \R^{5\times 4} $$

The last column is 0, 8, 27, 216, 343: wildly different scales. Polynomial features are numerically nasty, so standardising $x$ before raising it to powers is close to mandatory.

Guided problemDesign $\phi$ for a two-feature dataset

You have $N = 3$ samples with $K = 2$ raw features, $x = (x_1, x_2)$:

sample$x_1$$x_2$$y$
$x^{(1)}$127
$x^{(2)}$304
$x^{(3)}$2-11

You suspect the response depends on each feature, on their product, and on the distance from the origin. Define $\phi$, state $M$, and write out $\Phi$.

Step 1 — Choose the features and count them

"Depends on each feature" ⇒ include $x_1$ and $x_2$. "Their product" ⇒ include the interaction $x_1x_2$. "Distance from the origin" ⇒ include $\lVert x\rVert_2 = \sqrt{x_1^2 + x_2^2}$. And always include the constant 1 for the bias. So

$$ \phi(x) = \big[\,1,\ x_1,\ x_2,\ x_1x_2,\ \sqrt{x_1^2+x_2^2}\,\big]^\top $$

$M = 5$. The map is $\phi : \R^2 \to \R^5$, so $\Phi \in \R^{3\times 5}$.

Step 2 — Evaluate $\phi$ on each sample

$\phi(x^{(1)}) = [1,\ 1,\ 2,\ 1{\cdot}2,\ \sqrt{1+4}]^\top = [1,\ 1,\ 2,\ 2,\ 2.2361]^\top$

$\phi(x^{(2)}) = [1,\ 3,\ 0,\ 3{\cdot}0,\ \sqrt{9+0}]^\top = [1,\ 3,\ 0,\ 0,\ 3]^\top$

$\phi(x^{(3)}) = [1,\ 2,\ -1,\ 2{\cdot}(-1),\ \sqrt{4+1}]^\top = [1,\ 2,\ -1,\ -2,\ 2.2361]^\top$

Step 3 — Stack them as rows
$$ \Phi = \begin{bmatrix} 1 & 1 & 2 & 2 & 2.2361 \\ 1 & 3 & 0 & 0 & 3.0000 \\ 1 & 2 & -1 & -2 & 2.2361 \end{bmatrix} $$

Each row is one transformed sample. Each column is one engineered feature across all samples. If you ever write $\phi(x^{(i)})$ as a column of $\Phi$, you have transposed the whole thing and every subsequent formula will have mismatched shapes.

Answer & the takeaway

$M = 5$, $\Phi \in \R^{3\times5}$ as above.

Takeaway — and a deliberate trap: $M = 5$ but $N = 3$. You have five parameters and three equations. There are infinitely many $\theta$ that fit these three points exactly, and $\Phi^\top\Phi \in \R^{5\times5}$ has rank at most 3, so it is singular and $(\Phi^\top\Phi)^{-1}$ does not exist. That is §7, and it is not a rare pathology — it is what happens every single time you get enthusiastic about features.

7. The normal equations carry over — and where they break

Nothing about the optimisation changed, so everything from chapter 8 transfers with $X$ replaced by $\Phi$:

$$ J(\theta) \;=\; \lVert y - \Phi\theta\rVert_2^2 \;=\; \sum_{i=1}^{N}\Big(y^{(i)} - \theta^\top \phi\big(x^{(i)}\big)\Big)^2 $$

and setting $\nabla_\theta J = 0$ gives, exactly as before,

$$ \Phi^\top\Phi\,\theta^* = \Phi^\top y \qquad\Longrightarrow\qquad \boxed{\;\theta^* = (\Phi^\top\Phi)^{-1}\Phi^\top y\;} $$
Proof

Expand the objective, treating $\Phi$ and $y$ as constants:

$$ J(\theta) = (y - \Phi\theta)^\top(y-\Phi\theta) = y^\top y - 2\,\theta^\top\Phi^\top y + \theta^\top\Phi^\top\Phi\,\theta $$

Line 1 is just the definition of the squared norm. Line 2 multiplies out; the two cross terms $y^\top\Phi\theta$ and $\theta^\top\Phi^\top y$ are $1\times1$ matrices, i.e. scalars, and a scalar equals its own transpose, so they are equal and combine into $-2\theta^\top\Phi^\top y$.

Differentiate with respect to $\theta$, using $\nabla_\theta(\theta^\top a) = a$ and $\nabla_\theta(\theta^\top A\theta) = 2A\theta$ for symmetric $A$ (and $\Phi^\top\Phi$ is symmetric, since $(\Phi^\top\Phi)^\top = \Phi^\top\Phi$):

$$ \nabla_\theta J = -2\Phi^\top y + 2\Phi^\top\Phi\,\theta $$

Set to zero and divide by 2: $\Phi^\top\Phi\,\theta^* = \Phi^\top y$. Since $J$ is a convex quadratic (its Hessian $2\Phi^\top\Phi$ is positive semi-definite, because $v^\top\Phi^\top\Phi v = \lVert\Phi v\rVert^2 \ge 0$ for all $v$), this stationary point is a global minimum. If $\Phi^\top\Phi$ is invertible, multiply on the left by its inverse. ∎

Every step used only that the prediction is $\theta^\top\phi(x)$ — linear in $\theta$. The proof never asked what $\phi$ does. That is the formal version of §2.

7.1 What happens when $M > N$

Chapter 8's corner case — "what if $X^\top X$ isn't invertible?" — is the common case here. $\Phi^\top\Phi$ is $M \times M$ with rank $\operatorname{rank}(\Phi) \le \min(N, M)$:

$M = N$ is already trouble: with $N$ distinct $x$ values and a degree-$(N-1)$ polynomial the Vandermonde matrix is square and invertible, so the unique fit passes through every point and training error is zero — a disaster, as §8 shows. Just below that threshold $\Phi^\top\Phi$ is invertible but ill-conditioned, so $\theta$ comes out with enormous entries of alternating sign that nearly cancel: the violent wiggles you are about to see.

Key idea

Three fixes exist for $M \ge N$, and you will meet all of them:

  1. Use fewer features — the subject of the rest of this page.
  2. Use the pseudo-inverse $\theta^* = \Phi^{+}y$, which among all the perfect fits returns the one with smallest $\lVert\theta\rVert$. beyond syllabus
  3. Regularise: solve $(\Phi^\top\Phi + \lambda I)\theta = \Phi^\top y$ instead. Adding $\lambda I$ with $\lambda > 0$ makes the matrix strictly positive definite, hence invertible, always. Full treatment in chapter 12.

8. "Why not just have more and more features?"

If more features reach a larger family of functions, why not add as many as possible? Take genuinely linear data — degree 1 is the honest answer — and fit transforms of increasing degree $k$.

Figure 4 (reconstructed) — linear data, polynomial transforms of degree $k = 1, 5, 11, 30$
Same 12 points, same algorithm, four feature transforms. All four fits are computed live by the normal equations in your browser; nothing here is drawn by hand. At $k=1$ the fit is the trend. At $k=5$ it is still sane. At $k=11$ the model has as many parameters as data points, so it threads exactly through all 12 and its training error is ~0 — while it predicts values like $-3.5$ and $8.9$ between points where the truth is around $1.5$. At $k=30$ there are 31 parameters for 12 points; the curve leaves the panel entirely (it reaches about $-41$ and $+75$) and the drawn line is clipped at the frame.
Key idea

With very many features, the model starts to prioritise matching the exact distribution of the training data rather than capturing its general trend. That is overfitting, and it comes from the data's dimensionality being too high — exactly what complex feature transforms produce. So the transform must be reasonable: enough to fit the distribution, not enough to overfit it.

Intuition

A student who learns the material and one who memorises last year's exam both score 100% on last year's exam; exactly one can answer a new question. Training error is last year's exam, and degree 11 on 12 points has enough memory to store the answer key.

Where it breaks: nothing is being decided. Least squares minimises what you told it to. The failure is yours, in choosing a hypothesis class rich enough that "memorise" and "learn" score identically on the objective.

9. Interactive: watch overfitting happen

Ten training points (orange) from a smooth true function plus noise; forty held-out test points (grey) the model never sees. The slider sets the degree $M$, and the fit is recomputed from the normal equations on every move.

Polynomial degree ⟶ fit, training error, test error

What to notice — in this order. (1) Drag from 0 to 3: both errors fall. The model is underfitting below that; it lacks the capacity to express the shape. (2) Around 3–5 the test error bottoms out. That is the sweet spot. (3) Keep going: the training curve keeps falling and hits exactly zero at $M = 9$, where the number of parameters $M+1 = 10$ equals the number of training points $N = 10$ and the polynomial interpolates. (4) Meanwhile the test error climbs — by $M = 15$ it is eight times its best value. The two curves separate, and the gap between them is the overfitting. The training curve never warns you. If it were your only measurement you would choose $M = 15$ and ship a disaster.
In the widget above, training MSE hits exactly $0$ at degree 9. Why 9 and not some other number?
Why: $\Phi$ is $10\times10$ once $M+1 = 10$. With distinct $x^{(i)}$ the Vandermonde matrix is invertible, so there is a unique $\theta$ with $\Phi\theta = y$ exactly — every residual is zero. Beyond degree 9, $M+1 > N$ and there are infinitely many zero-error solutions (§7.1), so the training error stays at zero while the test error keeps getting worse. Zero training error is not a sign of a good model; here it is the precise symptom of having exactly as much capacity as data.

10. Overfitting, properly

The notes stop at "this is overfitting; more to come later." Here is the later part. extends the reading

10.1 The two error curves

Definition

Training error is the average loss on the data you fitted on. Test error (or generalisation error) is the average loss on data drawn from the same distribution that the model never saw during fitting.

As capacity grows, training error decreases monotonically (a richer hypothesis class contains the poorer one, so its best member is at least as good), while test error falls, reaches a minimum, then rises: the classic U.

The canonical picture: error against model complexity
model complexity (number of features / polynomial degree / tree depth) → error → sweet spot the gap = how much you overfit underfitting both errors high overfitting train low, test high training error test error
The single most reused diagram in machine learning. On the left both curves are high and close together — the model cannot express the truth, so it fails on training and test data alike. On the right they diverge: the model expresses the noise in the training set, which by definition does not repeat in the test set. The vertical gap between the curves is the quantity you are trying to keep small at the same time as the test curve itself.

10.2 Saying it with risk and empirical risk

The precise version is overfitting in the language of chapter 5. The true risk (expected loss) of a hypothesis $h$ is an expectation over the data-generating distribution $p(x, y)$:

$$ R(h) \;=\; \E_{(x,y)\sim p}\big[\ell\big(y, h(x)\big)\big] $$

That is what you care about, and you cannot compute it: you do not have $p$. So you compute the empirical risk on your $N$ samples instead:

$$ \hat R(h) \;=\; \frac{1}{N}\sum_{i=1}^{N}\ell\big(y^{(i)}, h(x^{(i)})\big) $$

and minimise that: empirical risk minimisation. The whole enterprise rests on $\hat R$ being a good stand-in for $R$.

Key idea

Overfitting is the failure of that stand-in. As capacity grows $\hat R(h^*)$ keeps falling, all the way to zero, while $R(h^*)$ turns around and rises. The optimiser does its job perfectly; the job is the wrong one.

Precisely: $\hat R$ is an unbiased estimate of $R$ for a hypothesis chosen independently of the sample. But $h^*$ was chosen by minimising $\hat R$ on that very sample, so it is selected partly for fitting the sample's noise. That makes $\hat R(h^*)$ an optimistically biased estimate of $R(h^*)$, and the bias grows with capacity.

Which is why a held-out test set works: those points did not choose $h$, so on them $\hat R$ is unbiased again.

10.3 Underfitting, the mirror failure

Figure 2 was underfitting: a model too rigid to express the truth, with high error on training and test data. Look at both numbers and the two failures are never confused.

Training errorTest errorDiagnosisWhat to do
HighHigh (≈ training)UnderfittingMore features, higher degree, richer model, train longer
LowLowGood fitStop. Ship it.
Very low / zeroHighOverfittingFewer features, regularisation, more data
HighLowBugYour split leaked, or the sets came from different distributions

10.4 Bias and variance, in words

Intuition

Re-collect the training set many times and re-fit: you get a cloud of fitted functions. Bias is how far the cloud's average sits from the truth (degree 1 on curved data: the same wrong line every time); variance is how much its members differ from each other (degree 15 on 10 points: shift one point and the curve rewrites itself). On a dartboard, bias is the group being off-centre, variance its being scattered.

High bias, low variance ⇒ underfitting; low bias, high variance ⇒ overfitting. Test error is their sum plus irreducible noise — one term falls, the other rises, hence the U.

10.5 The fixes the notes promise are coming

The notes promise "more to come on how to combat overfitting." Four fixes, all of them chapter 12:

Guided problemDiagnose four models from their error numbers

You fit polynomial transforms of four degrees on $N = 10$ training points and measure on 40 held-out points. Which degree do you ship, and what is wrong with each of the others?

$M$train MSEtest MSE
10.1460.339
50.0090.157
90.0000.355
150.0001.272

(These are the real numbers from the widget in §9.)

Step 1 — Read the training column alone. What can you conclude?

Almost nothing. It falls monotonically: 0.146 → 0.009 → 0.000 → 0.000. That is guaranteed by construction, because the degree-15 hypothesis class contains the degree-9 class, which contains degree 5, which contains degree 1. A larger class cannot have a worse best member.

So the training column can never tell you to stop. Any model-selection rule based on training error alone picks the biggest model, every time.

Step 2 — Read the test column

0.339 → 0.157 → 0.355 → 1.272. It falls then rises: the U. Minimum at $M = 5$.

$M = 1$: both errors are high-ish and the gap is modest ($0.339/0.146 \approx 2.3$). Classic underfitting — not enough capacity.

$M = 9$ and $M = 15$: train is exactly zero while test is worse than at $M=1$. The gap is infinite in ratio terms. Textbook overfitting. And note $M = 15$ gives $M + 1 = 16 > 10 = N$, so by §7.1 the solution isn't even unique — a solver detail determines which of infinitely many perfect fits you got.

Step 3 — Is $M=5$ definitely the answer?

It is the best of the four measured, which is not the same as best overall. Two caveats worth stating out loud:

(a) You only sampled four degrees. $M = 3$ or $M = 4$ might do better, and they are simpler — with two models of comparable test error, prefer the simpler one, because its estimate is more stable and it will degrade more gracefully on new data.

(b) You just used the test set to choose $M$. That makes 0.157 an optimistic estimate of the true risk of the selected model — you have leaked the test set into the model-selection decision. Correct practice: choose on a validation set, then report the test number once, at the end, never having looked at it.

Answer & the takeaway

Ship $M = 5$ (or check $M = 3,4$ first and ship the simplest one within noise of the best). $M = 1$ underfits; $M = 9$ and $M = 15$ overfit, with $M = 15$ additionally rank-deficient.

Takeaway: never make a model-selection decision from training error. And keep the set you use to report separate from the set you use to choose.

11. The same story, in a different chapter

Overfitting happens to any model with enough capacity to memorise. A decision tree with no depth limit splits until every leaf is pure, and with distinct feature vectors it always can — in the limit, one leaf per sample. Training error zero; test error bad, because a leaf built from one sample knows only that sample's label. Line the two up:

Polynomial featuresDecision trees
Capacity dialDegree $M$Depth / number of leaves
Memorisation point$M + 1 = N$: the polynomial interpolatesOne sample per leaf: every leaf pure
SymptomViolent wiggles between training pointsSplits on noise; tiny leaves with confident labels
Capacity limiterChoose a lower degree; add $\lambda\lVert\theta\rVert^2$Stopping criteria: max depth, min samples per leaf, min information gain; pruning
Key idea

A tree's stopping criteria are its way of limiting capacity — what a smaller $M$ does for polynomial features and what $\lambda$ does for ridge. Different algorithms, same dial, same U-curve, same rule: measure on data you did not fit on.

You fit a degree-20 polynomial to 200 points and get train MSE 0.02, test MSE 0.03. Your colleague says "degree 20 is way too complex, you must be overfitting." Who is right?
Why: Overfitting is not a property of the degree; it is a property of the relationship between capacity and data, and it is diagnosed by the train/test gap, not by the parameter count. With $N = 200$ and $M + 1 = 21$ you have ten samples per parameter, and the near-equal errors confirm the model is generalising. The same degree 20 on 10 points would be catastrophic. Always diagnose from the gap, never from the number of features alone.

12. Common mistakes, collected

Common mistake
  1. "$h(x)=b+w_1x+w_2x^2$ is a non-linear model." It is non-linear in $x$ and linear in $\theta$. Only the second fact decides whether linear regression applies.
  2. Forgetting $\phi$ at prediction time. §3.1. The shipped model is the pair $(\phi, \theta)$, and the failure is silent.
  3. Fitting $\phi$'s own parameters on the test set. If $\phi$ standardises using $\mu$ and $s$, those must be computed on the training data only and then reused. Computing them over train+test leaks test information into training.
  4. Reading $x^{(i)}$ as a power. Check for parentheses. In Table 2 both kinds appear in one cell.
  5. Treating engineered features as independent coordinates. $x$ and $x^2$ are perfectly dependent; real data lies on a curve in feature space, and off that curve the model is pure extrapolation.
  6. Choosing the model by training error. It is monotone in capacity. It can only ever tell you to add more.
  7. Assuming more features is never worse. It is never worse on the training set — which is exactly the problem.
  8. Raising raw, unscaled $x$ to high powers. If $x \sim 100$, then $x^6 \sim 10^{12}$; $\Phi^\top\Phi$ becomes numerically hopeless. Standardise before the transform.
Which of these models can not be fitted by ordinary linear regression after a feature transform?
Why: Options A and C are weighted sums of fixed functions of the input, so define $\phi$ to emit those functions and the prediction is $\theta^\top\phi(x)$ — linear in $\theta$, normal equations apply. In option B the parameter $w_2$ sits inside the exponential, so the prediction is not a linear function of $(b, w_1, w_2)$, the objective is not a quadratic in the parameters, and no amount of feature engineering fixes it. You would need iterative non-linear optimisation (see chapter 9), with no guarantee of a global optimum. The rule: the parameters must sit outside, multiplying fixed functions of $x$.

13. Recap

Every statement is in the Essentials box at the top. Four things are worth repeating: