Choosing Metrics, Penalties, and Ablations for an NLP Model
Machine LearningModel answerLast updated
Compare classifier evaluation metrics, contrast L1 and L2 penalties, and plan a controlled ablation study that isolates which pipeline components drive an NLP system's quality.
Answer the following three-part question as you would in a technical discussion for an applied scientist position.
Part 1: Evaluating a binary classifier
Describe each of the items below and say when you would favor it:
- The four confusion matrix outcomes (TP, FP, TN, FN)
- Precision, recall, and F1
- The ROC curve and AUC
- Optionally: the precision-recall curve, and why it can be more informative when classes are heavily imbalanced
Part 2: L1 versus L2 penalties
- Write the term each one adds to the training loss.
- Explain how each affects the learned weights (for example, which one yields sparsity, and why).
- Give practical guidance on choosing between them.
Part 3: Ablation study for a multi-stage NLP system
An NLP system is built from several parts, for instance text preprocessing, an encoder, a retrieval stage, a prompt template, a reranker, and decoding settings. Describe how you would design an ablation study that reveals which parts truly matter. Cover:
- What you hold fixed and what you vary
- How you guard against confounding factors
- How you decide whether an observed difference is meaningful rather than noise
Hints
Hint 1
For Part 1, start from the confusion matrix at a fixed threshold, then ask which error type is more expensive in the scenario. Work out a rare-positive example with real counts to see how a small false positive rate can still mean low precision.
Hint 2
For Part 2, compare the gradients of the two penalties: one pulls proportionally to the weight, the other with constant force. Then connect that to why one lands exactly on zero.
Hint 3
For Part 3, think about fairness: if the full system was tuned and the stripped-down variant was not, what are you actually measuring? Also consider interactions between components, and how to quantify uncertainty with paired comparisons on the same test examples.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Classification metrics
Confusion matrix. Once a threshold is fixed on the model score, each prediction is one of:
- TP: positive, predicted positive
- FN: positive, predicted negative (a miss)
- FP: negative, predicted positive (a false alarm)
- TN: negative, predicted negative
Precision, recall, F1
- Precision = TP / (TP + FP): of everything flagged, how much was correct. Favor it when false alarms are costly (auto-banning accounts, marking legitimate mail as spam).
- Recall = TP / (TP + FN): of all real positives, how many were found. Favor it when misses are costly (disease screening, fraud, a first-stage candidate retriever).
- F1 = 2PR / (P + R), the harmonic mean. It collapses if either component is low, so it suits cases where both error types matter about equally and a single number is needed. F-beta shifts the weight toward recall (beta > 1) or precision (beta < 1).
- In practice, a cleaner framing is often "maximize recall subject to precision of at least X", or choosing the threshold that minimizes expected cost, c_FP * FP + c_FN * FN.
ROC and AUC
- ROC plots TPR (recall) against FPR = FP / (FP + TN) as the threshold sweeps.
- AUC equals the probability that a random positive is scored above a random negative. 0.5 is chance and 1.0 is perfect ranking.
- It is threshold-free, so it is useful for comparing rankers before an operating point is chosen. It says nothing about calibration.
PR curve under imbalance
FPR is divided by the (huge) number of negatives, so a large absolute number of false positives can still look small. Example: 1,000 positives and 999,000 negatives. At TPR = 0.9 and FPR = 1%, there are 900 TP and about 9,990 FP, so precision is only about 8%, yet the ROC point looks excellent. The PR curve exposes this. Its chance baseline is the prevalence (0.001), and it is summarized with average precision. Prefer it when positives are rare and the quality of flagged items matters (fraud, rare-disease detection, relevance search).
Part 2: L1 vs. L2
Forms
- L1 (lasso): J(w) = L(w) + lambda * sum |w_i|
- L2 (ridge / weight decay): J(w) = L(w) + lambda * sum w_i^2
The bias is usually left unpenalized.
Effect on weights
- L2 has gradient 2lambdaw, a pull proportional to the weight. Large weights shrink strongly, small ones barely move, so weights get small but seldom exactly zero.
- L1 has subgradient lambdasign(w), a constant pull. If the data gradient for a weight is weaker than lambda, the weight settles at exactly zero. The proximal step is soft-thresholding: w <- sign(w) * max(|w| - etalambda, 0). The result is sparsity and implicit feature selection.
- Geometrically, the L1 constraint region is a diamond with corners on the axes, where loss contours tend to touch; the L2 region is a sphere with no such corners.
- Probabilistically, L2 is a Gaussian prior and L1 a Laplace prior (sharp peak at zero).
Choosing
- L1: many features with few relevant, need for interpretability or a cheap model, built-in selection.
- L2: many small contributing features, correlated features (weight is shared and the solution is stable), smooth optimization. Ridge also has a closed form, (X^T X + lambda I)^-1 X^T y, and fixes ill-conditioning.
- Elastic net (both penalties): correlated features where you still want sparsity. Pure L1 tends to pick one of a correlated group arbitrarily, and the pick varies across resamples.
- Always standardize features first, since both penalties depend on scale, and tune lambda by cross-validation.
- In deep learning with Adam, use decoupled weight decay (AdamW); an L2 term in the loss is not equivalent under adaptive optimizers.
Part 3: Designing the ablation
1. Establish a reference and a protocol
- Treat the full system as the reference. Use one held-out evaluation set never used for tuning.
- Decide in advance the primary metric (for example task accuracy or exact match), secondary metrics (latency, cost, faithfulness), and the smallest effect worth caring about (say 1 point).
2. Leave-one-out, plus add-one-in
Remove or swap one component at a time, with a sensible null for each:
- Retrieval: no retrieval, and also random passages (separates "more tokens" from "relevant context")
- Reranker: original retriever order
- Prompt: a minimal template
- Encoder: a baseline encoder
- Decoding: greedy
Also build up from a minimal baseline, because contributions are often non-additive (a reranker helps only if retrieval recall is adequate). With few components, a full or fractional 2^k factorial design estimates interaction effects directly.
3. Hold constant
Data and splits, corpus and index snapshot, model checkpoints and hosted API version, seeds, hardware and compute budget, context length, decoding parameters (unless studied), the evaluation script, and any LLM-judge model and prompt.
4. Confounders
- Tuning fairness: if only the full system was tuned, you measure tuning effort. Retune each variant with the same budget and search space, or retune none.
- Coupling: a prompt tuned for a given encoder or reranker; test key pairs jointly.
- Capacity or compute changes: removing a module changes parameters, tokens, or latency; use size- or token-matched controls.
- Leakage: no test answers in the retrieval corpus, and no design decisions made by looking at test results.
- Stochasticity: prefer deterministic decoding, or average over several seeds.
5. Significance
- Use paired comparisons on the same examples. Compute a bootstrap confidence interval on the metric difference, or use McNemar's test for binary correctness and a paired permutation test for continuous scores.
- Run multiple training seeds when training is involved and report mean and standard deviation; a difference smaller than seed-to-seed variance is not a finding.
- Correct for multiple comparisons (Holm or Benjamini-Hochberg) when testing many components.
- Report effect size with its interval, and judge practical significance against the pre-set threshold, not just the p-value.
- Check slices (length, domain, difficulty), since a component may help one segment and hurt another.
Common mistakes
- Reporting ROC AUC alone on a rare-positive problem.
- Comparing metrics at different thresholds without saying so.
- Claiming L1 "always" selects the right features, ignoring instability under correlation.
- Ablating with unequal tuning effort.
- Declaring a win from a single seed or unpaired comparison.
- Ignoring interactions by testing only one component at a time.