Precision, recall, F1, ROC-AUC
Every guardrail, router or judge is a classifier: read its confusion matrix, set the threshold by what each error costs, and prefer precision, recall and PR-AUC over accuracy when positives are rare.
Analogy: A smoke detector: too sensitive and it shrieks at toast (low precision), too lax and it sleeps through a fire (low recall). The threshold knob trades one for the other.
How it works
- The confusion matrix counts TP, FP, FN and TN; every metric is a ratio of these four.
- Precision asks how much of what you flagged was right; recall asks how many real positives you caught.
- Raising the threshold lifts precision and lowers recall; choose it by what each error costs.
- Accuracy misleads when positives are rare: at 1% positives, "always negative" scores 99%.
- ROC-AUC ignores class balance, so it flatters rare positives; PR-AUC's random baseline is the positive rate.
Check yourself
Answer to mark it learned; your answers aren't scored.
Your injection detector shows 96% accuracy and 0.97 ROC-AUC on 10,000 real prompts, 100 of them attacks. Yet users keep complaining that normal prompts get blocked. Which number should you have looked at?
Go deeper
Full explanation
A binary classifier's errors live in the confusion matrix: true positives (TP), false positives (FP), false negatives (FN), true negatives (TN). Every metric is a ratio of these four.
- Precision = TP / (TP + FP) — of what I flagged, how much was right? Low precision = good users blocked.
- Recall (TPR) = TP / (TP + FN) — of real positives, how many did I catch? Low recall = attacks missed.
- F1 — harmonic mean of the two; collapses if either is low. Use F-beta when one error costs more.
- Accuracy misleads on imbalanced data: at 1% positives, "always negative" scores 99%.
Most models emit a score, and a threshold turns it into a decision: raise it and precision rises while recall falls. Choose it by what each error costs, on validation data. Threshold-free summaries:
- ROC-AUC — TPR vs FPR across all thresholds; the chance a random positive outscores a random negative. Insensitive to class balance, so it flatters tasks where positives are rare.
- PR-AUC (average precision) — precision vs recall; its random baseline equals the positive rate. Prefer it when positives are rare.
In AI systems, use them for Guardrails: input, output, action and moderation (recall on harm vs false-block rate), Model routing & cascades (escalate to the big model or not), intent classifiers, and an LLM-as-a-judge against human labels.
Code Pick a threshold from a recall target
import numpy as np
from sklearn.metrics import (average_precision_score, classification_report,
precision_recall_curve, roc_auc_score)
# Labels: 1 = prompt injection (~2% of prompts); s_*: detector probabilities
(y_val, s_val), (y_test, s_test) = load_splits() # numpy arrays
print(f"ROC-AUC: {roc_auc_score(y_val, s_val):.3f}") # flattering on imbalance
print(f"PR-AUC : {average_precision_score(y_val, s_val):.3f}") # read it against...
print(f"PR-AUC random baseline: {y_val.mean():.3f}") # ...the positive rate
# Threshold comes from a product requirement, not 0.5:
# "catch >= 95% of injections" -> highest threshold that keeps recall >= 0.95
prec, rec, thr = precision_recall_curve(y_val, s_val)
i = np.where(rec[:-1] >= 0.95)[0][-1] # recall only falls as the threshold rises
t = thr[i]
print(f"threshold={t:.3f} precision={prec[i]:.2f} recall={rec[i]:.2f}")
# Report on held-out data, never on the split you tuned the threshold on
y_pred = (s_test >= t).astype(int)
print(classification_report(y_test, y_pred, target_names=["benign", "injection"], digits=3))Real example
A prompt-injection detector is evaluated on 10,000 real prompts, 100 of them attacks. At threshold 0.5 it catches 90 (recall 0.90) and flags 400 benign prompts, so precision is 90/490 ≈ 0.18 — yet accuracy is ~96%, which hid the problem. ROC-AUC is 0.97; PR-AUC is 0.41 against a 0.01 baseline. The team keeps recall ≥ 0.9 but sends flagged prompts to a stricter, tool-less mode instead of blocking them, so a false positive costs a weaker answer, not an angry user.
Trade-offs +3 · −3
+ You gain
- A shared language for any yes/no decision: guardrails, routers, judges, moderation.
- Precision and recall map directly to product costs: false blocks vs missed harm.
- Threshold-free AUCs compare models before you commit to an operating point.
− You pay
- Needs labeled data with enough positives: rare classes need large eval sets.
- A single number (F1, AUC) hides the operating point you actually ship.
- Multi-class needs a macro vs micro choice, and each tells a different story.
Use it when
Any component that makes a discrete decision — guardrail, moderation, router, intent or PII detector, an LLM judge vs human labels — and whenever you must choose a threshold.
Avoid it when
Open-ended generation quality (use rubric judges or human eval) or ranking quality where position matters (use recall@k, MRR, nDCG).
Numbers to know 4
- F1 = 2PR / (P + R): precision 0.9 with recall 0.5 gives F1 ≈ 0.64, not the 0.7 average.
- Base rate: at 1% prevalence, 99% recall with a 1% false-positive rate still gives only ~50% precision.
- Random baselines: ROC-AUC = 0.5 at any class balance; PR-AUC = the positive rate (e.g. 0.01).
- At 1% positives, an always-negative model scores 99% accuracy and 0 recall.
Common pitfalls 4
- Shipping the default 0.5 threshold instead of choosing it from the cost of each error.
- Tuning the threshold on the test set: the reported precision and recall become optimistic.
- Comparing PR-AUC across datasets with different positive rates: its baseline moves with prevalence.
- One global number when recall differs by language, user segment or attack type.
Interview questions 2
Answer out loud first, then reveal.
Your moderation model has 0.98 ROC-AUC. Is it good?Show answer
Not necessarily. ROC-AUC barely reacts to imbalance: if 0.5% of content is harmful, catching 90% of it with a 2% false-positive rate means only ~18% of flagged items are actually harmful. I'd look at the PR curve and PR-AUC against the 0.005 baseline, then at precision and recall at the threshold we'd actually ship, sliced by language and content type. The threshold is a cost decision: for severe harm, recall comes first and human review absorbs the false positives.
How would you evaluate a router that sends queries to a small or a large model?Show answer
It's a classifier where "needs the large model" is the positive class. A false negative sends a hard query to the small model, which is a quality failure; a false positive just costs money. I'd label a few hundred real queries by whether the small model's answer passes, plot the precision-recall curve of the router's score, and pick the threshold that keeps recall on hard queries around 0.95 while saving the most traffic. Then I'd confirm quality and cost online with an A/B test.