Repository navigation
Module 06
⬅️ Module 05 · 🗺️ Curriculum · 🏠 Home · Module 07 ➡️
Level: Intermediate · Prerequisites: Module 02, Module 03 · Time: about 7–8 hours
On this page: Overview and learning goals · Beginner: the big picture · Core concepts and derivations · Worked example · Implementation · Advanced topics · Pitfalls and best practices · Conceptual questions and answers · Sources and further reading
Learning is optimisation: pick a loss that says how wrong a prediction is, average it over the data (empirical risk), and descend its gradient. This module connects loss functions to probabilistic assumptions, defines risk and ERM, and analyses gradient descent on the simplest nontrivial case (a quadratic) to understand step sizes, convergence and conditioning.
After this module you should be able to:
- choose a loss from the task and noise model, and derive its gradient;
- distinguish empirical from population risk and explain the generalisation gap;
- compare batch, stochastic and mini-batch gradient descent;
- derive the convergence condition
$\eta<2/L$ and explain feature scaling.
A model makes a prediction
flowchart LR
D["Mini-batch of data"] --> F["Forward: predictions"]
F --> L["Loss L(theta)"]
L --> G["Backward: gradient"]
G --> U["Update: theta <- theta - eta * grad"]
U --> F
For data
The 0–1 loss

Figure 6.1 — Left: MSE, MAE and Huber as functions of the residual. Right: 0–1 loss and its convex surrogates as functions of the margin. Original figure (figures/make_figs_1.py).
Binary:
Modelling
The population risk
| Method | Gradient from | Cost/step | Noise |
|---|---|---|---|
| Batch GD | all |
high | none |
| SGD | 1 example | tiny | high |
| Mini-batch |
|
moderate, vectorised |
A mini-batch gradient is an unbiased estimator of the full gradient with covariance
Consider
For linear regression
Fit
-
$L(0)=\frac16(4+16+36)=9.333$ . -
$\nabla L=\frac1N\sum(wx_i-y_i)x_i=\frac13(-2-8-18)=-9.333$ . -
$w_1=0+0.1\cdot9.333=0.933$ ; residuals$(-1.067,-2.133,-3.2)$ ,$L(w_1)=2.655$ . - Curvature
$h=\frac1N\sum x_i^2=14/3=4.667$ , so stability needs$\eta<0.4286$ ;$\eta=1/h\approx0.214$ lands exactly on$w^\star=2$ in one step.
import numpy as np
x = np.array([1., 2., 3.]); y = 2 * x
def run(eta, steps=8, w=0.0):
out = []
for _ in range(steps):
w -= eta * np.mean((w * x - y) * x); out.append(w)
return np.round(out, 3)
print(run(0.1)); print(run(1/ (np.mean(x**2)))); print(run(0.5)) # converge / one step / divergeimport torch, torch.nn as nn
model = nn.Linear(10, 1); opt = torch.optim.SGD(model.parameters(), lr=0.1)
for xb, yb in loader: # mini-batches
opt.zero_grad(); loss = nn.functional.mse_loss(model(xb), yb); loss.backward(); opt.step()- Calibration of surrogates and consistency theory; focal loss for imbalance; class-balanced and cost-sensitive losses.
- Proper scoring rules: log-loss and Brier score are minimised only by true probabilities.
-
Stochastic approximation (Robbins–Monro):
$\sum\eta_t=\infty$ ,$\sum\eta_t^2<\infty$ ensures convergence for convex problems. -
Convergence rates: convex
$L$ -smooth GD$O(1/t)$ ; strongly convex linear rate; SGD$O(1/\sqrt t)$ (convex) or$O(1/t)$ (strongly convex). - Implicit regularisation: GD on separable logistic regression converges in direction to the max-margin solution (Soudry et al., 2018).
- Large-batch training and the linear scaling rule (Goyal et al., 2017).
- Mean versus sum reduction changes the effective learning rate by
$B$ . - Evaluating the loss on training data only.
- Unscaled features or targets → poor conditioning and unstable steps.
- Using MSE on probabilities for classification.
- Comparing losses across different reductions, weights or label-smoothing settings.
Q1. Why not directly minimise the 0–1 loss?
Show answer
It is discontinuous with zero gradient almost everywhere, and exact minimisation is NP-hard. Convex surrogates give usable gradients and, when calibrated, the same optimum.
Q2. When would you choose MAE or Huber over MSE?
Show answer
When the data contain outliers or heavy-tailed noise: MSE squares large residuals and lets outliers dominate; MAE grows linearly, Huber combines smoothness with robustness.
Q3. Why is the generalisation gap non-negative on average?
Show answer
The parameters are selected to minimise error on the training sample, so training error is an optimistically biased estimate of population risk.
Q4. Derive the stability condition for gradient descent on a 1-D quadratic.
Show answer
Q5. Why does feature scaling speed up training?
Show answer
It reduces the condition number of the Hessian, so one learning rate suits all directions and the iterates do not zigzag across narrow valleys.
Q6. What is the benefit and cost of larger mini-batches?
Show answer
Lower-variance gradients and better hardware utilisation, but more computation per step, diminishing returns in noise reduction and sometimes worse generalisation without learning-rate retuning.
Q7. MSE is minimised by the conditional mean; MAE by the median. Why does this matter?
Show answer
If the target distribution is skewed or multimodal, the two losses give different predictions; pick the one whose statistic matches the business or scientific question.
Q8. Why is the gradient of cross-entropy w.r.t. logits well behaved when the model is wrong?
Show answer
It equals
Q9. Does a lower training loss always mean a better model?
Show answer
No. It may reflect overfitting; judge by held-out data (Modules 10, 24).
- Hastie, T., Tibshirani, R., & Friedman, J. (2009). The Elements of Statistical Learning (2nd ed.). Springer.
- Huber, P. J. (1964). Robust estimation of a location parameter. Annals of Mathematical Statistics, 35(1).
- Robbins, H., & Monro, S. (1951). A stochastic approximation method. Annals of Mathematical Statistics, 22(3).
- Bartlett, P. L., Jordan, M. I., & McAuliffe, J. D. (2006). Convexity, classification, and risk bounds. JASA, 101(473).
- Bottou, L., Curtis, F. E., & Nocedal, J. (2018). Optimization methods for large-scale machine learning. SIAM Review, 60(2).
- Soudry, D., et al. (2018). The implicit bias of gradient descent on separable data. JMLR, 19.
- Goyal, P., et al. (2017). Accurate, large minibatch SGD: training ImageNet in 1 hour. arXiv:1706.02677.
⬅️ Module 05 · 🗺️ Curriculum · 🏠 Home · Module 07 ➡️
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths · ❓ Question bank · 📖 Glossary · 📚 References · ✏️ Contributing
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths
❓ Question bank · 📖 Glossary · 📚 References
Jump to module:
01 02 03 04 05 06 07 08 09 10 11 12
13 14 15 16 17 18 19 20 21 22 23 24