Skip to content

Module 06

Anurag Prasad edited this page Nov 9, 2026 · 9 revisions

Module 06 — Loss Functions, Gradient Descent and Empirical Risk Minimization

⬅️ 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


Overview and learning goals

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.

Beginner: the big picture

A model makes a prediction $\hat y$; the residual $r=\hat y-y$ measures its error; a loss $\ell(\hat y,y)$ turns it into one number to minimise. Gradient descent (GD) walks downhill: $\theta\leftarrow\theta-\eta\nabla L(\theta)$. The learning rate $\eta$ is the step length: too small is slow, too large overshoots and diverges.

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
Loading

Core concepts and derivations

Prediction, target, residual and objective

For data $\{(\mathbf{x}_i,y_i)\}_{i=1}^N$ and model $f_\theta$, the objective is $L(\theta)=\frac1N\sum_i\ell(f_\theta(\mathbf{x}_i),y_i)+\text{regulariser}$.

0–1 loss and differentiable surrogates

The 0–1 loss $\mathbf{1}[y\ne\mathrm{sign}f(x)]$ is the quantity we care about but is piecewise constant (zero gradient, NP-hard to minimise exactly). Convex surrogates of the margin $m=yf(\mathbf{x})$ — hinge $\max(0,1-m)$, logistic $\ln(1+e^{-m})$, exponential $e^{-m}$ — upper-bound it (suitably scaled) and are minimised by gradient methods. The hinge, logistic and exponential surrogates are all classification-calibrated: minimising them (over a sufficiently rich model class) recovers the Bayes-optimal classifier (Bartlett, Jordan & McAuliffe 2006); only the logistic loss also yields calibrated probabilities.

Regression losses and classification surrogates

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).

MSE, MAE and Huber

$\ell_{MSE}=\frac12r^2$ (gradient $r$; Gaussian MLE; sensitive to outliers), $\ell_{MAE}=\lvert r\rvert$ (gradient $\mathrm{sign}r$; Laplace MLE; robust; estimates the median), Huber: quadratic for $\lvert r\rvert\le\delta$, linear beyond — smooth near 0 and robust in the tails. MSE is minimised by the conditional mean, MAE by the conditional median.

Binary and categorical cross-entropy

Binary: $\ell=-[y\ln p+(1-y)\ln(1-p)]$ with $p=\sigma(z)$; categorical: $\ell=-\sum_ky_k\ln p_k$ with softmax (Module 03). Both have gradient $\mathbf{p}-\mathbf{y}$ with respect to the logits.

Sigmoid, softmax and negative log-likelihood

Modelling $P(y=1\mid\mathbf{x})=\sigma(\mathbf{w}^\top\mathbf{x}+b)$ and maximising the likelihood is logistic regression. Its NLL is convex in $(\mathbf{w},b)$. Label smoothing, temperature and class weights modify the target or logits but keep this structure (Module 10).

Empirical versus population risk

The population risk $R(\theta)=\mathbb{E}_{(x,y)\sim\mathcal{D}}[\ell]$ is what we want; the empirical risk $\hat R(\theta)=\frac1N\sum_i\ell$ is what we can compute. ERM minimises $\hat R$. The generalisation gap $R(\hat\theta)-\hat R(\hat\theta)$ is non-negative in expectation because $\hat\theta$ was chosen to fit that sample; capacity control and regularisation (Module 10) manage it.

Batch, stochastic and mini-batch gradient descent

Method Gradient from Cost/step Noise
Batch GD all $N$ examples high none
SGD 1 example tiny high
Mini-batch $B$ examples moderate, vectorised $\propto1/B$

A mini-batch gradient is an unbiased estimator of the full gradient with covariance $\propto1/B$. Noise helps escape sharp regions but prevents exact convergence at a fixed $\eta$ (hence decay schedules, Module 08).

Learning rate and convergence

Consider $L(w)=\frac h2(w-w^\star)^2$. Then $w_{t+1}-w^\star=(1-\eta h)(w_t-w^\star)$, so GD converges iff $\lvert1-\eta h\rvert&lt;1\iff0&lt;\eta&lt;2/h$, fastest at $\eta=1/h$ (one step). For a multivariate quadratic with Hessian eigenvalues in $[\mu,L]$, convergence requires $\eta&lt;2/L$ and the rate along each eigendirection is $1-\eta\lambda_i$. With $\eta=2/(L+\mu)$ the contraction factor is $\frac{\kappa-1}{\kappa+1}$, $\kappa=L/\mu$ — slow when $\kappa$ is large (Figure 8.1).

Feature scaling and conditioning

For linear regression $L=\frac1{2N}\lVert X\mathbf{w}-\mathbf{y}\rVert^2$, the Hessian is $\frac1NX^\top X$ (the feature covariance). Features with very different scales produce a large condition number. Standardising features ($x\leftarrow(x-\mu)/\sigma$) makes $\kappa$ close to 1 and speeds convergence; the closed-form solution is $\hat{\mathbf{w}}=(X^\top X)^{-1}X^\top\mathbf{y}$ (normal equations), which is rarely used at deep-learning scale.

Worked example

Fit $y=wx$ to $(1,2),(2,4),(3,6)$ with $L=\frac1{2N}\sum(wx_i-y_i)^2$, $w_0=0$, $\eta=0.1$.

  • $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&lt;0.4286$; $\eta=1/h\approx0.214$ lands exactly on $w^\star=2$ in one step.

Implementation

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 / diverge
import 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()

Advanced topics

  • 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&lt;\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).

Pitfalls and best practices

  • 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.

Conceptual questions and answers

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

$w_{t+1}-w^\star=(1-\eta h)(w_t-w^\star)$ contracts iff $\lvert1-\eta h\rvert&lt;1$, i.e. $0&lt;\eta&lt;2/h$.

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 $\mathbf{p}-\mathbf{y}$, which is large exactly when the prediction is far from the target, unlike MSE-on-sigmoid whose gradient vanishes at saturation.

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).

Sources and further reading

  • 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 ➡️

🎓 Deep Learning Hub

🏠 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

Part 1 · Mathematical foundations
Part 2 · Neural network fundamentals
Part 3 · Training deep networks
Part 4 · Core architectures
Part 5 · Representation and generative learning
Part 6 · Specialised, modern and responsible deep learning
Reference and meta

Clone this wiki locally