Skip to content

Module 24

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

Module 24 — Evaluation, Explainability, Robustness and Efficient Deep Learning

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


Overview and learning goals

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.

Beginner: the big picture

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"]
Loading

Core concepts and derivations

Classification metrics and the confusion matrix

From true/false positives and negatives (TP, FP, FN, TN):

$$ \text{accuracy}=\frac{TP+TN}{N},\ \ \text{precision}=\frac{TP}{TP+FP},\ \ \text{recall (TPR)}=\frac{TP}{TP+FN},\ \ \text{FPR}=\frac{FP}{FP+TN},\ \ F_1=\frac{2PR}{P+R}. $$

$F_1$ is the harmonic mean of precision and recall (it punishes imbalance between them); $F_\beta$ weights recall $\beta$ times as much. Multiclass: macro (average per-class metrics, equal class weight), micro (pool counts), weighted. Regression: MAE, RMSE, $R^2$, quantile loss; ranking: NDCG, MAP; generation: BLEU/ROUGE, learned metrics and human evaluation.

ROC, PR curves and imbalance

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.

ROC, precision-recall and reliability diagram for a simulated classifier

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

Baselines, error analysis, confidence intervals and ablations

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

Calibration

A model is calibrated if among predictions with confidence $p$, the fraction correct is $p$. Partition into $M$ confidence bins $B_m$:

$$ \mathrm{ECE}=\sum_{m=1}^{M}\frac{\lvert B_m\rvert}{n},\bigl\lvert\mathrm{acc}(B_m)-\mathrm{conf}(B_m)\bigr\rvert . $$

Modern deep nets are typically over-confident (Guo et al. 2017). Temperature scaling fits one scalar $T>0$ on validation data by minimising NLL of $\mathrm{softmax}(\mathbf{z}/T)$ — it does not change the argmax (accuracy) but fixes confidence. Other measures: Brier score $\frac1n\sum(p-y)^2$ (a proper scoring rule), reliability diagrams, conformal prediction for coverage guarantees.

Interpretability and attribution

  • 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'$:

$$ \mathrm{IG}_i(x)=(x_i-x_i')\int_0^1\frac{\partial F\bigl(x'+\alpha(x-x')\bigr)}{\partial x_i},d\alpha,\qquad\sum_i\mathrm{IG}_i=F(x)-F(x')\ \ (\text{completeness}). $$

  • Grad-CAM (Selvaraju et al. 2017): weight a conv layer's feature maps by the spatially averaged gradients of the class score: $L=\mathrm{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 robustness and distribution shift

Adversarial examples are tiny perturbations that flip predictions (Szegedy et al. 2014). FGSM (Goodfellow et al. 2015): $\mathbf{x}'=\mathbf{x}+\epsilon\mathrm{sign}(\nabla_{\mathbf{x}}L(\theta,\mathbf{x},y))$ — a one-step maximisation of the linearised loss under an $\ell_\infty$ budget; PGD iterates with projection. Adversarial training solves $\min_\theta\mathbb{E}\bigl[\max_{\lVert\delta\rVert\le\epsilon}L(\theta,x+\delta,y)\bigr]$ (Madry et al. 2018): the strongest empirical defence, at higher cost and some clean-accuracy loss. Distribution shift: covariate, label and concept shift (Module 22); evaluate on corrupted (ImageNet-C), natural-shift and OOD sets; OOD detection baselines use maximum softmax probability (Hendrycks & Gimpel 2017) or energy scores. Monitor input and prediction drift in production.

Efficiency: precision, memory and compression

  • 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=\mathrm{clip}\bigl(\mathrm{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.

Reproducibility and experiment management

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.

Ethics, fairness, privacy and documentation

Group fairness criteria: demographic parity $P(\hat y=1\mid A=a)$ equal across groups; equalised odds (equal TPR and FPR); calibration within groups — in general not simultaneously satisfiable when base rates differ (Kleinberg et al. 2017; Chouldechova 2017), so the choice is a value judgement made with stakeholders. Privacy: models can memorise training data; differential privacy via DP-SGD clips each per-example gradient to norm $C$ and adds Gaussian noise $\mathcal{N}(0,\sigma^2C^2I)$ to the sum (Abadi et al. 2016). Documentation: Model Cards (Mitchell et al. 2019) and Datasheets for Datasets (Gebru et al. 2021) state intended use, data provenance, metrics by subgroup, limitations. Consider consent and licensing of data, environmental cost, dual use and misuse (deepfakes, surveillance), human oversight and recourse.

Worked example

Confusion matrix: TP=80, FP=20, FN=40, TN=860 ($N=1000$, prevalence 12%). Accuracy $=0.94$ (but majority-class baseline $=0.88$); precision $=0.80$; recall $=0.667$; $F_1=0.727$; FPR $=20/880=0.023$.

ECE (two bins, 5 examples each): bin A: mean confidence $0.9$, accuracy $0.8$ ⇒ gap $0.1$; bin B: confidence $0.6$, accuracy $0.4$ ⇒ gap $0.2$. $\mathrm{ECE}=0.5(0.1)+0.5(0.2)=0.15$ — over-confident.

Quantisation: $s=1/127$; $x=0.3\to q=\mathrm{round}(38.1)=38\to\hat x=38/127=0.2992$, error $8\times10^{-4}$.

FGSM: for $\mathbf{w}=(0.5,-1)$ in a linear scorer $f=\mathbf{w}^\top\mathbf{x}$, the loss-increasing perturbation direction is $-\mathrm{sign}(\mathbf{w})\cdot y$ per coordinate; with $\epsilon=0.1$ every coordinate moves by $0.1$ and the score changes by $\epsilon\lVert\mathbf{w}\rVert_1=0.15$ — in $d$ dimensions the change grows with $d$, which is why high-dimensional inputs are fragile.

Implementation

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

Advanced topics

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

Pitfalls and best practices

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

Conceptual questions and answers

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 $T>1$ fitted on validation NLL, softening probabilities without changing predicted classes.

Q4. State the completeness axiom of Integrated Gradients.

Attributions sum to $F(x)-F(x')$, the difference in model output between the input and the baseline.

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 $\epsilon\mathrm{sign}(\nabla_xL)$. Per-coordinate changes are tiny, but their effects add across $d$ dimensions ($\epsilon\lVert\nabla\rVert_1$), changing the logit substantially.

Q7. Why does distillation use temperature and a $T^2$ factor?

Higher $T$ softens the teacher's probabilities, revealing relative similarities between wrong classes ("dark knowledge"); gradients scale as $1/T^2$, so multiplying by $T^2$ keeps the loss balanced.

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.

Sources and further reading

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

🎓 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