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.
How a model that is only ever linear in its parameters fits curves — and the exact price of overdoing it.
- The whole idea — $h(x)=b+w_1x+w_2x^2$ is non-linear in $x$ but linear in the parameters. Linear regression requires only the second, so you change the data, not the model.
- Polynomial feature transform — to fit a degree-$M$ polynomial, add the columns $1, x, x^2, \dots, x^M$: $M+1$ parameters. $x^{(i)}$ is sample $i$; $x^i$ is a power.
- General transform — $\phi : \R^{K} \to \R^{M}$, applied to every sample and stacked row-wise, gives $\Phi \in \R^{N\times M}$ with row $i$ equal to $\phi(x^{(i)})^\top$ (often just renamed $X$).
- Normal equations, unchanged — $\theta^* = (\Phi^\top\Phi)^{-1}\Phi^\top y$, because the derivation only ever used that the prediction is $\theta^\top\phi(x)$.
- Same $\phi$ at prediction time — the shipped model is the pair $(\phi, \theta)$. Omit the transform and nothing crashes; the numbers are simply wrong.
- Geometry — with features $(x, x^2)$ the model is a plane; the curve you see is that plane's height read along the constraint $x_2 = x^2$, which is where all real data lies.
- $M \ge N$ — $\operatorname{rank}(\Phi^\top\Phi) \le \min(N, M)$, so for $M > N$ it is singular: infinitely many $\theta$ with zero training error. At $M+1 = N$ the fit interpolates every point exactly.
- Overfitting — past a point the empirical risk $\hat R$ keeps falling while the true risk $R$ rises. Training error is monotone in capacity, so it can never tell you to stop.
- Diagnosis — high train and high test = underfitting; near-zero train and high test = overfitting. Judge by the gap, never by the feature count.
- Cures — fewer features, more data, held-out validation or $k$-fold CV, and regularization: chapter 12.
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
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.
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.
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.
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.
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:
$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:
- The prediction $\theta^\top z^{(i)}$ is a linear function of $\theta$.
- 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$.
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.
"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$ |
|---|---|
| 5 | 6 |
| 12 | 7 |
| 1 | 3 |
| 5 | 2 |
| 15 | 0 |
| ⋮ | ⋮ |
Feature-engineered dataset $\D'$
| $y$ | $x$ | $x^2$ |
|---|---|---|
| 5 | 6 | 36 |
| 12 | 7 | 49 |
| 1 | 3 | 9 |
| 5 | 2 | 4 |
| 15 | 0 | 0 |
| ⋮ | ⋮ | ⋮ |
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 $$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.
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.
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.
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.
"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.
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).
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.
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.
- Periodic: $\sin(x)$, paired with $\cos(x)$ so a phase shift is a linear combination. For cycles — hour of day, day of year.
- Radial: the distance $\lVert x\rVert_2 = \sqrt{x_1^2 + \dots + x_K^2}$. This alone lets a linear model carve out a circle in the original space, since "$\lVert x\rVert_2 \le r$" is linear in the new coordinate.
- Logs: $\log(1+x)$ compresses heavy tails (income, view counts) so a handful of giants stop dominating the squared loss.
- Interactions: $x_1x_2$. Without it the effect of $x_1$ must be the same whatever $x_2$ is; with it the model can say "fertiliser helps, but only if there is water."
- Indicators / one-hot: for colour ∈ {red, green, blue}, three binary columns $\1[\text{red}], \1[\text{green}], \1[\text{blue}]$ — how a model that only does arithmetic handles a variable with none.
- Buckets: $\1[x < 0],\ \1[0 \le x < 5],\ \1[x \ge 5]$ turns a continuous feature into a step function fitted at whatever heights the model likes.
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.
"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 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.
You have $N = 3$ samples with $K = 2$ raw features, $x = (x_1, x_2)$:
| sample | $x_1$ | $x_2$ | $y$ |
|---|---|---|---|
| $x^{(1)}$ | 1 | 2 | 7 |
| $x^{(2)}$ | 3 | 0 | 4 |
| $x^{(3)}$ | 2 | -1 | 1 |
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
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\;} $$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)$:
- If $M > N$, then $\operatorname{rank}(\Phi^\top\Phi) \le N < M$, and an $M\times M$ matrix of rank less than $M$ is singular. The inverse does not exist and the boxed formula is meaningless as written.
- Geometrically: you have $M$ unknowns and only $N$ independent equations. The solution set is an affine subspace of dimension at least $M - N$ — infinitely many parameter vectors that all achieve exactly zero training error.
- Each one interpolates the training data perfectly and they disagree wildly everywhere else. Nothing in the least-squares objective prefers one over another.
$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.
Three fixes exist for $M \ge N$, and you will meet all of them:
- Use fewer features — the subject of the rest of this page.
- Use the pseudo-inverse $\theta^* = \Phi^{+}y$, which among all the perfect fits returns the one with smallest $\lVert\theta\rVert$. beyond syllabus
- 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$.
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.
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.
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
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.
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$.
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 error | Test error | Diagnosis | What to do |
|---|---|---|---|
| High | High (≈ training) | Underfitting | More features, higher degree, richer model, train longer |
| Low | Low | Good fit | Stop. Ship it. |
| Very low / zero | High | Overfitting | Fewer features, regularisation, more data |
| High | Low | Bug | Your split leaked, or the sets came from different distributions |
10.4 Bias and variance, in words
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:
- Held-out validation set — split train / validation / test; pick the degree by validation error, report on test. Costs data.
- $k$-fold cross-validation — $k$ fits, each validating on a different fold, averaged. Costs $k\times$ the compute, buys a much less noisy estimate.
- Regularisation — keep the features, charge for large weights: minimise $\lVert y - \Phi\theta\rVert^2 + \lambda\lVert\theta\rVert^2$, giving $\theta^* = (\Phi^\top\Phi + \lambda I)^{-1}\Phi^\top y$, which also fixes the invertibility problem of §7.1.
- More data — overfitting is a ratio of capacity to data, so doubling $N$ moves the interpolation threshold $M+1 = N$ right and the U-curve's minimum to a higher complexity.
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 MSE | test MSE |
|---|---|---|
| 1 | 0.146 | 0.339 |
| 5 | 0.009 | 0.157 |
| 9 | 0.000 | 0.355 |
| 15 | 0.000 | 1.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 features | Decision trees | |
|---|---|---|
| Capacity dial | Degree $M$ | Depth / number of leaves |
| Memorisation point | $M + 1 = N$: the polynomial interpolates | One sample per leaf: every leaf pure |
| Symptom | Violent wiggles between training points | Splits on noise; tiny leaves with confident labels |
| Capacity limiter | Choose a lower degree; add $\lambda\lVert\theta\rVert^2$ | Stopping criteria: max depth, min samples per leaf, min information gain; pruning |
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.
12. Common mistakes, collected
- "$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.
- Forgetting $\phi$ at prediction time. §3.1. The shipped model is the pair $(\phi, \theta)$, and the failure is silent.
- 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.
- Reading $x^{(i)}$ as a power. Check for parentheses. In Table 2 both kinds appear in one cell.
- 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.
- Choosing the model by training error. It is monotone in capacity. It can only ever tell you to add more.
- Assuming more features is never worse. It is never worse on the training set — which is exactly the problem.
- 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.
13. Recap
Every statement is in the Essentials box at the top. Four things are worth repeating:
- The fix for complex data is applied to the data, not the model — and "linear" means linear in the parameters.
- The shipped model is the pair $(\phi, \theta)$. Lose $\phi$ and $\theta$ is meaningless numbers.
- The curve you plot is a flat plane's height read along the constraint curve the features obey. Off that curve there is no support at all.
- Training error is monotone in capacity, so it can only ever tell you to add more. Measure on data you did not fit on.