Repository navigation
Module 24
⬅️ Module 23 · 🗺️ Curriculum · 🏠 Home · Question bank ➡️
Level: Intermediate–Advanced · Prerequisites: Modules 03, 10 and familiarity with at least one architecture module · Time: about 9–10 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
Building a model is half the job; the other half is knowing whether it works, why it behaves as it does, when it breaks, what it costs and whom it affects. This module covers evaluation metrics and calibration, interpretability, robustness and distribution shift, efficiency (mixed precision, quantisation, distillation), reproducibility and the ethics of deployment.
After this module you should be able to:
- compute precision, recall, F1, ROC/PR curves and choose metrics for imbalanced problems;
- measure and fix calibration (ECE, temperature scaling);
- apply and critique attribution methods (saliency, Integrated Gradients, Grad-CAM, SHAP);
- explain adversarial examples, FGSM and adversarial training, and detect distribution shift;
- apply quantisation, pruning, distillation, mixed precision and checkpointing;
- design reproducible experiments and discuss fairness, privacy and documentation.
A model with 94% accuracy sounds great — until you learn that 88% of the data belong to one class and a model that always predicts it scores 88%. Good evaluation asks the right question (which errors are costly?), compares against sensible baselines, quantifies uncertainty, tests under shift and examines subgroups. Responsible practice documents what the model is for and where it should not be used.
flowchart LR
D["Data + splits (no leakage)"] --> M["Train model"] --> E["Evaluate: metrics, baselines, CIs"]
E --> C["Calibration"]
E --> R["Robustness / shift tests"]
E --> S["Subgroup / fairness analysis"]
E --> X["Interpretability checks"]
C --> DEP["Deploy with monitoring"]
R --> DEP
S --> DEP
X --> DEP
DEP --> DOC["Model card, datasheet, incident process"]
From true/false positives and negatives (TP, FP, FN, TN):
Varying the decision threshold traces the ROC curve (TPR vs FPR); AUC is the probability a random positive outscores a random negative. Under strong class imbalance ROC can look optimistic because FPR's denominator (negatives) is huge; the precision–recall curve and average precision are more informative (Davis & Goadrich 2006; Saito & Rehmsmeier 2015). A random classifier has AP equal to the prevalence.

Figure 24.1 — Simulated scores with 10% prevalence. Left: ROC. Middle: precision–recall; the dashed line is the no-skill baseline (prevalence). Right: reliability diagram of a deliberately over-confident probability transform lying below the diagonal. Original figure (figures/make_figs_2.py).
Always report a trivial baseline (majority class, last-value forecast, simple linear model), several random seeds with mean ± standard deviation, and confidence intervals (bootstrap resampling of the test set). Slice errors by subgroup, input length, source and label noise; inspect the worst examples manually. Ablations remove one component at a time to attribute gains; "improvements" within seed variance are not evidence (Henderson et al. 2018 on RL variance).
A model is calibrated if among predictions with confidence
Modern deep nets are typically over-confident (Guo et al. 2017). Temperature scaling fits one scalar
-
Saliency:
$\lvert\partial F/\partial x_i\rvert$ (Simonyan et al. 2014) — noisy. -
Integrated Gradients (Sundararajan et al. 2017): attribute to feature
$i$ the path integral from a baseline$x'$ :
-
Grad-CAM (Selvaraju et al. 2017): weight a conv layer's feature maps by the spatially averaged gradients of the class score:
$L=\operatorname{ReLU}\bigl(\sum_k\alpha_kA^k\bigr)$ ,$\alpha_k=\frac1Z\sum_{ij}\partial y^c/\partial A^k_{ij}$ . -
SHAP (Lundberg & Lee 2017): Shapley values
$\phi_i=\sum_{S\subseteq F\setminus{i}}\frac{\lvert S\rvert!(\lvert F\rvert-\lvert S\rvert-1)!}{\lvert F\rvert!}\bigl[f(S\cup{i})-f(S)\bigr]$ . - Caveat: attribution maps can look plausible while being independent of the model (Adebayo et al. 2018 "sanity checks"); validate with randomisation tests and faithfulness metrics. Prefer interpretability claims backed by interventions.
Adversarial examples are tiny perturbations that flip predictions (Szegedy et al. 2014). FGSM (Goodfellow et al. 2015):
-
Mixed precision: compute in fp16/bf16 with fp32 master weights; fp16 needs loss scaling (multiply loss by
$S$ so small gradients do not underflow), bf16 has fp32's exponent range and usually does not (Micikevicius et al. 2018). -
Activation checkpointing: store a subset of activations and recompute the rest (Module 02): memory
$O(\sqrt L)$ for$L$ layers at the cost of one extra forward pass (Chen et al. 2016). -
Quantisation: map floats to integers,
$q=\operatorname{clip}\bigl(\operatorname{round}(x/s)+z\bigr)$ ,$\hat x=s(q-z)$ ; int8/int4 weights shrink memory 4–8× and speed inference; post-training quantisation vs quantisation-aware training (Jacob et al. 2018). - Pruning: remove low-magnitude weights/structures; the lottery ticket hypothesis (Frankle & Carbin 2019) finds sparse trainable sub-networks.
-
Knowledge distillation (Hinton et al. 2015): train a small student on the teacher's temperature-softened outputs: $L=(1-\alpha),\mathrm{CE}(y,\mathbf{p}s)+\alpha,T^2,D{KL}\bigl(\mathbf{p}_t^{(T)}\Vert\mathbf{p}_s^{(T)}\bigr)$; the
$T^2$ factor keeps gradient magnitudes comparable. - Measure latency, throughput, memory, energy on target hardware, not just FLOPs.
Record code version, data version/hash, config, seeds, library/CUDA versions, hardware; log metrics and checkpoints (MLflow/W&B-style tools); fix seeds but expect nondeterminism from GPU kernels; report compute budget; release code, configs and evaluation scripts. Beware leakage (Module 10) and benchmark contamination.
Group fairness criteria: demographic parity
Confusion matrix: TP=80, FP=20, FN=40, TN=860 (
ECE (two bins, 5 examples each): bin A: mean confidence
Quantisation:
FGSM: for
import numpy as np
def prf(y_true, y_pred):
tp = np.sum((y_true == 1) & (y_pred == 1)); fp = np.sum((y_true == 0) & (y_pred == 1)); fn = np.sum((y_true == 1) & (y_pred == 0))
p = tp / max(tp + fp, 1); r = tp / max(tp + fn, 1); return p, r, 2 * p * r / max(p + r, 1e-12)
def ece(conf, correct, bins=10):
edges = np.linspace(0, 1, bins + 1); idx = np.clip(np.digitize(conf, edges) - 1, 0, bins - 1); out = 0.0
for b in range(bins):
m = idx == b
if m.any(): out += m.mean() * abs(correct[m].mean() - conf[m].mean())
return out
def bootstrap_ci(metric, y, yhat, n=1000, seed=0):
r = np.random.default_rng(seed); vals = [metric(y[i], yhat[i]) for i in (r.integers(0, len(y), len(y)) for _ in range(n))]
return np.percentile(vals, [2.5, 97.5])import torch, torch.nn.functional as F
def fgsm(model, x, y, eps):
x = x.clone().requires_grad_(True); F.cross_entropy(model(x), y).backward()
return (x + eps * x.grad.sign()).clamp(0, 1).detach()
def distill_loss(zs, zt, y, T=4.0, alpha=0.7):
soft = F.kl_div(F.log_softmax(zs / T, -1), F.softmax(zt / T, -1), reduction='batchmean') * T * T
return (1 - alpha) * F.cross_entropy(zs, y) + alpha * soft
# Mixed precision with bf16 (no loss scaling needed):
# with torch.autocast('cuda', dtype=torch.bfloat16): loss = model(x).loss- Conformal prediction and uncertainty (deep ensembles, MC dropout, Bayesian last layers, evidential models).
- Causal evaluation: A/B tests, off-policy evaluation, spurious correlations (waterbirds), invariant risk minimisation and its limits.
- Certified robustness: randomised smoothing, interval bound propagation.
- Red-teaming and safety evaluations for LLMs; evaluation of dangerous capabilities; benchmark saturation and contamination (Module 23).
- Mechanistic interpretability: circuits, probing, causal interventions (activation patching), sparse-autoencoder features.
- Green AI: energy/carbon accounting, efficient architectures, reuse of pretrained models.
- Model monitoring and MLOps: drift detection, shadow deployment, rollback, incident response.
- Reporting accuracy on imbalanced data; tuning thresholds on the test set.
- Single-seed comparisons without intervals.
- Trusting saliency maps without sanity checks.
- Evaluating robustness with weak attacks (gradient masking creates false security).
- Quantising without calibration data or per-channel scales for outlier-heavy layers.
- Skipping subgroup evaluation; averaging hides harm.
- Treating fairness as a post-hoc metric rather than a design decision.
Q1. Why is accuracy misleading for imbalanced data, and what should you report?
A majority-class predictor scores high accuracy while being useless. Report precision, recall/F1, PR curves/AP, confusion matrices and costs, compared with a prevalence baseline.
Q2. ROC vs precision–recall curves?
ROC (TPR vs FPR) is insensitive to class prevalence and may look good when negatives dominate; PR curves reflect the false-positive burden relative to true positives and are preferred under heavy imbalance.
Q3. What is calibration and how does temperature scaling fix over-confidence?
Calibration means confidence equals empirical accuracy. Temperature scaling divides logits by a scalar
Q4. State the completeness axiom of Integrated Gradients.
Attributions sum to
Q5. Why might a saliency map be misleading?
It can be insensitive to the model's parameters and merely reflect image edges (Adebayo et al. 2018); gradients also saturate. Validate with randomisation tests and interventions.
Q6. Explain FGSM and why high-dimensional inputs are vulnerable.
FGSM steps by
Q7. Why does distillation use temperature and a $T^2$ factor?
Higher
Q8. Why do fp16 training runs need loss scaling but bf16 usually do not?
fp16 has a narrow exponent range, so small gradients underflow; bf16 has the same exponent range as fp32 (with fewer mantissa bits).
Q9. Why can't all fairness criteria be satisfied at once?
With different base rates across groups, calibration and equal error rates are mathematically incompatible (except for perfect prediction), so one must choose criteria according to context and values.
Q10. What is in a model card?
Intended use and out-of-scope uses, training/evaluation data, metrics (including by subgroup), limitations, ethical considerations and versioning.
- Davis, J., & Goadrich, M. (2006). The relationship between precision-recall and ROC curves. ICML.
- Saito, T., & Rehmsmeier, M. (2015). The precision-recall plot is more informative than the ROC plot when evaluating binary classifiers on imbalanced datasets. PLOS ONE, 10(3).
- Guo, C., Pleiss, G., Sun, Y., & Weinberger, K. Q. (2017). On calibration of modern neural networks. ICML. arXiv:1706.04599.
- Simonyan, K., Vedaldi, A., & Zisserman, A. (2014). Deep inside convolutional networks: visualising image classification models and saliency maps. ICLR Workshop.
- Sundararajan, M., Taly, A., & Yan, Q. (2017). Axiomatic attribution for deep networks. ICML. arXiv:1703.01365.
- Selvaraju, R. R., et al. (2017). Grad-CAM. ICCV. arXiv:1610.02391.
- Lundberg, S. M., & Lee, S.-I. (2017). A unified approach to interpreting model predictions. NeurIPS. arXiv:1705.07874.
- Adebayo, J., et al. (2018). Sanity checks for saliency maps. NeurIPS. arXiv:1810.03292.
- Szegedy, C., et al. (2014). Intriguing properties of neural networks. ICLR. arXiv:1312.6199.
- Goodfellow, I., Shlens, J., & Szegedy, C. (2015). Explaining and harnessing adversarial examples. ICLR. arXiv:1412.6572.
- Madry, A., et al. (2018). Towards deep learning models resistant to adversarial attacks. ICLR. arXiv:1706.06083.
- Hendrycks, D., & Gimpel, K. (2017). A baseline for detecting misclassified and out-of-distribution examples in neural networks. ICLR.
- Micikevicius, P., et al. (2018). Mixed precision training. ICLR. arXiv:1710.03740.
- Chen, T., Xu, B., Zhang, C., & Guestrin, C. (2016). Training deep nets with sublinear memory cost. arXiv:1604.06174.
- Jacob, B., et al. (2018). Quantization and training of neural networks for efficient integer-arithmetic-only inference. CVPR.
- Frankle, J., & Carbin, M. (2019). The lottery ticket hypothesis. ICLR. arXiv:1803.03635.
- Hinton, G., Vinyals, O., & Dean, J. (2015). Distilling the knowledge in a neural network. arXiv:1503.02531.
- Henderson, P., et al. (2018). Deep reinforcement learning that matters. AAAI.
- Kleinberg, J., Mullainathan, S., & Raghavan, M. (2017). Inherent trade-offs in the fair determination of risk scores. ITCS. Chouldechova, A. (2017). Fair prediction with disparate impact. Big Data, 5(2).
- Abadi, M., et al. (2016). Deep learning with differential privacy. CCS. arXiv:1607.00133.
- Mitchell, M., et al. (2019). Model cards for model reporting. FAT*. arXiv:1810.03993.
- Gebru, T., et al. (2021). Datasheets for datasets. Communications of the ACM, 64(12). arXiv:1803.09010.
⬅️ Module 23 · 🗺️ Curriculum · 🏠 Home · Question bank ➡️
🏠 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