Unit 1 · 6 Hours · Course Outcome CO1
The mathematics every model runs on
Six topics that look like separate maths lectures are really one idea seen from six angles: a model is a set of numbers, a loss says how wrong they are, and calculus tells you which way to move them. This unit builds that machinery on a dataset small enough to compute by hand.
Sections 1.1 – 1.4
Five students, one straight line
Which line is least wrong?
Five students report hours of focused practice and the marks they scored out of 10. The marks do not sit on any straight line, so no line is right. Asking for the least wrong line turns the question into algebra: two equations, two unknowns, one answer.
That answer is marks = 1.1 + 1.3 × hours. Section 1.1 solves for it exactly, 1.3 says what "least wrong" means, and 1.4 finds the same answer again by walking downhill — the method that scales when the exact solution stops being available.
Section 1.5
The same five, now labelled
Which question separates them best?
Forget the marks and keep only pass or fail. Three passed, two failed. A decision tree has to pick one yes/no question to ask first, and it picks the one that removes the most uncertainty.
Entropy measures that uncertainty in bits: 0.9710 bits before asking anything. Ask "practised more than 2 hours?" and it drops to 0. Ask "attended the lab?" and it drops to 0.9510 — almost nothing. Information gain is that drop, and it is the whole of tree learning.
Sections 1.6 – 1.7
Five points, four curves
Why does the best fit predict worst?
A degree-4 polynomial passes exactly through all five students. Its training error is zero. Ask it about a student who practised 6 hours and it answers −3 marks.
Section 1.6 splits that failure into bias and variance and shows why the two cannot both be small. Section 1.7 fixes it by making large parameters expensive rather than by deleting them.
Section 1.8
From a number to a decision
What does a neuron do after adding up?
Every model so far output a raw number. To output a probability, or to stack layers into something that is not just one big linear map, the number gets pushed through a non-linear squash.
Which squash you pick decides whether gradients survive the trip back through the network. Sigmoid's derivative never exceeds 0.25, so five stacked layers shrink a gradient by at least 1024× — the reason ReLU took over.
What you need before this chapter
From the bridge topics: vectors and dot products, matrix × vector multiplication, partial derivatives, and the idea of a probability distribution over a discrete variable. Nothing else. Where a bridge topic is load-bearing — the gradient vector, the log of a probability — it is re-derived here rather than assumed.
You do not need calculus of several variables beyond partial derivatives, and you do not need to have seen any machine learning model yet. Unit 2 assumes everything in this chapter.
The dataset this whole chapter uses
One dataset, eight sections. Every formula gets applied to these five rows, so that by section 1.8 you already know the numbers by heart and can spend attention on the new idea instead of on new data.
| Student | Hours practised x | Marks /10 y | Attended lab | Result |
|---|---|---|---|---|
| A | 1 | 2 | yes | fail |
| B | 2 | 4 | no | fail |
| C | 3 | 5 | yes | pass |
| D | 4 | 7 | yes | pass |
| E | 5 | 7 | no | pass |
Five sums are worth memorising now, because six sections use them: n = 5, Σx = 15, Σy = 25, Σx² = 55, Σxy = 88. The pass label is defined as marks 5 or above, which is why C, D and E pass.
System of Linear Equations
Fitting a model is almost always solving a system that has no exact solution. Understanding what that means is the entry point to everything else.
The question
You have five students and you want one straight line through their marks. A straight line has two unknowns: where it starts and how steeply it climbs. Five data points give you five demands on those two unknowns. Five demands, two dials — you cannot satisfy them all.
So the honest question is not "what is the solution" but "what does an unsolvable system tell us, and what should we return instead". Every regression, every least-squares problem, and the closed-form solution used by linear regression in Unit 2 is this question.
The intuition
A single linear equation in two unknowns, like w₀ + 3w₁ = 5, is a line in the plane of possible parameter values. Every point on that line is a parameter pair satisfying that one equation. Two such equations are two lines, and solving the system means finding where they cross.
That picture immediately gives the three cases. Two lines that cross at a point: exactly one solution. Two parallel lines: no solution, the demands contradict each other. Two lines lying on top of each other: infinitely many solutions, because the second equation added no new information.
Machine learning lives almost entirely in the "no solution" case, and it is not a failure. It means the data is richer than the model. The fix is to stop demanding equality and start minimising disagreement.
The formal treatment
Write the system as A θ = b, where A is the m × d coefficient matrix, θ (theta) is the d-vector of unknowns, and b is the m-vector of right-hand sides. Here m counts equations and d counts unknowns.
The rank of a matrix is the number of genuinely independent rows in it — rows that are not sums or multiples of the others. [A | b] is the augmented matrix, formed by gluing b on as an extra column. If gluing b on raises the rank, then b points somewhere the columns of A cannot reach, and the system is inconsistent.
With m = 5 equations and d = 2 unknowns the system is overdetermined, and for real measured data it is inconsistent with probability one. Rather than solve it, we minimise the squared length of the residual vector Aθ − b. Setting the derivative of that squared length to zero gives the normal equations:
Three facts about this. The normal equations are always consistent, so a least-squares answer always exists. The matrix AᵀA is d × d — small, no matter how many data rows you have. And AᵀA is invertible exactly when the columns of A are linearly independent, which in data terms means no feature is a linear combination of the others.
Depth — why they are called "normal"
The residual that minimises length must be perpendicular (normal) to everything the model can produce. The set of producible vectors is the column space of A. Perpendicular to every column means Aᵀ(Aθ − b) = 0, which rearranges to AᵀAθ = Aᵀb. So least squares is orthogonal projection of b onto the column space, and nothing more. Skippable, but it explains why the residuals of a fitted line always sum to zero when the model has an intercept.
Cost
Forming AᵀA costs O(md²) and inverting it costs O(d³). Linear in the number of data rows, cubic in the number of features. That is why the closed form is used for a 12-feature house-price model and gradient descent for a model with a million parameters.
The worked example
Worked 1.1 — the least-squares line, solved exactly
closed formw₀ and w₁ so that y ≈ w₀ + w₁x minimises total squared error on the five students.The column of ones is what lets the line have a non-zero intercept. Leave it out and you force the line through the origin.
Every entry is one of the sums already tabulated. No matrix multiplication is really needed.
Divide (i) by 5: w₀ + 3w₁ = 5, so w₀ = 5 − 3w₁.
det(AᵀA) = 5(55) − 15(15) = 275 − 225 = 50, so the inverse is (1/50) [[55, −15], [−15, 5]] = [[1.1, −0.3], [−0.3, 0.1]].
Predictions: 2.4, 3.7, 5.0, 6.3, 7.6
Residuals: −0.4, +0.3, 0.0, +0.7, −0.6 (they sum to 0, as the intercept guarantees)
Read the parameters as sentences, always. A student who practises nothing is predicted 1.1 marks; each extra hour of practice is worth 1.3 marks. That sentence is the model.
The visualization
Two equations, one crossing
parameter space(1.1, 1.3) satisfies both. Sections 1.2 and 1.4 keep using these axes.The pitfalls
Where marks are lost
- Dropping the column of ones and then wondering why the fit is bad. Without it the model is
y = w₁x, forced through the origin. On this data that givesw₁ = 88/55 = 1.6and a worse fit. - Trying to invert a singular
AᵀA. If one feature is 2× another, the columns are dependent, the determinant is 0, and there is no unique answer — infinitely many parameter pairs fit equally well. This is multicollinearity, and section 1.7 is its cure. - Believing a 5×2 system "has no solution, so linear regression fails". The system has no exact solution; the least-squares problem always has one.
- Reversing the roles in
AᵀA.AAᵀis 5×5 here and is not what you want. The small square matrix is the correct one. - Solving by computing the inverse in code. Numerically, solving the system directly is more stable than forming
(AᵀA)⁻¹. Fine by hand for 2×2; wrong habit at scale.
Practice
P1.1.1 (direct) — Fit y = w₀ + w₁x by normal equations to the four points (1,3), (2,4), (3,6), (4,7). Report the line, the residuals, and the MSE.
Sums: n = 4, Σx = 10, Σy = 20, Σx² = 30, Σxy = 57.
Predictions 2.9, 4.3, 5.7, 7.1. Residuals +0.1, −0.3, +0.3, −0.1. SSE = 0.01 + 0.09 + 0.09 + 0.01 = 0.20, MSE = 0.20/4 = 0.05. Residuals sum to zero, as expected.
P1.1.2 (variation) — A colleague adds a second feature: x₂ = 2x₁ ("minutes per half-hour block"). What happens to AᵀA, and what does it mean for the fitted parameters?
The design matrix now has columns [1, x₁, 2x₁]. The third column is exactly twice the second, so rank(A) = 2 while d = 3. Therefore AᵀA is 3×3 with rank 2, its determinant is 0, and it cannot be inverted.
Interpretation: the least-squares fit is unchanged — the same predictions are still optimal — but the parameters are no longer identifiable. Any pair (w₁, w₂) with w₁ + 2w₂ = 1.3 gives an identical prediction, so the model has infinitely many equally good parameter settings, and any statement like "an extra hour is worth w₁ marks" becomes meaningless.
P1.1.3 (interpretation) — A tool reports a fitted intercept of 1.1 and slope of 1.3, and separately reports that the mean of y is 5 and the mean of x is 3. Verify the fit is self-consistent without touching the raw data.
Equation (i) of the normal equations, divided by n, says ̄y = w₀ + w₁̄x: the least-squares line always passes through the point of means. Check: 1.1 + 1.3(3) = 1.1 + 3.9 = 5.0 = ̄y. Consistent.
This is the cheapest sanity check that exists on a reported linear fit, and it catches transposed or mismatched columns instantly. It holds for any model with an intercept term, not just this data.
P1.1.4 (synthesis) — Without computing anything, argue from section 1.1 alone that the least-squares problem for the five students has exactly one answer, and say which property of the data would have to change for that to fail.
AᵀA is invertible if and only if the columns of A are linearly independent. The columns are the all-ones vector and the hours vector. A vector of ones and a vector of hours are dependent only if the hours are all identical, since a constant vector is the only multiple of the ones vector.
The hours are 1, 2, 3, 4, 5 — not identical. So the columns are independent, AᵀA is invertible, and the solution is unique. It would fail if every student had practised the same number of hours: then there is no information about slope at all, and infinitely many lines fit the single vertical stack of points equally well.
Convex and Non-convex Functions
Whether "walk downhill" is a complete algorithm or merely a hopeful heuristic depends entirely on the shape of the function you are walking on.
The question
Section 1.4 will minimise a function by repeatedly stepping downhill. When does that guarantee the best answer, and when does it merely find a comfortable spot? The answer depends on a single geometric property of the function, and the whole vocabulary of "the loss surface" rests on it.
The intuition
Picture two landscapes. The first is a smooth bowl. Drop a marble anywhere; it rolls to the one lowest point. Where it started does not matter, and once it stops you know it is at the bottom.
The second is an egg carton. Drop a marble and it settles in whichever dip it happened to land near. It has stopped moving, but there is a deeper dip three positions over that it will never find. Where it started decided everything.
Bowls are convex. Egg cartons are non-convex. Linear and logistic regression give you bowls; neural networks give you egg cartons in a million dimensions. That single distinction explains why linear regression is reproducible and neural network training is not.
The formal treatment
A set is convex if the straight segment joining any two of its points stays inside the set. A function f defined on a convex set is convex if its graph never rises above any of its own chords — where a chord is the straight line joining two points on the graph.
Two equivalent tests are easier to apply. The first-order condition: a differentiable f is convex exactly when its graph lies above every tangent line, so a tangent is a global underestimate. The second-order condition: f is convex exactly when its second derivative is non-negative everywhere, or in several variables when its Hessian — the matrix of all second partial derivatives — is positive semi-definite.
The payoff is one theorem, and it is the reason convexity is taught at all:
So on a convex loss, "the gradient is zero" means "done, and this is the best possible". On a non-convex loss it means only "locally flat", which a saddle point also satisfies.
Depth — convex in what?
Convexity is a statement about the function of the parameters, with the data held fixed. The MSE of linear regression is convex in (w₀, w₁) even though, viewed as a function of x, a parabola-shaped prediction curve is possible. Confusing the two is a common exam error: adding a squared feature x² to a linear model keeps the loss convex in the parameters, because the model is still linear in the parameters. It is the composition of parameters through a non-linear activation, as in section 1.8, that destroys convexity.
The worked example
Worked 1.2 — prove the spine's loss surface is a bowl
Hessian testJ(w₀, w₁) = (1/5)Σ(w₀ + w₁xᵢ − yᵢ)² is strictly convex, then verify the chord test numerically at two specific parameter values.Differentiate twice. The data appears, the parameters do not — a signature of a quadratic.
Positive definite, so J is strictly convex and has exactly one minimum — the (1.1, 1.3) found in 1.1. Note H = (2/n)AᵀA, so the same matrix that solved the system also certifies the shape.
Hold the intercept at 1.1 and vary the slope. Take u = 0.5, v = 2.5, midpoint 1.5, so λ = 0.5.
Any downhill method started anywhere converges to the same unique
(1.1, 1.3).A non-convex function to compare against
Take g(w) = w⁴ − 4w² + w. Its derivative g′(w) = 4w³ − 8w + 1 has three roots, and g″(w) = 12w² − 8 is negative between ±√(2/3) ≈ ±0.816 — so the second-order test fails there and the function cannot be convex.
| w | g(w) | g″(w) | type | what descent does here |
|---|---|---|---|---|
| −1.4730 | −5.4442 | +18.04 | global minimum | reached only if started at w < 0.126 |
| +0.1260 | +0.0627 | −7.81 | local maximum | the watershed between the two basins |
| +1.3470 | −2.6186 | +13.77 | local minimum | reached from any start w > 0.126, and it is 2.83 worse |
Both minima satisfy g′(w) = 0. Both are places where descent stops and reports success. Only one is right, and which one you get is decided by initialisation — which is exactly why neural network training in Unit 4 cares so much about how weights are initialised.
The visualization
The chord test, live
drag the second pointThe pitfalls
Where marks are lost
- "Convex means it has only one minimum." Convex means no local minimum is worse than the global one. A convex function can have a flat valley floor with infinitely many equally optimal points — which is exactly what happens under multicollinearity. Uniqueness needs strict convexity.
- Testing convexity in the wrong variable. The loss surface is a function of parameters. Sketching
yagainstxand declaring the loss non-convex because the data looks curved is a different question entirely. - Assuming gradient zero means minimum. On a non-convex surface it can be a maximum or, far more commonly in high dimensions, a saddle point — downhill in some directions, uphill in others. Check the Hessian, or in practice check that the loss is still decreasing.
- Checking only the diagonal of the Hessian. Both diagonal entries positive is not enough;
[[1, 5], [5, 1]]has positive diagonals and determinant −24. The off-diagonal coupling matters. - Treating non-convex as hopeless. Deep networks are non-convex and work extremely well. In high dimensions most stationary points are saddles rather than bad minima, and the local minima that are found tend to be nearly as good as each other.
Practice
P1.2.1 (direct) — Is f(w₀, w₁) = 3w₀² + 2w₀w₁ + w₁² − 4w₀ convex? Strictly?
Second partials: ∂²f/∂w₀² = 6, ∂²f/∂w₀∂w₁ = 2, ∂²f/∂w₁² = 2. So H = [[6, 2], [2, 2]].
Leading entry 6 > 0; determinant 6(2) − 4 = 8 > 0. Positive definite everywhere (H is constant), so f is strictly convex and has a unique minimiser. Note the linear term −4w₀ never affects convexity — it vanishes on the second derivative. Only the quadratic part decides.
P1.2.2 (variation) — Change one coefficient: f(w₀, w₁) = 3w₀² + 8w₀w₁ + w₁². What is the shape now, and what does gradient descent do?
H = [[6, 8], [8, 2]]. Determinant = 12 − 64 = −52 < 0. A negative determinant in 2×2 means one positive and one negative eigenvalue: the surface is a saddle, convex along one direction and concave along the perpendicular one.
The origin has zero gradient but is not a minimum. Gradient descent started exactly on the saddle's stable direction would stall; started anywhere else it slides off along the concave direction and the loss runs to −∞. This is why an unbounded-below objective is a modelling bug, not an optimisation one.
P1.2.3 (interpretation) — Two students train identical neural networks on identical data and report final losses of 0.031 and 0.048. Both say the gradient was numerically zero at the end. Who made a mistake?
Neither, necessarily. The loss surface of a neural network is non-convex, so the zero-gradient condition is satisfied at many points of different quality. Different random weight initialisations put the two runs in different basins, and each converged correctly to its own local minimum.
What this does tell you: a single training run is not evidence about the best achievable loss, reported numbers should come with a seed and preferably several runs, and if you needed reproducibility you needed to fix the seed. If instead the loss had been convex — a linear or logistic regression — then two different answers would imply that one run had a bug or had not converged.
P1.2.4 (synthesis) — Using the Hessian formula from Worked 1.2, explain what happens to the shape of the MSE bowl if all five students had practised for 3 hours each, and connect this to P1.1.4.
With every xᵢ = 3: Σxᵢ = 15 still, and Σxᵢ² = 5(9) = 45. So H = (2/5)[[5, 15], [15, 45]] = [[2, 6], [6, 18]], and the determinant is 2(18) − 36 = 0.
Determinant zero means positive semi-definite but not positive definite: the bowl has become a parabolic trough with a perfectly flat floor. Still convex, so descent still works and still finds a minimum — but not a unique one. Every parameter pair along the floor achieves the same loss. This is the same degeneracy P1.1.4 found algebraically as a singular AᵀA, seen now as geometry: rank deficiency in the data is a flat direction in the loss surface.
Loss Functions and Their Minimisation
"Least wrong" is not a definition until you say how wrongness is measured. Change the measure and the answer changes with it.
The question
Section 1.1 minimised squared error without ever justifying the square. Why not the absolute error? Why not the largest single error? Each choice is a different definition of a good model, and each one produces a different fitted line from the same five students.
The loss function is where you tell the algorithm what you care about. It is the single most consequential modelling decision in this unit, and it is the one usually made by copying whatever the tutorial used.
The intuition
Think of a loss as a fine charged per mistake. A flat fine of ₹100 per wrong prediction, regardless of size, treats a near miss and a wild miss alike. A fine proportional to the size of the miss treats a 4-mark error as four times as bad as a 1-mark error. A fine proportional to the square of the miss treats it as sixteen times as bad.
That last choice has a consequence worth seeing before any formula. Squaring makes the model terrified of large errors, so it will accept several small errors to avoid one big one. If a big error is a genuine emergency — a bridge load estimate — that is exactly right. If it is a typo in the data, the model will contort itself to accommodate a value that was never real.
The formal treatment
Three words that exams use interchangeably and this chapter does not:
| Term | Applies to | Symbol used here |
|---|---|---|
| Loss | One training example | L(yᵢ, ŷᵢ) |
| Cost | The average over the whole training set | J(θ) |
| Objective | Cost plus anything else being optimised, such as a regularization penalty (1.7) | J(θ) + λR(θ) |
Regression losses
MSE is differentiable everywhere and strictly convex, which is why closed forms exist for it. MAE is convex but has a kink at r = 0 where the derivative jumps from −1 to +1, so gradient methods need a subgradient and the optimum can be non-unique. Huber loss is the compromise: squared near zero so it is smooth, linear far out so a single outlier cannot dominate. The threshold δ is a hyperparameter.
Classification losses
The 0–1 loss is what you are actually graded on and it is useless for training: its gradient is zero wherever it is defined and undefined where it is not, so there is no downhill direction. Every practical classification loss is a smooth, convex surrogate for it. Log loss is the standard surrogate because it is convex in the model's linear score and because it punishes confident mistakes without limit — predicting 0.001 for a true positive costs 6.91, while predicting 0.4 costs 0.92.
Depth — losses are not arbitrary, they are likelihoods
Assume the observed target is the model's prediction plus Gaussian noise. Write down the probability of the whole dataset under that assumption, take the logarithm, and drop constants: what remains is −Σrᵢ². Maximising likelihood is therefore identical to minimising MSE. Assume instead that the label is a Bernoulli draw with probability p, and the same procedure yields log loss exactly.
So MSE encodes a belief that errors are symmetric, additive and Gaussian; log loss encodes a belief that outcomes are coin flips with a modelled bias. Choosing a loss is choosing a noise model, whether or not you meant to. This is the Maximum Likelihood Estimation from the bridge topics, arriving with a different label on it.
Two ways to minimise
Set the gradient to zero and solve algebraically — possible only for a few losses and model families, as in 1.1. Or start somewhere and iterate downhill, which needs only that the loss be differentiable. That second route is section 1.4 and is how essentially every model past linear regression is trained.
The worked example
Worked 1.3a — score the fitted line four ways
metrics on the spineŷ = 1.1 + 1.3x, compute MSE, RMSE, MAE and R².| Student | y | ŷ | r = ŷ − y | r² | |r| | (y − ̄y)² |
|---|---|---|---|---|---|---|
| A | 2 | 2.4 | +0.4 | 0.16 | 0.4 | 9 |
| B | 4 | 3.7 | −0.3 | 0.09 | 0.3 | 1 |
| C | 5 | 5.0 | 0.0 | 0.00 | 0.0 | 0 |
| D | 7 | 6.3 | −0.7 | 0.49 | 0.7 | 4 |
| E | 7 | 7.6 | +0.6 | 0.36 | 0.6 | 4 |
| Σ | 25 | 25.0 | 0.0 | 1.10 | 2.0 | 18 |
Note the sign convention: r = ŷ − y throughout this chapter. Many textbooks use y − ŷ; every squared quantity is identical either way, but the sign of the gradient flips, so mixing the two mid-derivation is a classic error.
RMSE > MAE always, and the gap grows with the spread of errors. The model explains 93.9% of the variation in marks.
SST here is 18, the total squared deviation of marks from their mean. R² compares your model against the laziest possible one — always predicting 5 — which would score MSE = 18/5 = 3.6.
Worked 1.3b — one typo, two losses
robustnessNew ̄y = (2+4+5+7+17)/5 = 7. Recompute Sₓₕ = Σ(xᵢ−̄x)(yᵢ−̄y):
MAE has no closed form; searching the parameter plane gives the minimum at about w₀ = 0, w₁ = 2.0 with MAE 1.80. Before the typo, an MAE-optimal line was roughly w₀ = 0.52, w₁ = 1.50.
under MSE 1.30 → 3.30 (Δ = 2.00, and the intercept goes negative — the model now predicts −2.9 marks for a student who practises nothing)
under MAE 1.50 → 2.00 (Δ = 0.50)
MSE let a single row move the slope by more than the original slope's own value. That is the price of squaring. The price of MAE, visible here, is that its optimum is not unique — several different lines achieve MAE = 0.40 on the clean data, including the MSE line.
A log-loss calculation, since Unit 2 needs it
Treat the same students as a classification problem: predict pass. Suppose a model outputs the score z = −3 + 1.2x and converts it to a probability with the sigmoid p = 1/(1 + e⁻ᶻ) from section 1.8.
| Student | x | z | p = P(pass) | true y | loss |
|---|---|---|---|---|---|
| A | 1 | −1.8 | 0.1419 | 0 | 0.1530 |
| B | 2 | −0.6 | 0.3543 | 0 | 0.4375 |
| C | 3 | +0.6 | 0.6457 | 1 | 0.4375 |
| D | 4 | +1.8 | 0.8581 | 1 | 0.1530 |
| E | 5 | +3.0 | 0.9526 | 1 | 0.0486 |
| mean log loss | 0.2459 | ||||
Only the probability assigned to the true class enters each row: for A the loss is −ln(1 − 0.1419) = 0.1530, for C it is −ln(0.6457) = 0.4375. All five students are classified correctly at a 0.5 threshold, so the 0–1 loss is 0 and accuracy is 100% — yet log loss is 0.2459, not 0. Log loss keeps grading confidence after accuracy has stopped noticing, which is why it is the training loss and accuracy is the reporting metric.
The visualization
What each loss charges for a miss
penalty curvesThe pitfalls
Where marks are lost
- Training on one thing, being graded on another, without noticing. Minimising MSE while the deliverable is ranked accuracy is a mismatch you must at least be able to name.
- Reporting MSE and calling it an error in the original units. MSE is in squared units. Only RMSE and MAE are comparable to the target values themselves.
- Using MSE on probabilities for classification. It is possible — here it gives 0.0587 — but it is not convex in the parameters of a logistic model and it saturates: a confidently wrong prediction produces a nearly zero gradient, so the model stops correcting exactly when it is most wrong.
- Comparing losses across differently scaled targets. An MSE of 0.22 on marks out of 10 and an MSE of 0.22 on marks out of 100 are not the same quality of fit. Normalise, or use R².
- Assuming a lower training loss is a better model. Section 1.6 is entirely about why this is false.
- Taking log of zero. A model that outputs exactly 0 or 1 makes log loss infinite. Implementations clip probabilities to a range such as
[10⁻¹⁵, 1 − 10⁻¹⁵], and if you write it from scratch, you must too.
Practice
P1.3.1 (direct) — A model predicts probabilities 0.8, 0.3, 0.6 for three samples whose true labels are 1, 0, 0. Compute the mean log loss and the accuracy at threshold 0.5.
At threshold 0.5 the predictions are 1, 0, 1 against truth 1, 0, 0, so two of three are correct: accuracy = 0.6667. The third sample carries 61% of the total loss on its own — log loss localises blame, accuracy does not.
P1.3.2 (variation) — For a single residual, write the derivative of squared loss, absolute loss and Huber loss with δ = 1. Evaluate each at r = 0.5 and r = 5, and explain what the four numbers imply about outliers.
The gradient is what actually moves the parameters, so it is the honest measure of a sample's influence. Under squared loss the outlier pushes ten times as hard as the small error; under absolute and Huber loss it pushes exactly as hard as any other wrong sample. Huber is smooth at the origin (derivative r, going to 0) where absolute loss is not, which is why it is preferred when gradients are needed.
P1.3.3 (interpretation) — Model P has accuracy 0.90 and log loss 0.62. Model Q has accuracy 0.88 and log loss 0.21. Which would you deploy, and what does the pair of numbers tell you about each?
P gets more labels right but is badly calibrated: a log loss of 0.62 with 90% accuracy means it is either hedging near 0.5 on most samples or occasionally very confident and very wrong. Q gets slightly fewer labels right but its probabilities are trustworthy.
The decision depends on how the output is used. If a human or a downstream system consumes the probability — risk scoring, triage, expected-cost decisions, or a threshold that will be tuned later — deploy Q, because its numbers mean something. If the output is a hard label and every error costs the same, deploy P. What you cannot do is declare a winner from accuracy alone; that is why the syllabus asks for both.
P1.3.4 (synthesis) — Using section 1.2, explain why the 0–1 loss is not merely inconvenient for gradient descent but formally unusable, and why log loss is a good replacement.
The 0–1 loss is a step function of the model's score. Its derivative is 0 everywhere except at the decision threshold, where it does not exist. A gradient of zero carries no direction, so the update rule of 1.4 cannot move at all. It is also non-convex, so even a search method that ignored gradients would face the multiple-minima problem of 1.2.
Log loss fixes both: it is differentiable everywhere on (0,1), and it is convex in the linear score, so section 1.2's theorem applies and any local minimum is global. It also upper-bounds the 0–1 loss, so driving log loss down cannot leave accuracy behind. That combination — smooth, convex, and a bound on the thing you actually care about — is what "surrogate loss" means.
Gradient and Gradient Descent
Batch and stochastic. The algorithm that trains everything in Units 2 to 6, in three lines of arithmetic repeated a few thousand times.
The question
Section 1.1 solved for the best line exactly, using a matrix inverse. That route closes the moment the model stops being linear in its parameters — no closed form exists for logistic regression, for an SVM, or for any neural network. What replaces it?
The intuition
You are on a hillside in thick fog and want to reach the valley floor. You cannot see the valley. But you can feel the slope under your feet, so you take a step in the steepest downhill direction, then feel again, and repeat.
Two decisions control everything. How do you measure the slope — carefully, by testing the ground all around you (expensive, accurate), or roughly, by one quick prod with a stick (cheap, noisy)? That is batch versus stochastic. And how big a step do you take? Too small and night falls before you arrive; too big and you stride straight over the valley and up the far slope. That is the learning rate, and it is the hyperparameter most likely to be the reason a model "does not work".
The formal treatment
For a function of several variables, the partial derivative ∂J/∂θⱼ is the rate of change of J when you nudge only θⱼ and hold the rest fixed. The gradient ∇J collects them into a vector.
Two properties justify the minus sign. The gradient points in the direction of steepest increase, and its magnitude is the rate of increase in that direction. So −∇J is steepest decrease, and for a small enough η the step is guaranteed to reduce J unless the gradient is already zero.
The gradient of MSE, derived
This derivation is examinable and worth being able to reproduce from nothing.
Setting that to zero recovers AᵀAθ = Aᵀy — the normal equations of 1.1. Closed form and gradient descent are not two methods for two problems; they are two routes to the same stationary point.
Batch, stochastic, mini-batch
| Variant | Samples per update | Cost per update | Behaviour |
|---|---|---|---|
| Batch GD | all n | O(nd) | Exact gradient, smooth monotone descent for small η, one update per pass over the data. Unusable when n is millions. |
| Stochastic GD | 1 | O(d) | Noisy gradient, jittery path, n updates per pass. Fast early progress; never fully settles, so the learning rate is usually decayed. |
| Mini-batch GD | B, typically 32–512 | O(Bd) | The practical default. Noise averaged down by √B, and B samples vectorise onto a GPU at nearly the cost of one. |
One epoch is one full pass over the training data. Batch GD performs one update per epoch; SGD performs n. Comparing "100 iterations of batch" with "100 iterations of SGD" compares 100 passes with one fifth of a pass on this data — a mistake that makes SGD look far worse than it is.
Depth — how large can η be?
For a quadratic cost with Hessian H, batch gradient descent converges if and only if 0 < η < 2/λₘₖₓ, where λₘₖₓ is the largest eigenvalue of H. For the spine, H = [[2, 6], [6, 22]] has eigenvalues 0.3381 and 23.6619, so the limit is η < 2/23.6619 = 0.0845. The widget below crosses that line at η = 0.09, and the loss then grows without bound.
The ratio λₘₖₓ/λₘₛₙ = 69.99 is the condition number. It says the bowl is 70 times steeper across than along, so the largest safe step is set by the steep direction while the distance to travel is set by the shallow one — producing the zig-zag you will see in the widget. Feature scaling reduces the condition number, and that is its whole purpose. Unit 4's momentum and Adam attack the same problem.
The worked example
Worked 1.4a — batch gradient descent by hand, η = 0.02
3 iterations shownw₀ = 0, w₁ = 0 and run batch gradient descent on the spine's MSE. Show every intermediate value.With both parameters zero, every prediction is 0, so rᵢ = −yᵢ.
Both gradients are negative, so both parameters increase. That is the algorithm noticing that predicting zero marks for everyone is too low.
| k | w₀ | w₁ | J | ∂J/∂w₀ | ∂J/∂w₁ |
|---|---|---|---|---|---|
| 0 | 0.0000 | 0.0000 | 28.6000 | −10.000 | −35.200 |
| 1 | 0.2000 | 0.7040 | 8.1558 | −5.376 | −18.512 |
| 2 | 0.3075 | 1.0742 | 2.4821 | −2.940 | −9.722 |
| 3 | 0.3663 | 1.2687 | 0.9070 | −1.655 | −5.091 |
| 4 | 0.3994 | 1.3705 | 0.4691 | −0.978 | −2.653 |
| 5 | 0.4190 | 1.4235 | 0.3469 | −0.621 | −1.368 |
| 8 | 0.4467 | 1.4715 | 0.2981 | −0.278 | −0.148 |
| ∞ | 1.1000 | 1.3000 | 0.2200 | 0.000 | 0.000 |
By step 8 the slope is nearly right at 1.4715 but the intercept is still stuck at 0.4467 on its way to 1.1000. The intercept's gradient has barely shrunk while the slope's has collapsed — the condition number of 70, in action.
Worked 1.4b — one epoch of stochastic gradient descent
same η, same startη = 0.02 from (0, 0). Compare with one batch iteration.Drop the sum and the 1/n: for a single sample, ∂L/∂w₀ = 2rᵢ and ∂L/∂w₁ = 2rᵢxᵢ. Every update uses the parameters left behind by the previous student, which is what makes progress within an epoch possible.
| Visit | xᵢ | yᵢ | ŷᵢ | rᵢ | 2rᵢ | 2rᵢxᵢ | w₀ after | w₁ after |
|---|---|---|---|---|---|---|---|---|
| A | 1 | 2 | 0.0000 | −2.0000 | −4.000 | −4.000 | 0.0800 | 0.0800 |
| B | 2 | 4 | 0.2400 | −3.7600 | −7.520 | −15.040 | 0.2304 | 0.3808 |
| C | 3 | 5 | 1.3728 | −3.6272 | −7.254 | −21.763 | 0.3755 | 0.8161 |
| D | 4 | 7 | 3.6397 | −3.3603 | −6.721 | −26.882 | 0.5099 | 1.3537 |
| E | 5 | 7 | 7.2784 | +0.2784 | +0.557 | +2.784 | 0.4988 | 1.2980 |
Student E is the interesting row. By the time SGD reaches E, the parameters learned from A–D already overshoot E: predicted 7.2784 against an actual 7. So E's update pushes both parameters back down. That sign flip is the noise in stochastic gradient descent, and it is also its escape mechanism on non-convex surfaces.
SGD (0.4988, 1.2980) J = 0.5887
Batch (0.2000, 0.7040) J = 8.1558
Same data touched once, same learning rate. SGD is 13.9× lower in loss, because it got five updates out of the pass instead of one.
Batch would need about 5 epochs to reach where SGD is after 1. On five rows this is a curiosity; on five million rows it is the difference between a model that trains and one that does not.
The visualization
Descent on the spine's loss surface
interactive — step it yourselfParameter space — the path
Loss against update count
The widget opens at η = 0.020 from the origin, so the first press of Step must reproduce Worked 1.4a exactly: (0.200, 0.704) with J = 8.156. Push η to 0.060 to see the zig-zag, and to 0.090 — past the 2/λₘₖₓ limit of 0.0845 — to watch it diverge.
The pitfalls
Where marks are lost
- Losing the factor
2/n. A gradient that is 2/5 of the right size is not wrong in direction, so the run still converges — just at a different effective learning rate than you think. In an exam, the missing constant is the mark. - Updating
w₀and then using the neww₀to compute∂J/∂w₁. In batch GD both partials are evaluated at the same old parameter vector, then both are updated. Doing it sequentially is a different algorithm. - Blaming the model for a learning-rate failure. A loss that rises, oscillates, or becomes
NaNis almost alwaysηtoo large. A loss that barely moves isηtoo small. Neither is evidence about the model. - Not scaling features. With one feature in the range 1–5 and another in 10000–50000, the condition number explodes and no single
ηsuits both directions. Standardising is not cosmetic; it changes what is optimisable. - Confusing epochs with iterations. Always state which. See the SGD table above for how large the difference is.
- Expecting SGD's loss curve to fall monotonically. It should not. Judge SGD on the running average, or on loss measured once per epoch.
- Using the loss value instead of the gradient in the update.
θ ← θ − ηJis dimensionally meaningless. The update needs the derivative.
Practice
P1.4.1 (direct) — Minimise f(w) = (w − 3)² + 2 by gradient descent from w = 0 with η = 0.1. Give four iterations, and state the exact minimiser.
f′(w) = 2(w − 3). Update: w ← w − 0.1 · 2(w − 3) = 0.8w + 0.6.
Exact minimiser w* = 3, f(3) = 2. The error shrinks by a factor 0.8 each step, so it approaches 3 geometrically and never arrives exactly — the normal behaviour of gradient descent on a smooth minimum.
P1.4.2 (variation) — Same function, but try η = 0.5, η = 1.0 and η = 1.1. Classify each behaviour and derive the stability limit.
Convergence needs |1 − 2η| < 1, that is 0 < η < 1. Here f″ = 2, so this is precisely the general rule η < 2/λₘₖₓ. The fastest choice, η = 1/λ = 0.5, jumps to the exact answer in one step — possible only because this is a perfectly circular quadratic; the spine's bowl is elongated and no single η can do that.
P1.4.3 (interpretation) — A training log shows the loss falling for 40 epochs, then jumping to NaN at epoch 41. Give the two most likely causes and how you would separate them.
Cause 1 — learning rate too large for a region newly entered. As parameters grow, gradients can grow with them; one oversized step throws the parameters far out, the next gradient is larger still, and two or three steps later the numbers overflow. Test: reduce η by 10× and rerun from the same seed. If the run survives past epoch 41, this was it. Standard fixes are a smaller η, a decay schedule, or gradient clipping.
Cause 2 — an undefined arithmetic operation in the loss. A log of zero, a division by a variance that has collapsed, or a square root of a negative number. This one does not care about η. Test: rerun with the reduced η and, if it still fails, print the loss inputs at the failing step. Clipping probabilities away from 0 and 1 is the fix.
Separating them costs one training run and is worth doing before changing the model, which is the usual and wrong first response.
P1.4.4 (synthesis) — The spine has a closed-form solution that costs one 2×2 inversion. Under what conditions would you still choose gradient descent, and what does section 1.2 contribute to that answer?
Choose gradient descent when the closed form is unavailable or unaffordable: when the model is non-linear in its parameters and no algebraic solution exists (logistic regression, any neural network); when d is large enough that O(d³) is prohibitive; when n is too large to hold in memory, since SGD needs only one sample at a time; or when the data arrives as a stream and the model must be updated online.
Section 1.2 supplies the guarantee that makes the choice safe here: the MSE cost is strictly convex, so descent cannot converge to anything other than the unique closed-form answer. That equivalence is exactly what disappears in Unit 4, where the surface is non-convex, descent finds one of many minima, and the closed form does not exist to check it against.
Entropy and Information Gain
Measuring uncertainty in bits, so that a machine can decide which question is worth asking first.
The question
Drop the marks and keep only the outcome: A and B failed, C, D and E passed. You are allowed one yes/no question about a student before guessing their result. Which question should you ask?
"Did they practise more than 2 hours?" tells you the answer outright on this data. "Did they attend the lab?" leaves you almost as unsure as before. To automate that comparison you need to measure "how unsure am I" as a number, and that number is entropy. Decision trees in Unit 2 are nothing but this comparison, repeated.
The intuition
Consider three bags of coloured balls. The first is all red: draw one and you knew in advance what you would get, so there is no uncertainty and learning the colour tells you nothing new. The second is half red and half blue: maximum uncertainty, and learning the colour is genuinely informative. The third is 90% red: you would bet red, and you would usually be right, so there is uncertainty but not much.
Entropy puts a number on that scale — 0 bits for the pure bag, 1 bit for the fifty-fifty bag, 0.469 bits for the 90-10 bag. One bit is exactly the information in one fair coin flip, which is what makes the unit intuitive.
The second idea is just as simple. Asking a question splits your group into two smaller groups. Compute the uncertainty of each smaller group, average them by size, and see how much the uncertainty dropped. That drop is the information gain, and the best question is the one with the largest drop.
The formal treatment
Four properties are worth knowing by name. Entropy is never negative. It is 0 exactly when one class has all the probability — a pure node. It is maximal, equal to log₂k, when all k classes are equally likely. And it does not depend on which class is which, only on the proportions, so a 30/70 split and a 70/30 split have identical entropy.
The weights |Sᵥ|/|S| matter and are the most commonly dropped part of the formula. A branch holding one sample out of a hundred is pure by luck; weighting stops that purity from counting for much.
Gini impurity, the alternative
Gini is the probability that two samples drawn at random from the node have different labels. It needs no logarithm, so it is cheaper, and in practice it selects nearly the same splits as entropy. CART uses Gini, ID3 and C4.5 use information gain. Where they disagree, entropy is slightly more willing to create small pure branches.
Depth — why base 2, and why the log at all
Information should be additive: learning two independent facts should give the total of their individual information. Probabilities of independent events multiply, and the only function turning multiplication into addition is the logarithm — hence −log p as the surprise of a single outcome, and entropy as its average. Base 2 makes the unit the bit; natural log gives nats, and since log₂x = ln x / ln 2, every entropy in nats is 0.693 of the same entropy in bits. Comparisons are unaffected, absolute values are not, so state your base.
Cross-entropy from section 1.3 is the same quantity with two distributions: −Σp log q, the average surprise of the truth p under your model q. Minimising log loss is minimising cross-entropy. One idea, two syllabus sections.
The worked example
Worked 1.5 — choose the root split for a decision tree
five candidate questionshours plus the binary attribute attended lab, and pick the root split.2 fails and 3 passes out of 5, so p(fail) = 0.4 and p(pass) = 0.6.
Close to the maximum of 1 bit, as expected for an almost balanced group.
For a numeric attribute the candidates are the midpoints between consecutive distinct values: 1.5, 2.5, 3.5, 4.5. Work one out fully, then read the rest from the table.
Take hours ≤ 3.5. Left branch: A, B, C → fail, fail, pass. Right branch: D, E → pass, pass.
| Question | Left (fail/pass) | Hₗ | Right (fail/pass) | Hₕ | weighted H | IG | Gini gain |
|---|---|---|---|---|---|---|---|
| hours ≤ 1.5 | 1 / 0 | 0.0000 | 1 / 3 | 0.8113 | 0.6490 | 0.3219 | 0.1800 |
| hours ≤ 2.5 | 2 / 0 | 0.0000 | 0 / 3 | 0.0000 | 0.0000 | 0.9710 | 0.4800 |
| hours ≤ 3.5 | 2 / 1 | 0.9183 | 0 / 2 | 0.0000 | 0.5510 | 0.4200 | 0.2133 |
| hours ≤ 4.5 | 2 / 2 | 1.0000 | 0 / 1 | 0.0000 | 0.8000 | 0.1710 | 0.0800 |
| attended lab | 1 / 2 | 0.9183 | 1 / 1 | 1.0000 | 0.9510 | 0.0200 | 0.0133 |
Both branches are pure, so the tree is finished after one question and the training accuracy is 100%.
attended lab gains 0.0200 bits: it looks like a plausible feature and is almost worthless here.
Notice the shape of the IG column. It peaks at the threshold that matches the real structure and falls away on either side, which is why exhaustive threshold search works. Also notice that hours ≤ 1.5 produces a pure left branch yet gains only 0.3219 bits, because that pure branch holds one student out of five. Purity without weight is not information.
The Gini gain column ranks the five candidates in exactly the same order. That is typical, and it is why the choice between the two impurity measures is rarely the reason a tree performs badly.
The visualization
Uncertainty as a function of the class balance
the entropy curveSplit explorer
interactive — pick the questionThe pitfalls
Where marks are lost
- Averaging the branch entropies without weights. For
hours ≤ 1.5the unweighted average is(0 + 0.8113)/2 = 0.4057, giving a fictitious gain of 0.5653 that would beat the correct answer. Always weight by branch size. - Computing the entropy of the feature instead of the label. Entropy in this section is always over the class distribution inside a node. The spread of
hoursitself is irrelevant. - Rewarding features with many distinct values. A student ID number splits five students into five pure branches and gains the full 0.9710 bits, while predicting nothing about anyone new. C4.5 divides by the split information — the entropy of the branch sizes, here
log₂5 = 2.3219bits — giving a gain ratio of 0.4182 against 0.9710 for the honest split. This is the standard exam question on gain ratio. - Mixing bits and nats. Using
lngives 0.6730 instead of 0.9710 for the root. Not wrong, but not bits. - Assuming IG can be negative. It cannot. If you get a negative number, the weighting or the parent entropy is wrong.
- Reading 100% training accuracy as success. One question separated five students perfectly. Section 1.6 explains why that is not a reason to be pleased.
Practice
P1.5.1 (direct) — A node holds 8 samples: 5 positive, 3 negative. Compute its entropy and Gini impurity.
P1.5.2 (variation) — That node can be split two ways. Split A gives branches of (3 pos, 0 neg) and (2 pos, 3 neg). Split B gives (4 pos, 1 neg) and (1 pos, 2 neg). Which is better?
Split A wins, more than twice over. It isolates three samples with complete certainty, and even though its other branch is left almost maximally impure, that impurity is cheaper than B's two mediocre branches. A greedy tree takes A and continues working on the impure branch — which is exactly how trees grow.
P1.5.3 (interpretation) — A tree's root split reports IG = 0.0034 bits, the best of 40 candidate features. What are you being told, and what would you do?
No single feature carries usable information about the label on this data. Three explanations to separate: the label may genuinely not be predictable from these features; the signal may be there but only in combinations of features, which a single-feature greedy split cannot see (parity and XOR-like structure are the standard example, where every individual feature has zero gain and a pair has full gain); or the target may be so imbalanced that the parent entropy is tiny to begin with, leaving nothing to gain.
Actions in order of cost: check the parent entropy to rule out the third case; engineer interaction or ratio features to attack the second; try a model that is not built from axis-aligned single-feature splits. Growing the tree deeper is the one thing that will not help — it will fit noise, which is section 1.6.
P1.5.4 (synthesis) — Connect this section to 1.3: state precisely how entropy, cross-entropy and log loss relate, using the root node of the spine as the example.
Entropy is the average surprise of a distribution under itself: H(p) = −Σp log p. Cross-entropy is the average surprise of the true distribution p under a model q: H(p, q) = −Σp log q. It is never smaller than H(p), and their difference is the KL divergence — the avoidable part of your surprise, caused purely by q being wrong.
At the spine's root, a model that knows only the class proportions predicts q = 0.6 for every student. Its cross-entropy equals the node's own entropy, 0.9710 bits or 0.6730 nats, and no constant prediction can do better. Log loss from 1.3 is exactly this cross-entropy measured in nats and averaged over samples. So the entropy of a node is the log loss of the best possible constant predictor for that node — which is why a decision tree that reduces entropy is a model that reduces log loss.
Bias and Variance Trade-offs
Why the model that fits your data best is usually not the model you want, and why the failure splits cleanly into two named parts.
The question
A degree-4 polynomial passes exactly through all five students. Its training MSE is 0.0000 — a perfect score by the measure section 1.3 built. Ask it about a student who practised 6 hours and it predicts −3.0 marks.
So a lower training error made the model worse. Any account of learning has to explain that, and the bias–variance decomposition is that account.
The intuition
Think about throwing darts, where the bullseye is the truth and each throw is a model fitted to a different sample of data.
All five darts tightly grouped, but in the top-left corner: consistent and consistently wrong. That is bias — the model is too simple to represent the truth, so no amount of data will centre it. Darts scattered widely all around the bullseye, averaging out to the centre: right on average, unreliable on any single throw. That is variance — the model is flexible enough to chase the particular noise in whichever sample it saw.
The trade-off is that the same knob controls both. Add flexibility and the grouping loosens while the centre improves. Remove it and the grouping tightens while the centre drifts. And under everything sits noise you cannot remove at all, because two students with identical hours can still score differently.
The formal treatment
Fix an input x. Imagine drawing a fresh training set, fitting the model, and predicting at x — then repeating that thousands of times. The prediction ŷ(x) becomes a random variable, and its expected squared error splits into three pieces that cannot interact.
Three consequences. Total error cannot fall below σ², so a reported test MSE of 0 on real data means a leak, not a triumph. Bias and variance are both non-negative, so neither can be traded for a negative amount of the other. And more training data shrinks variance without touching bias — which is why "get more data" fixes an overfitting model and does nothing at all for an underfitting one.
| Training error | Validation error | Diagnosis | What to do |
|---|---|---|---|
| high | high, close to training | Underfitting — high bias | More capacity, better features, less regularization, train longer |
| low | much higher | Overfitting — high variance | More data, more regularization (1.7), fewer features, simpler model, early stopping |
| low | low | Working | Stop. Report on a test set not used for any of these decisions. |
| high | low | Something is wrong | Almost always a bug: leakage into validation, mismatched splits, or regularization applied at training time only |
Depth — where the cross term goes
Expand E[(y − ŷ)²] by inserting E[ŷ] and grouping: the cross term is 2 E[(E[ŷ] − f)(ŷ − E[ŷ])]. The first bracket is a constant once x is fixed, and the second has expectation zero by construction, so the product vanishes. That is the whole derivation, and it is why the three terms are exactly additive rather than approximately so.
The same reasoning explains ensembles from Unit 2. Averaging B independently fitted models leaves bias unchanged — the average of unbiased-ish models is still centred the same way — while dividing variance by up to B. That single line is why random forests work.
The worked example
Worked 1.6a — five polynomials on five students
complexity ladderx = 6, an hour count no student had.| degree | params | fitted model | train MSE | ŷ at x = 6 |
|---|---|---|---|---|
| 0 | 1 | ŷ = 5.0 | 3.6000 | 5.0 |
| 1 | 2 | ŷ = 1.1 + 1.3x | 0.2200 | 8.9 |
| 2 | 3 | ŷ = −0.4 + 2.5857x − 0.2143x² | 0.0914 | 7.4 |
| 3 | 4 | ŷ = 1.0 + 0.6190x + 0.5357x² − 0.0833x³ | 0.0714 | 6.0 |
| 4 | 5 | ŷ = −8.0 + 17.5833x − 9.7917x² + 2.4167x³ − 0.2083x⁴ | 0.0000 | −3.0 |
Training MSE falls at every step and hits exactly zero at degree 4, where the model has five parameters for five data points. With as many parameters as observations, interpolation is guaranteed and training error stops carrying any information at all.
The x = 6 column tells the real story. Degree 0 says 5.0, ignoring the obvious upward trend. Degree 1 says 8.9, a defensible extrapolation. Degree 4 says −3.0, which is not a possible mark. Its coefficients are the giveaway: 17.5833 and −9.7917 are enormous compared with the data they describe, and they nearly cancel inside the observed range while diverging just outside it. Large cancelling coefficients are the fingerprint of overfitting, and section 1.7 attacks them directly.
Prediction at x = 6: 5.0 → 8.9 → 7.4 → 6.0 → −3.0 (falls apart)
Training error is a measure of memorisation. It becomes a measure of learning only when the parameter count is small relative to
n.Worked 1.6b — the decomposition, measured
20 000 simulated training setsf(x) = 1 + 1.6x − 0.1x² with Gaussian noise of standard deviation σ = 0.6 at the same five hour values. Draw 20 000 training sets, fit each degree, and measure bias² and variance directly.| degree | params | bias² | variance | noise σ² | expected test MSE |
|---|---|---|---|---|---|
| 0 | 1 | 2.0280 | 0.0722 | 0.3600 | 2.4602 |
| 1 | 2 | 0.0280 | 0.1435 | 0.3600 | 0.5315 |
| 2 | 3 | 0.0000 | 0.2149 | 0.3600 | 0.5749 |
| 3 | 4 | 0.0000 | 0.2867 | 0.3600 | 0.6467 |
| 4 | 5 | 0.0000 | 0.3592 | 0.3600 | 0.7192 |
Bias collapses once, then stays. Degree 0 cannot represent an upward trend at all, so its bias² is 2.0280 — the dominant term. Degree 1 removes almost all of it. From degree 2 onward the model family contains the truth exactly, so bias² is zero and cannot improve further.
Variance grows in exact proportion to parameter count. The numbers are 0.0722, 0.1435, 0.2149, 0.2867, 0.3592 — each step adds about 0.0718, which is σ²/n = 0.36/5. For linear-in-parameters models the identity is variance = σ²(d+1)/n. Every parameter you add costs a fixed amount of variance, whether or not it earns anything.
The best model is not the true model. The truth is quadratic, yet degree 1 wins on total error, 0.5315 against 0.5749. The straight line accepts a bias² of 0.0280 to save 0.0714 of variance. With n = 5 that trade is worth making; with n = 200 the variance term shrinks by 40× and degree 2 would win comfortably. Optimal complexity is a property of the model and the amount of data, never of the model alone.
The noise floor is 0.3600, so the best achievable model is still wrong by that much and no method in this course can do better.
Degree 4 pays 0.3592 of variance for 0.0000 of bias improvement — pure waste, and the source of the −3.0 prediction above.
The visualization
One dataset, five complexities
interactive — slide the degreeThe pitfalls
Where marks are lost
- Confusing model variance with data variance. "High variance" here means the fitted function moves a lot when the training sample changes. It says nothing about the spread of
y. - Using the test set to choose complexity, then reporting test error. Once the test set has influenced a decision it is a validation set, and the number it reports is optimistic. Keep three splits, or use cross-validation and hold out a final test set.
- Prescribing more data for an underfitting model. Bias is a property of the model family. Ten thousand more students will not teach a horizontal line to slope upward.
- Believing zero training error is achievable only by cheating. It is guaranteed whenever parameters match data points, as at degree 4 here. It is a structural fact, not a signal.
- Treating the decomposition as something you can measure on real data. Bias and variance require many training sets and knowledge of the truth. On real data you observe only their sum, through validation error. The decomposition is a thinking tool.
- Assuming complexity means depth or degree only. Tree depth,
kin k-NN (smallkis high variance), the number of features, the number of training epochs, and the regularization strength of 1.7 all move the same knob.
Practice
P1.6.1 (direct) — A model family has bias² = 0.09, variance = 0.16 and irreducible noise σ² = 0.25. Give the expected test MSE, and the best possible test MSE if the training set were made infinitely large with the family unchanged.
Expected test MSE = 0.09 + 0.16 + 0.25 = 0.50.
Infinite data drives variance to 0 but leaves bias and noise untouched, so the floor for this family is 0.09 + 0.25 = 0.34. To go below 0.34 you must change the model family; to go below 0.25 is impossible. Note that of the 0.50, half is noise — a reminder that a large test error is not automatically a modelling failure.
P1.6.2 (variation) — Using the identity variance = σ²(d+1)/n from Worked 1.6b, find the degree that minimises expected test MSE if the same experiment were run with n = 100 students instead of 5, keeping the bias² column unchanged.
Degree 2 now wins — the true model, recovered once there is enough data to afford its third parameter. This is the formal version of "complex models need more data": variance falls as 1/n while bias does not move, so the optimum migrates toward higher complexity as n grows.
P1.6.3 (interpretation) — Training accuracy 99.4%, validation accuracy 71.2%, and the validation curve was still falling when training stopped. Diagnose, then say what you expect from (a) doubling the data, (b) doubling the model size.
A 28-point gap with training near perfect is textbook high variance: the model has memorised the training set. The still-falling validation curve suggests training was also stopped in a bad place, but the gap is the dominant problem.
(a) Doubling the data should help substantially. Variance scales roughly as 1/n, so the gap should narrow and validation accuracy should rise, with training accuracy falling slightly — a sign that it is working, not breaking.
(b) Doubling model size should make it worse. More parameters means more variance, and bias is clearly not the constraint here since training accuracy is already 99.4%. Cheaper interventions first: regularization (1.7), early stopping, fewer features, or a smaller model.
P1.6.4 (synthesis) — Section 1.5's decision tree achieved 100% training accuracy on the five students with a single split. Analyse that result with this section's vocabulary, and say what would change your assessment.
Zero training error on five samples from a model that searched five candidate splits is weak evidence of anything. The split threshold was chosen using the labels, so training accuracy is optimistically biased by the search itself — the same reason degree 4 achieves zero MSE above.
In decomposition terms, a depth-1 tree on one feature is actually a fairly high-bias model, so the risk here is less about a wildly flexible fit and more about the estimate of its quality being unreliable at n = 5. What would change the assessment: the same split holding up on held-out students, or a stability check — refit on subsets and see whether the threshold stays near 2.5. If the chosen threshold jumps around between 1.5 and 4.5 across resamples, the variance of the structure is high even though each individual tree looks confident. That instability is precisely what random forests average away.
Cost Function Trade-offs and Regularization
Keeping a flexible model and making its worst instincts expensive, rather than removing the flexibility.
The question
The degree-4 fit failed with coefficients of 17.5833 and −9.7917 on data whose values never leave the range 2 to 7. Section 1.6's remedy was to use a simpler model, which throws away capacity you might need elsewhere.
There is a better move. Keep the flexible model, and add a term to the objective that charges for large parameters. The model then uses its flexibility only where the data pays for it.
The intuition
Give the model a budget. It still wants to reduce error, but every unit of parameter magnitude now costs something, so it will only buy a large coefficient if the error reduction is worth the price. Wild cancelling coefficients — a huge positive next to a huge negative — are exactly what a budget kills first, because they cost a great deal and buy accuracy only inside the training range.
The strength of the budget is a single number, λ. At λ = 0 there is no budget and you are back to plain least squares. As λ grows, parameters shrink toward zero, and in the limit the model predicts a constant. Somewhere in between is the setting that generalises best, and finding it is a validation exercise, not an algebra one.
The formal treatment
Excluding the intercept is not a detail. Penalising w₀ would force predictions toward zero rather than toward the mean, so adding a constant to every mark would change the fitted model. Regularization is meant to constrain the model's shape, not its overall level.
Ridge has a closed form
Adding λ to the diagonal does two things at once. It shrinks every coefficient toward zero, and it makes the matrix invertible even when AᵀA is singular — because the smallest eigenvalue rises from 0 to λ. So ridge is simultaneously the cure for overfitting from 1.6 and the cure for the multicollinearity that broke 1.1. Historically it was invented for the second reason.
L1 versus L2, and why only one produces zeros
For a single centred feature, minimising SSE + λ|w| gives a soft threshold:
Ridge gives 13/(10+λ), which approaches zero but never arrives — at λ = 90 it is still 0.1300. Lasso subtracts a constant and therefore reaches zero at a finite λ, and stays there. That is why L1 performs feature selection and L2 does not.
Geometrically: the constraint region for L1 is a diamond with corners on the axes, and the first point of contact between an elliptical error contour and a diamond is usually a corner — a corner has one coordinate equal to zero. The L2 region is a circle, which has no corners.
Depth — three views of the same λ
Constrained optimisation. Minimising J + λ‖w‖² is equivalent to minimising J subject to ‖w‖² ≤ t, with a one-to-one decreasing relationship between λ and the budget t. Large λ is a small budget.
Bayesian. Put a zero-mean Gaussian prior on each weight and find the most probable parameters given the data. The log of the prior contributes −Σwⱼ²/(2τ²), so ridge is maximum-a-posteriori estimation with a Gaussian prior and λ = σ²/τ². A Laplace prior gives lasso. Choosing λ is stating how strongly you believe, before seeing data, that the weights are small.
Bias–variance. λ is the continuous version of 1.6's degree slider. It buys a reduction in variance with an increase in bias, and unlike degree it can be tuned smoothly.
The worked example
Worked 1.7 — ridge on the spine, by hand
coefficient pathλ = 0, 1, 5, 10, 30. Report the parameters, the training MSE, and the value of the full objective.With Sₓₓ = 10 and Sₓₕ = 13 from section 1.1, and the intercept left unpenalised so that the line still passes through the point of means:
The line still passes through (3, 5) — the pivot the unpenalised intercept guarantees — and has rotated flatter about that point. Ridge rotates the line; it does not translate it.
| λ | w₁ | w₀ | train MSE | penalty | objective |
|---|---|---|---|---|---|
| 0 | 1.3000 | 1.1000 | 0.2200 | 0.0000 | 0.2200 |
| 1 | 1.1818 | 1.4545 | 0.2479 | 0.2793 | 0.5273 |
| 2.5 | 1.0400 | 1.8800 | 0.3552 | 0.5408 | 0.8960 |
| 5 | 0.8667 | 2.4000 | 0.5956 | 0.7511 | 1.3467 |
| 10 | 0.6500 | 3.0500 | 1.0650 | 0.8450 | 1.9100 |
| 30 | 0.3250 | 4.0250 | 2.1213 | 0.6338 | 2.7550 |
| 90 | 0.1300 | 4.6100 | 2.9578 | 0.3042 | 3.2620 |
That is not a bug and not a reason to prefer
λ = 0. Ridge deliberately sacrifices training fit; the payoff appears only on data the model has not seen.As
λ → ∞, w₁ → 0 and w₀ → 5 = ̄y: the model degenerates into the degree-0 predictor of section 1.6, with MSE 3.6.Read the penalty column carefully — it rises and then falls, peaking near λ = 10. It is the product of a growing λ and a shrinking w₁², so it must eventually turn over. Only the total objective is guaranteed to behave monotonically in the relevant sense.
How λ is actually chosen
Not by algebra. Split off a validation set, or use k-fold cross-validation, evaluate a grid of λ spaced logarithmically — 0.001, 0.01, 0.1, 1, 10, 100 — and keep the value with the lowest validation error. Logarithmic spacing matters because the difference between 0.001 and 0.01 is as meaningful as that between 10 and 100. This is the grid search of syllabus 2.1, and the spine is too small to run it honestly, which is itself worth knowing.
The visualization
The regularization dial
interactive — sweep λThe fitted line pivots about (3, 5)
Coefficient path
Other ways to spend the same budget
Regularization does not have to be a term in the objective. Anything that restricts effective capacity does the same job, and Unit 4 uses all of these.
Early stopping
Halt training when validation error starts rising. Limits how far parameters can travel from their small initial values, so it behaves like an L2 penalty whose strength depends on when you stop. Cost: needs a validation set and a patience setting.
Dropout
Randomly zero a fraction of units each training step, so no unit can rely on any other. Approximates averaging over an ensemble of thinned networks. Cost: slower convergence; must be switched off at test time.
Data augmentation
Add label-preserving transformations of the training data. Reduces variance by increasing effective n, and encodes real invariances. Cost: domain-specific; a wrong invariance injects bias.
Fewer features
Cheapest of all, and directly reduces the σ²(d+1)/n variance term from 1.6. Cost: discarding a useful feature adds bias you cannot recover.
The pitfalls
Where marks are lost
- Penalising the intercept. Makes the model depend on the arbitrary zero point of the target. Every serious implementation excludes it, and exam solutions should say so explicitly.
- Not standardising features first. A penalty on raw coefficients punishes features measured in small units, because their coefficients must be large to have any effect. Regularization without scaling silently reweights your features by their measurement units.
- Expecting ridge to zero out a coefficient. It shrinks, indefinitely, and never reaches zero. If you want selection, that is L1.
- Choosing
λon the test set.λis a hyperparameter, so it is chosen on validation data. Selecting it on test data makes the reported error optimistic. - Reading rising training error as failure. It is the mechanism working. Only validation error can tell you whether
λis too large. - Using a large
λto fix an underfitting model. Regularization only ever adds bias. If training error is already high,λshould go down, not up. - Applying dropout at test time. Predictions become random. Switch it off, or scale activations accordingly.
Practice
P1.7.1 (direct) — Using the spine, compute the ridge slope and intercept at λ = 15, and the resulting training MSE.
Between the λ = 10 row (1.0650) and the λ = 30 row (2.1213) of the worked table, as it must be. The line still passes through (3, 5).
P1.7.2 (variation) — With lasso instead, at what λ does the slope become exactly zero, and what is the model then? Compare with ridge at the same λ.
The soft threshold gives w₁ = (13 − λ/2)/10, which reaches zero when λ/2 = 13, that is λ = 26. Beyond that it stays exactly 0 and the model is ŷ = 5, the mean — the degree-0 model of 1.6, with MSE 3.6.
Ridge at λ = 26 gives w₁ = 13/36 = 0.3611, still non-zero, with MSE 1.9830. So at identical λ lasso has discarded the feature entirely while ridge is still using it at 28% of its unpenalised strength. With one feature this is merely a curiosity; with 500 features, lasso returning a model that names the 12 that matter is the reason it is used.
P1.7.3 (interpretation) — A cross-validation sweep gives validation MSE 0.91 at λ = 0.01, 0.62 at λ = 1, 0.58 at λ = 10, 0.79 at λ = 100. Training MSE rises across the whole sweep. What do you choose and what does the shape tell you?
Choose λ = 10, the validation minimum. The U-shape is the bias–variance curve of 1.6 traced by a continuous knob: the fall from 0.91 to 0.58 is variance being removed, and the rise to 0.79 is bias taking over.
The shape also says the unpenalised model was overfitting substantially, since a large λ helped so much. Two refinements worth doing: search a finer grid between 1 and 100, because the true optimum lies somewhere in that interval and a factor-of-10 grid cannot locate it precisely; and if 0.58 and 0.62 are within the fold-to-fold noise, prefer the larger λ, since among statistically indistinguishable models the more heavily regularized one is the safer bet.
P1.7.4 (synthesis) — Explain, using 1.1 and 1.6 together, why ridge regression can fit a model with more features than data points while ordinary least squares cannot.
With d + 1 > n the design matrix cannot have full column rank, so AᵀA is singular, its determinant is 0, and section 1.1's inverse does not exist. Infinitely many parameter vectors achieve zero training error, and least squares has no way to prefer one — section 1.2's flat valley floor, in the extreme.
Ridge replaces AᵀA with AᵀA + λI′, which shifts every eigenvalue up by λ and so is invertible for any λ > 0. The penalty acts as a tie-breaker, selecting the minimum-norm solution among the infinitely many perfect fits. In 1.6's terms, the penalty supplies the missing information that the data cannot: a preference for small coefficients, which is a bias, traded against the enormous variance of an unconstrained fit. This is why regularization is not optional in genomics or text models, where d routinely exceeds n by orders of magnitude.
Activation Functions: Which, When and Why
The one non-linear step that separates a neural network from a large linear regression, and the gradient arithmetic that decides which one to use.
The question
Everything so far output a raw number. Two things force a change. A probability must lie in [0, 1], and a raw score does not. And stacking layers must buy you something — which, as the next paragraph shows, it does not unless something non-linear sits between them.
The intuition
Compose two linear maps and you get a linear map. In symbols, with no activation between the layers:
A fifty-layer network with no activations has exactly the representational power of a single linear layer. All the depth in deep learning is bought by the non-linearity between layers, which is why this section exists and why it sits in the mathematical foundation rather than in Unit 4.
The activation is a squash applied element-wise to each unit's weighted sum. The choice matters for one reason above all others: backpropagation multiplies the activation's derivative once per layer, so a derivative that is habitually small makes deep networks untrainable.
The formal treatment
Note that both sigmoid and tanh have derivatives expressible in terms of their own output, which is why implementations cache the forward value and reuse it in the backward pass.
The numbers that decide everything
| z | σ(z) | σ′(z) | tanh(z) | tanh′(z) | ReLU | ReLU′ |
|---|---|---|---|---|---|---|
| −4 | 0.0180 | 0.0177 | −0.9993 | 0.0013 | 0 | 0 |
| −2 | 0.1192 | 0.1050 | −0.9640 | 0.0707 | 0 | 0 |
| −1 | 0.2689 | 0.1966 | −0.7616 | 0.4200 | 0 | 0 |
| 0 | 0.5000 | 0.2500 | 0.0000 | 1.0000 | 0 | undefined |
| 1 | 0.7311 | 0.1966 | 0.7616 | 0.4200 | 1 | 1 |
| 2 | 0.8808 | 0.1050 | 0.9640 | 0.0707 | 2 | 1 |
| 4 | 0.9820 | 0.0177 | 0.9993 | 0.0013 | 4 | 1 |
Read the σ′ column. Its largest value anywhere is 0.25, at z = 0. By z = ±4 it is 0.0177 — the unit is saturated, meaning its output barely responds to its input and its gradient has almost vanished. Backpropagation through k sigmoid layers multiplies k such numbers together:
That is the vanishing gradient problem, and it is why deep sigmoid networks were nearly untrainable before ReLU. ReLU's derivative is exactly 1 for all positive inputs, so it multiplies through any depth without shrinking anything.
Which, when and why
| Function | Use it | Because | Watch for |
|---|---|---|---|
| ReLU | Default for hidden layers of feed-forward and convolutional networks | Derivative is 1 on the positive side, so gradients survive depth. Cheap — a comparison, not an exponential. Produces sparse activations. | Dying ReLU: a unit pushed permanently negative has zero gradient forever and never recovers. Often caused by too large a learning rate. |
| Leaky ReLU | When a trained network shows many dead units | The small negative slope α keeps a gradient path alive for negative inputs. | One more hyperparameter. Gains are usually modest. |
| tanh | Hidden layers of small or recurrent networks | Zero-centred output, so the next layer receives inputs of both signs and converges faster than with sigmoid. Derivative reaches 1. | Still saturates at both ends. Not competitive with ReLU at depth. |
| sigmoid | Output layer for binary classification, and for gates inside LSTM/GRU (Unit 5) | Maps any real number to a valid probability. Pairs exactly with log loss, and the two derivatives combine to give the clean gradient (p − y). | Never as a hidden activation in a deep network: max derivative 0.25, and its output is not zero-centred. |
| softmax | Output layer for multi-class classification | Produces a probability distribution over k classes that sums to 1, and pairs with categorical cross-entropy. | Only in the output layer, only once. Shift-invariant, so implementations subtract the maximum before exponentiating. |
| identity | Output layer for regression | The target is an unbounded real number, so squashing it would cap what the model can predict. | Using ReLU here silently forbids negative predictions. |
Depth — why sigmoid plus log loss is so clean
With p = σ(z) and L = −[y ln p + (1−y) ln(1−p)], the chain rule gives ∂L/∂z = (p − y) — the saturating factor σ′(z) in the chain is cancelled exactly by the 1/p(1−p) coming out of the logarithm. So a confidently wrong output still produces a large gradient, and learning does not stall.
Replace log loss with MSE and that cancellation is lost: ∂L/∂z = 2(p − y)σ′(z), which goes to zero when the unit is saturated. A confidently wrong prediction then produces almost no gradient. This is the precise reason section 1.3 warned against MSE on probabilities, and it only becomes visible once activations are on the table.
The worked example
Worked 1.8 — one forward pass and one gradient, by hand
two-unit layerz = −3 + 1.2x and applies a sigmoid to predict pass. Compute the output, the log loss, and ∂L/∂w₁. Then repeat with tanh and with ReLU to compare the gradient that reaches the weight.Use the cancellation from the depth box: ∂L/∂z = p − y.
Negative, so w₁ increases — the unit becomes more confident that longer practice means passing. Exactly what it should conclude from D.
Both saturating functions have already lost about 90% of the gradient at z = 1.8, which is not even a large input. ReLU loses none.
z = 1.8, p = 0.8581, L = 0.1530, ∂L/∂w₁ = −0.5676Activation derivative at the same z: sigmoid 0.1218, tanh 0.1036, ReLU 1.0000
Through five such layers the sigmoid path would multiply to
0.1218⁵ = 2.68 × 10⁻⁵; the ReLU path stays at 1.A softmax calculation
Three-class scores z = [2, 1, −1]:
Shift invariance is why libraries subtract max(z) before exponentiating: it cannot change the answer and it prevents eᶻ overflowing for large scores.
The visualization
Activation and its derivative
interactive — the derivative is the pointThe pitfalls
Where marks are lost
- Sigmoid in hidden layers of a deep network. The single most common cause of a network that trains to a mediocre plateau and stops. Use ReLU and keep sigmoid for the output.
- ReLU on the output of a regression that can go negative. The model becomes structurally incapable of predicting below zero, and you will read it as underfitting.
- Softmax with one output unit. A softmax over a single value returns 1.0 always. Binary classification needs one unit with sigmoid, or two units with softmax — not one with softmax.
- Applying softmax and then a cross-entropy that applies it again. Most libraries fuse the two for numerical stability, so passing already-normalised probabilities into a function expecting raw scores double-applies it and quietly flattens your predictions.
- Claiming ReLU is differentiable at 0. It is not. Implementations pick a subgradient, conventionally 0. Say "subgradient" and the mark is yours.
- Thinking ReLU cannot vanish. Its gradient is exactly 0 for negative inputs, which is worse than small — a dead unit has no path back to life. Leaky ReLU exists for this.
- Adding an activation without checking the output range. tanh on a target in
[0, 10]caps predictions at 1 no matter how well the network trains.
Practice
P1.8.1 (direct) — A unit computes z = 0.5x₁ − 2x₂ + 1 with input x = (4, 1). Give its output and derivative under sigmoid, tanh and ReLU.
tanh's derivative is 2.14× sigmoid's at the same input, which is the entire reason tanh was preferred over sigmoid for hidden layers before ReLU.
P1.8.2 (variation) — The same unit now receives x = (20, 1). Recompute, and state what has gone wrong under each activation.
Under both saturating activations this input contributes essentially no gradient: the unit is certain, and a certain unit cannot learn. Nothing is wrong with the activation — the problem is that x₁ = 20 is on a scale the weights were not initialised for. The two standard fixes are to standardise the inputs and to use an initialisation that keeps pre-activations near zero, which is exactly the initialisation topic of syllabus 4.7. ReLU is unaffected here, but the same unscaled feature will make its learning rate impossible to tune.
P1.8.3 (interpretation) — After training a ReLU network, 40% of the units in layer 3 output exactly 0 for every sample in the training set. Is this a problem?
Yes, and it is the dying ReLU. A unit outputting 0 for all inputs has zero gradient for all inputs, so it will never update again — 40% of that layer's capacity is permanently gone, and the effective network is much smaller than the one you specified.
The usual cause is a learning rate large enough that one update drove the bias strongly negative. Fixes in order: reduce the learning rate, switch that layer to leaky ReLU or ELU so a gradient path survives, check the initialisation, and check for unscaled inputs producing huge pre-activations.
The distinction that earns marks: sparse activation, where different units fire for different samples, is a benefit of ReLU. Dead units, silent for every sample, are a loss of capacity. The diagnostic is per-unit, across samples, not per-sample.
P1.8.4 (synthesis) — Using 1.2 and 1.4, explain why introducing any non-linear activation changes what section 1.2 can promise, and what practical consequence follows.
Sections 1.1 to 1.4 relied on the model being linear in its parameters, which made the MSE a quadratic form with a constant positive-definite Hessian — strictly convex, one global minimum, gradient descent guaranteed to find it. An activation composes parameters through a non-linear function, and the loss as a function of the parameters is then no longer quadratic. Its Hessian varies from point to point and is generally indefinite.
So section 1.2's theorem no longer applies: zero gradient no longer means global optimum, and different initialisations reach different solutions of different quality. Practical consequences: the random seed becomes part of the experimental record; multiple restarts or a good initialisation scheme become necessary; a single run is not evidence about the best achievable loss; and there is no closed form to check the optimiser against, so bugs in the gradient must be caught by numerical gradient checking instead. Every one of these is a cost paid for the representational power that the non-linearity bought — and Unit 4 is the engineering built to manage that cost.
Cheat Sheet
Everything in Unit 1 that is worth having in front of you the night before. Every number here comes from the five students.
1.1 Normal equations
AᵀAθ = Aᵀy
2×2 form:
n w₀ + Σx w₁ = Σy
Σx w₀ + Σx² w₁ = Σxy
Line always passes through (̄x, ̄y).
Invertible ⇔ features linearly independent.
Spine: 5,15,25 / 15,55,88 → (1.1, 1.3)
1.2 Convexity
Chord test: f(λu+(1−λ)v) ≤ λf(u)+(1−λ)f(v)
2×2 positive definite ⇔ a > 0 and ac − b² > 0
Convex → local min IS global min.
Spine Hessian [[2,6],[6,22]], det 8.
MSE, log loss: convex. Neural nets: not.
1.3 Losses
MSE = (1/n)Σr² · RMSE = √MSE
MAE = (1/n)Σ|r| · RMSE ≥ MAE always
R² = 1 − SSE/SST
log loss = −[y ln p + (1−y) ln(1−p)]
Huber: squared inside δ, linear outside.
Spine: MSE 0.22, RMSE 0.4690, MAE 0.40, R² 0.9389
1.4 Gradient descent
θ ← θ − η∇J
∂J/∂w₀ = (2/n)Σrᵢ
∂J/∂w₁ = (2/n)Σrᵢxᵢ
Matrix: ∇J = (2/n)Aᵀ(Aθ−y)
Converges ⇔ η < 2/λₘₖₓ (spine: 0.0845)
1 epoch = 1 pass. Batch 1 update, SGD n updates.
1.5 Entropy
H = −Σpᵢ log₂ pᵢ bits
Gini = 1 − Σpᵢ²
IG = H(S) − Σ(|Sᵥ|/|S|)H(Sᵥ)
H = 0 pure · H = 1 at 50/50 · max log₂k
Gain ratio = IG / split information
Spine root: H = 0.9710, best IG = 0.9710 at hours ≤ 2.5
1.6 Bias & variance
E[err] = bias² + variance + σ²
Linear models: variance = σ²(d+1)/n
High bias: train high, val high → more capacity
High variance: train low, val high → more data, more λ
More data cuts variance only, never bias.
Spine: best degree 1, test MSE 0.5315, floor 0.36
1.7 Regularization
min J(θ) + λR(θ), intercept excluded
L2 ridge R = Σw² → shrinks, never zeroes
L1 lasso R = Σ|w| → exact zeros, selection
Ridge closed form (AᵀA + λI′)θ = Aᵀy
One feature: w = Sₓₕ/(Sₓₓ+λ)
Spine: λ=10 → w₁=0.65, w₀=3.05, MSE 1.065
1.8 Activations
σ′ = σ(1−σ), max 0.25 at z=0
tanh′ = 1 − tanh², max 1 at z=0
ReLU′ = 1 if z>0 else 0
Hidden → ReLU · binary out → sigmoid
multi-class out → softmax · regression out → identity
k sigmoid layers, best case: 0.25ᵏ (k=5 → 1/1024)
The one table to memorise
Every number below is derived somewhere in this chapter from the same five students. If you can reproduce this column of results from n = 5, Σx = 15, Σy = 25, Σx² = 55, Σxy = 88, you have the unit.
| Quantity | Value | Section |
|---|---|---|
| Least-squares line | 1.1 + 1.3x | 1.1 |
| Hessian of MSE, determinant | [[2,6],[6,22]], 8 | 1.2 |
| MSE / RMSE / MAE / R² | 0.22 / 0.4690 / 0.40 / 0.9389 | 1.3 |
| Gradient at the origin | (−10.000, −35.200) | 1.4 |
| First batch step, η = 0.02 | (0.2000, 0.7040), J = 8.1558 | 1.4 |
| Learning-rate limit | η < 0.0845 | 1.4 |
| Condition number | 69.99 | 1.4 |
| Root entropy / best IG | 0.9710 / 0.9710 bits | 1.5 |
| Degree-4 fit, prediction at x = 6 | −3.0 marks | 1.6 |
| Best expected test MSE | 0.5315 at degree 1 | 1.6 |
| Ridge at λ = 10 | w₁ = 0.65, w₀ = 3.05 | 1.7 |
| Lasso zeroes the slope at | λ = 26 | 1.7 |
| Sigmoid derivative at z = 1.8 | 0.1218 | 1.8 |
Mixed Self-Test
Nine questions in no particular order and with no section labels, because a question paper does not label them either. Attempt all before opening any solution.
Q1. A dataset of six points has Σx = 18, Σy = 42, Σx² = 70, Σxy = 142. Fit y = w₀ + w₁x and state the predicted value at x = 5.
Cross-check with the deviation form: Sₓₓ = 70 − 18²/6 = 16, Sₓₕ = 142 − (18)(42)/6 = 16, so w₁ = 16/16 = 1. And ̄y = 7 = 4 + 1(3) = w₀ + w₁̄x.
Q2. Is f(w₀, w₁) = 2w₀² + 6w₀w₁ + 5w₁² − 3w₁ convex? If so, does gradient descent from any starting point reach the same answer?
Positive definite, and constant, so f is strictly convex everywhere. Therefore it has exactly one minimiser, every local minimum is global, and gradient descent from any start converges to the same point provided η is small enough — the eigenvalues are 0.2918 and 13.7082, so η < 2/13.7082 = 0.1459. Convexity guarantees the destination; it does not excuse an oversized step.
Q3. At θ = (2, −1) a cost has ∂J/∂w₀ = −4 and ∂J/∂w₁ = +12. Perform one gradient descent update with η = 0.05, and say which parameter the optimiser currently considers more wrong.
w₁, by a factor of three: the magnitude of a partial derivative is the sensitivity of the cost to that parameter, and 12 against 4 means moving w₁ pays three times as much per unit. Note the signs move each parameter against its gradient — up for w₀ because its gradient is negative.
Q4. A node has 10 samples, 7 positive and 3 negative. Give its entropy and Gini. A candidate split produces branches of (5 pos, 0 neg) and (2 pos, 3 neg). Compute the information gain.
Both weights are 0.5 here, which is the one case where forgetting to weight gives the right answer by accident. Do not rely on it.
Q5. Training MSE is 0.02 and validation MSE is 0.90. Name the condition, then rank four interventions by expected benefit: (a) add features, (b) collect more data, (c) increase λ, (d) train for more epochs.
High variance — overfitting. A 45× gap with near-zero training error means the model has memorised the training set.
(b) more data and (c) increase λ both directly attack variance, and are the right moves. Which comes first is practical: more data is strictly better but usually expensive, so raising λ is the cheap first experiment.
(a) add features raises the parameter count and therefore the σ²(d+1)/n variance term — it makes this worse. (d) more epochs also makes it worse, since training longer drives training error lower still; early stopping is the intervention that goes the other way. Underfitting would reverse this entire ranking, which is why naming the condition before choosing a fix is the whole exercise.
Q6. For a single centred feature, Sₓₓ = 20 and Sₓₕ = 30. Give the ordinary least-squares slope, the ridge slope at λ = 10, and the lasso slope at λ = 10.
The mechanisms differ and it matters. Ridge divides, so it shrinks proportionally and can never reach zero. Lasso subtracts, so it shrinks by the same absolute amount regardless of the coefficient's size, and reaches exactly zero once λ/2 ≥ |Sₓₕ| = 30, that is λ ≥ 60. Small coefficients are therefore eliminated first, which is what makes lasso a selector.
Q7. A network has four hidden layers, all sigmoid. Assuming every unit sits at its most favourable point, by what factor is the gradient reaching the first layer reduced? What if the units sit at z = 2 instead?
The best case is already a 256-fold reduction, and the best case is unattainable because it requires every pre-activation to be exactly 0. This is the vanishing gradient problem quantitatively, and it is why the first layers of a deep sigmoid network barely train. Substituting ReLU makes each factor exactly 1 for active units, so the product is 1 and depth costs nothing in gradient magnitude.
Q8. A classifier reports 100% accuracy and a log loss of 0.2459 on five samples. Explain how both can be true, and what a log loss of 0.0000 would have required.
Accuracy thresholds the probability at 0.5 and asks only which side it fell on; log loss reads the probability itself. Every sample can be on the correct side of 0.5 while none is predicted with certainty. In the worked example of 1.3 the five probabilities were 0.1419, 0.3543, 0.6457, 0.8581 and 0.9526 against labels 0, 0, 1, 1, 1 — all correct, none confident, so accuracy is 1.0 and log loss is 0.2459.
Log loss of exactly 0 requires probability 1.0 on every true class, since −ln(1) = 0 and nothing else gives 0. That would need infinite pre-activation scores, so it is unreachable and, on noisy data, undesirable — a model claiming certainty is claiming the noise floor σ² does not exist.
Q9. Batch gradient descent on the five students is run with η = 0.09 from the origin. The loss goes 28.60, 36.40, 46.36, 59.06. Diagnose precisely, and give the largest η that would have worked.
The step size exceeds the stability limit. For a quadratic cost, batch gradient descent converges if and only if η < 2/λₘₖₓ where λₘₖₓ is the largest eigenvalue of the Hessian.
At η = 0.09 the error component along the steep eigendirection is multiplied by |1 − 0.09(23.6619)| = 1.130 each step, so it grows by 13% per iteration and the loss increases geometrically — exactly the 1.27× per-step growth visible in the given sequence. The model, the data and the gradient formula are all fine.
Practical answer: use something safely below 0.0845, such as 0.04. Better answer: standardise the feature first. The condition number of 69.99 is what makes the safe range so narrow, and scaling x to zero mean and unit variance removes the coupling between the two parameters entirely.
Where This Goes Next
Every section of this unit is a prerequisite for something specific in Units 2 to 6. Here is the map.
| From here | Reappears as |
|---|---|
| 1.1 Normal equations | The closed-form solution of linear regression (2.2), and the singular-matrix problem that motivates ridge (2.2). PCA in 3.3 solves a related eigenvalue problem on the same kind of matrix. |
| 1.2 Convexity | Why logistic regression and SVMs have reliable solutions (2.3) and neural networks do not (4.x). The reason initialisation is a topic at all (4.7). |
| 1.3 Loss functions | Log loss for logistic regression, hinge loss for SVMs (2.3), the metrics of 2.4, and the common losses of 4.1. Reconstruction error in 3.3 is MSE wearing a different name. |
| 1.4 Gradient descent | Training every model from 2.3 onward. Backpropagation (4.4) is the chain rule applied to this update. Momentum and Adam (4.5) are direct patches for the condition-number problem seen here. |
| 1.5 Entropy and IG | Decision tree construction (2.3), the Gini alternative used by CART, and the NMI, homogeneity and completeness scores for clustering (3.4). Cross-entropy loss everywhere. |
| 1.6 Bias and variance | Model selection and hyperparameter search (2.1), why ensembles and random forests work (2.3), the elbow method's logic (3.2), and learning-curve diagnosis (4.8, 5.5). |
| 1.7 Regularization | Ridge and lasso regression (2.2), SVM's C parameter (2.3), and dropout, batch normalisation and early stopping (4.6). |
| 1.8 Activations | Perceptrons and layers (4.1), the trade-off discussion of 4.3, vanishing gradients in RNNs (5.4), and the softmax output of every classifier in Units 4 and 5. |
Before you start Unit 2
You should be able to do four things from a blank page: write and solve the normal equations for a small dataset; derive the MSE gradient and take one gradient descent step by hand; compute an entropy and an information gain including the branch weights; and say which of bias or variance a given train/validation gap indicates, plus one intervention for each direction.
If any of those four is shaky, the corresponding section's practice ladder is the fastest repair. Unit 2 assumes all four without reintroducing them.
Further reading
- Géron, Hands-On Machine Learning, 3rd ed., ch. 4 — the prescribed textbook. Best for seeing gradient descent, batch versus stochastic, and ridge/lasso as running code with plots. Light on derivations.
- Bishop, Pattern Recognition and Machine Learning, ch. 1.1, 1.5 and 3.1–3.2 — the careful treatment of the bias–variance decomposition and of regularization as a Gaussian prior. This is where to go when a derivation in this chapter felt compressed.
- Hastie, Tibshirani and Friedman, The Elements of Statistical Learning, ch. 3 — ridge and lasso in full, including the geometry of why L1 produces zeros.
- Goodfellow, Bengio and Courville, Deep Learning, ch. 4, 6.3 and 8.2 — conditioning and ill-conditioning, the activation function survey, and why non-convexity is manageable in practice.
- Mitchell, Machine Learning, ch. 3 — the original clear account of entropy and information gain in ID3, including gain ratio.
Spine dataset: five students, hours practised against marks out of 10. Every numerical value in this chapter was computed rather than estimated.
Next: Unit 2 — Supervised Learning (13 hours)