Module contents
Lesson 7 of 24Core 100 min

Evaluation metrics: thresholds, rankings and costs

Organize metrics by what they measure: threshold-based decisions (confusion matrix, precision, recall, F1), threshold-independent ranking quality (ROC, AUC, precision-recall curves), and regression errors. Derive the optimal threshold from a cost matrix and address class imbalance using weights, resampling and prior correction. Probability metrics (log-loss, Brier) are covered in depth in the calibration lessons.

After this lesson you can

  • Compute the confusion matrix and derived metrics, including macro, micro and weighted averages.
  • Construct an ROC curve and prove that AUC is the probability that a positive scores above a negative.
  • Choose between ROC and precision-recall according to prevalence and explain why PR is more informative for rare classes.
  • Derive the optimal decision threshold for a probabilistic classifier from a cost matrix.
  • Address imbalance with class weights, resampling and prior correction, and measure their effects.
  • Choose regression metrics consistent with the loss and recognize their pathologies.

Before you start

Motivation: 99% accuracy that detects nothing

You have an analyzer scoring each function in a repository by its risk of containing a vulnerability, and an evaluation set of 10,000 manually reviewed functions, of which 100 are vulnerable: a prevalence of 1%. Compare two models.

  • The lazy model always says “not vulnerable.” It is correct in 9900 of 10,000 cases: accuracy 0.990.99. It finds no vulnerabilities.
  • A real model detects 80% of vulnerable functions (80 of 100) and falsely raises the alarm on 2% of healthy ones (198 of 9900). It is correct in 80+9702=978280 + 9702 = 9782 cases: accuracy 0.97820.9782, worse than the lazy model. Of its 80+198=27880 + 198 = 278 alerts, only 28.8% are real vulnerabilities.

By accuracy the lazy model wins. By recall (how many vulnerable functions you find), the real model wins decisively. By precision (how many alerts are true), the real model is mediocre: over seven in ten requested reviews are wasted. None of these figures is wrong. They answer different questions, and choosing the wrong question is the most common way to mislead yourself when evaluating a model.

This lesson organizes metrics by what they measure:

  1. Decisions at a threshold. Once the threshold is fixed, the model is a hard classifier and everything is summarized by a confusion matrix: precision, recall, specificity, F1F_1 and their multiclass averages.
  2. Ranking quality, without a threshold: the ROC curve, its area (which turns out to be a probability of ordering a pair correctly), and the precision-recall curve, which responds to prevalence when ROC does not.
  3. Decisions with costs. If a false negative costs fifty times more than a false positive, the threshold is not a knob adjusted by eye: it follows from a calculation, provided probabilities mean what they say.
  4. Class imbalance, using weights, resampling and probability correction, measured in a lab with 1% positives.
  5. Regression errors: which prediction each metric rewards, continuing the regression losses and functionals elicited by each loss from the module’s first lesson.

Probability metrics (log-loss, Brier) and calibration have their own later lessons; here they appear only where needed.

Threshold decisions: the confusion matrix

Most probabilistic classifiers, such as logistic regression, return a score s(x)∈Rs(\vb{x}) \in \R rather than a class (a probability, logit, or distance to the hyperplane). To decide, set a threshold τ\tau and predict

y^(x)=1[s(x)≥τ].\hat{y}(\vb{x}) = \ind[s(\vb{x}) \ge \tau].

In an evaluation set with PP positives and NN negatives, each example falls into one of four cells.

The right-hand column matters. Recall, specificity and FPR are conditioned on the true class: they describe how the model treats positives and negatives separately and do not change when their relative numbers change. Precision is conditioned on the prediction, and by Bayes’ theorem, with prevalence π=P(Y=1)\pi = \Pr(Y = 1),

precisioˊn=P(Y=1∣Y^=1)=π TPRπ TPR+(1−π) FPR.\text{precisión} = \Pr(Y = 1 \given \hat{Y} = 1) = \frac{\pi\,\mathrm{TPR}}{\pi\,\mathrm{TPR} + (1 - \pi)\,\mathrm{FPR}}.

The same recall and FPR give very different precision depending on π\pi: in the opening example, TPR=0.8\mathrm{TPR} = 0.8 and FPR=0.02\mathrm{FPR} = 0.02 give 0.008/(0.008+0.0198)=0.2880.008/(0.008 + 0.0198) = 0.288 with π=0.01\pi = 0.01, and 0.9760.976 with π=0.5\pi = 0.5. Accuracy also depends on π\pi, because P(Y^=Y)=π TPR+(1−π)(1−FPR)\Pr(\hat{Y} = Y) = \pi\,\mathrm{TPR} + (1 - \pi)(1 - \mathrm{FPR}) averages the two rates weighted by prevalence: with π=0.01\pi = 0.01, specificity weighs 99 times more than recall. That is what hurt the real model against the lazy one. Balanced accuracy, (TPR+TNR)/2(\mathrm{TPR} + \mathrm{TNR})/2, removes that weighting.

F1F_1 combines precision pp and recall rr with the harmonic mean, 2pr/(p+r)2pr/(p + r), which stays close to the smaller value: with p=0.1p = 0.1 and r=0.9r = 0.9 it gives 0.180.18, not the arithmetic mean’s 0.50.5. Notice VN\mathrm{VN} does not appear: adding a million correctly classified negatives does not change F1F_1. That is useful when negatives are “everything else” (healthy functions, irrelevant pages), and a drawback when they matter. The parameter of Fβ=(1+β2)pr/(β2p+r)F_\beta = (1 + \beta^2)pr/(\beta^2 p + r) has a precise meaning, going back to van Rijsbergen’s effectiveness measure in information retrieval: differentiation gives ∂Fβ/∂p=∂Fβ/∂r\partial F_\beta/\partial p = \partial F_\beta/\partial r exactly when r/p=βr/p = \beta. With β=2\beta = 2, while recall is less than twice precision, a point of recall raises F2F_2 more than a point of precision; F2F_2 is common when a false negative is serious (screening, security), and F0.5F_{0.5} when false alarms are serious.

InteractiveThe threshold moves the entire confusion matrix
Sample scores (60 positives, 240 negatives) and threshold
−3−2−1012345τ = 1.60 → positive
  • positives (class 1)
  • negatives (class 0)
  • threshold τ
Confusion matrix
predicted positive
predicted negative
actual +
TP
32
correct
FN
28
missed
actual −
FP
15
false alarms
TN
225
correct
ROC: recall versus FPR
AUC = 0.893
PR: precision versus recall
chance: π = 0.2AP = 0.710
1.60
Class separation
Precision TP/(TP+FP)0.681
Recall TP/P0.533
Specificity TN/N0.938
F10.598
Accuracy0.857
AUC (independent of τ)0.893
Average precision (independent of τ)0.710
A sample from the binormal model used throughout the lesson: 60 positives with scores N(d′,1)\Normal(d', 1) and 240 negatives with N(0,1)\Normal(0, 1). Drag threshold τ\tau across the histogram. Observe three things: the entire confusion matrix changes at once (what one cell gains, its row neighbor loses); the threshold point moves along the ROC and PR curves, which stay fixed; and AUC and average precision do not depend on τ\tau. Move the threshold far right: what happens to accuracy? Change separation and request another sample: how much do curves vary with just 60 positives?

The interactive illustrates the idea organizing the rest of the lesson: a threshold metric evaluates one point; curves evaluate every point the model can reach. If the threshold is not yet decided (because it depends on costs, review capacity, or production prevalence), single-point metrics conflate the model with one possible configuration.

Multiclass: macro, micro and weighted

With KK classes, the confusion matrix is C∈NK×K\mat{C} \in \N^{K\times K} where CklC_{kl} counts examples of true class kk predicted as ll (rows: truth; columns: prediction, the scikit-learn convention). Treat each class against the rest: VPk=Ckk\mathrm{VP}_k = C_{kk}, FPk=∑l≠kClk\mathrm{FP}_k = \sum_{l \ne k} C_{lk} (its column off the diagonal), and FNk=∑l≠kCkl\mathrm{FN}_k = \sum_{l \ne k} C_{kl} (its row). This gives precision, recall and F1F_1 per class, with three ways to summarize them:

  • Macro: simple average of the KK per-class metrics. Every class has equal weight, so a poorly classified rare class shows up. Macro recall is multiclass balanced accuracy.
  • Weighted: average weighted by each class’s support nk/nn_k/n. Frequent classes carry more weight.
  • Micro: sum VPk\mathrm{VP}_k, FPk\mathrm{FP}_k and FNk\mathrm{FN}_k across classes, then calculate the metric once. Every example weighs the same.

In multiclass classification with one label per example, each error is both an FP (for the predicted class) and an FN (for the true class), so ∑kFPk=∑kFNk=n−∑kVPk\sum_k \mathrm{FP}_k = \sum_k \mathrm{FN}_k = n - \sum_k \mathrm{VP}_k: micro precision, micro recall and micro F1F_1 coincide and equal accuracy exactly. Weighted recall adds nothing new either: ∑k(nk/n)(VPk/nk)=∑kVPk/n\sum_k (n_k/n)(\mathrm{VP}_k/n_k) = \sum_k \mathrm{VP}_k/n. One detail: “macro F1F_1” has two definitions in use, the mean of per-class F1F_1 scores (scikit-learn’s) and the F1F_1 of macro precision and macro recall; these generally differ. Always say which you use.

[ ]Multiclass confusion matrix and its averagesBrowser
import numpy as np
from sklearn.metrics import confusion_matrix, precision_recall_fscore_support, accuracy_score

def matriz_confusion(y, yhat, K):
    C = np.zeros((K, K), dtype=int)
    np.add.at(C, (y, yhat), 1)          # fila = clase real, columna = predicha
    return C

def por_clase(C):
    vp = np.diag(C).astype(float)
    predichos = C.sum(axis=0)           # VP + FP de cada clase
    soporte = C.sum(axis=1)             # VP + FN de cada clase
    prec = np.divide(vp, predichos, out=np.zeros_like(vp), where=predichos > 0)
    sens = np.divide(vp, soporte, out=np.zeros_like(vp), where=soporte > 0)
    f1 = np.divide(2 * prec * sens, prec + sens, out=np.zeros_like(vp), where=prec + sens > 0)
    return prec, sens, f1, soporte

def promedios(C):
    prec, sens, f1, soporte = por_clase(C)
    w = soporte / soporte.sum()
    vp = np.trace(C)
    fp = C.sum() - vp                   # una etiqueta por ejemplo: suma de FP = suma de FN
    micro = vp / (vp + fp)
    return {"macro": (prec.mean(), sens.mean(), f1.mean()),
            "ponderado": (w @ prec, w @ sens, w @ f1),
            "micro": (micro, micro, micro)}

# un clasificador de tráfico con tres clases muy desequilibradas
clases = ["benigno", "sospechoso", "malicioso"]
C_obj = np.array([[850, 40, 10],
                  [ 20, 55,  5],
                  [  5,  7,  8]])
y = np.repeat(np.repeat(np.arange(3), 3), C_obj.ravel())      # clase real de cada ejemplo
yhat = np.repeat(np.tile(np.arange(3), 3), C_obj.ravel())     # clase predicha
C = matriz_confusion(y, yhat, 3)
assert (C == confusion_matrix(y, yhat)).all()

prec, sens, f1, sop = por_clase(C)
for k in range(3):
    print(f"{clases[k]:10s} soporte={sop[k]:4d}  precisión={prec[k]:.3f}  sensibilidad={sens[k]:.3f}  F1={f1[k]:.3f}")
print(f"exactitud = {accuracy_score(y, yhat):.3f}")
for modo, (p, r, f) in promedios(C).items():
    pk, rk, fk, _ = precision_recall_fscore_support(y, yhat, average={"ponderado": "weighted"}.get(modo, modo))
    print(f"{modo:9s} P={p:.3f} R={r:.3f} F1={f:.3f}   sklearn: P={pk:.3f} R={rk:.3f} F1={fk:.3f}")

The malicious class, with 20 examples, has recall 0.4000.400 and precision 0.3480.348 (F1=0.372F_1 = 0.372): the model misses 12 of 20 and is wrong two times out of three when it predicts that class. The weighted average (F1=0.918F_1 = 0.918) barely sees this because the class weighs 2%. Micro equals accuracy, 0.9130.913, as shown above, as does weighted recall. Only macro (F1=0.645F_1 = 0.645, recall 0.6770.677) reflects that two of the three classes perform poorly. If the rare class is what matters, weighted or micro averages hide exactly what you wanted to measure.

Rankings: the ROC curve

Moving the threshold traces a family of classifiers. The ROC (receiver operating characteristic, a name inherited from radar signal detection theory) plots them all at once.

Properties that follow from the definition:

  • It runs from (0,0)(0, 0) (threshold +∞+\infty: nothing positive) to (1,1)(1, 1) (threshold −∞-\infty: everything positive) and increases monotonically in both coordinates.
  • It does not depend on prevalence, because both rates are conditioned on class.
  • It is invariant under strictly increasing score transformations: ss, s3s^3 and σ(s)\sigmoid(s) rank identically and have the same ROC. ROC sees order, not values. A model with implausible but perfectly ordered probabilities has a perfect ROC.
  • The diagonal corresponds to a score independent of class: TPR(τ)=FPR(τ)\mathrm{TPR}(\tau) = \mathrm{FPR}(\tau) for every τ\tau, AUC =0.5= 0.5. A curve below the diagonal is a good curve with its sign reversed.
  • Every point on the segment between two reachable points is reachable: randomly use one classifier or the other in the appropriate proportion. Thus the ROC’s convex hull is also reachable and underlies ROCCH classifier selection, summarized by Fawcett (2006). Tie segments are exactly of this kind: crossing a tie diagonally is equivalent to random tie-breaking.
  • If S+S^+ and S−S^- have densities f1f_1 and f0f_0, the ROC slope at threshold τ\tau is  ⁣dTPR/ ⁣dFPR=f1(τ)/f0(τ)\dd\mathrm{TPR}/\dd\mathrm{FPR} = f_1(\tau)/f_0(\tau), the likelihood ratio. It will return when we discuss costs.

AUC is the probability of ordering a pair correctly

The area has an interpretation that makes it the quintessential ranking metric.

Proof

We prove the case where the distribution function F0F_0 of S−S^- is continuous; you will handle the empirical case with ties in a guided exercise. As τ\tau drops from +∞+\infty to −∞-\infty, FPR(τ)=1−F0(τ)\mathrm{FPR}(\tau) = 1 - F_0(\tau) increases continuously from 0 to 1 and the area is the Stieltjes integral

AUC=∫TPR  ⁣dFPR=∫RP(S+≥τ)  ⁣dF0(τ).\mathrm{AUC} = \int \mathrm{TPR}\,\dd\mathrm{FPR} = \int_{\R} \Pr(S^+ \ge \tau)\,\dd F_0(\tau).

(Where F0F_0 is constant, the ROC has vertical segments with no area, ignored by the integral.) By independence and Fubini’s theorem, the last integral is E[P(S+≥S−∣S−)]=P(S+≥S−)\E[\Pr(S^+ \ge S^- \given S^-)] = \Pr(S^+ \ge S^-). Since S−S^- has no atoms, P(S+=S−)=E[P(S−=S+∣S+)]=0\Pr(S^+ = S^-) = \E[\Pr(S^- = S^+ \given S^+)] = 0, and P(S+≥S−)=P(S+>S−)\Pr(S^+ \ge S^-) = \Pr(S^+ > S^-), the stated formula with a zero tie term.

∎

The theorem says AUC is the probability that, given a random positive and negative, the model scores the positive higher, with ties worth half a win. The empirical estimator averages over PNPN pairs, the normalized UU statistic: AUC and the Mann-Whitney test use the same calculation. This gives AUC a complete error theory (it is a U-statistic, unbiased for the population probability, with calculable variance; DeLong, DeLong and Clarke-Pearson (1988) gave the standard method for comparing AUCs of models evaluated on the same cases, revisited when comparing models with paired tests).

InteractiveAUC counts pairs
Scores
0.000.250.500.751.00+−
ROC square = grid of 8 negatives × 6 positives (descending score)
0.760.620.550.470.350.220.140.050.920.810.700.550.430.30
  • positive (rows)
  • negative (columns)
  • correctly ordered
  • reversed
  • tie
  • ROC
all 48 pairs
Pairs compared48 of 48
Correctly ordered35
Reversed12
Ties (worth ½)1
(correct + ½ ties) / total pairs0.7396
Area under drawn ROC0.7396
AUC final0.7396
The ROC square divided into a grid: each column is a negative and each row a positive, both ordered from highest to lowest score. Cell (positive ii, negative jj) lies below the ROC exactly when the positive beats the negative. Initially you see the result: green cells and half a yellow cell make up the area under the ROC. Play the animation: it walks through 48 pairs column by column, coloring each cell (green for a correctly ordered pair, red for an inverted one, a yellow half-triangle for a tie), and draws the ROC above each completed column. Compare the two highlighted readouts: they coincide after each column. Then request a random sample.

Why the grid works: the first negative in the list (the highest-scoring one) is first to cross the falling threshold, and ROC steps right by 1/N1/N. By then every higher-scoring positive has crossed too, so without ties the ROC height over that column is (number of positives beating it)/P/P; a tie makes the step diagonal, leaving half a cell below the curve. Column area is 1/(PN)1/(PN) times that count: pairs won by the positive. In the lesson’s example (6 positives and 8 negatives), 35 pairs are correctly ordered, 12 inverted and one tied at 0.550.55, so AUC=(35+0.5)/48=0.7396\mathrm{AUC} = (35 + 0.5)/48 = 0.7396. ROC cells are the Mann-Whitney pairs.

The binormal model

An explicit model helps reasoning and is used by every interactive in the lesson: scores S−∼N(0,1)S^- \sim \Normal(0, 1) and S+∼N(d′,1)S^+ \sim \Normal(d', 1), with d′d' the separation in standard deviations (the d′d' of signal detection theory). Since FPR(τ)=1−Φ(τ)\mathrm{FPR}(\tau) = 1 - \Phi(\tau) and TPR(τ)=1−Φ(τ−d′)\mathrm{TPR}(\tau) = 1 - \Phi(\tau - d'), eliminating τ\tau gives the entire curve:

TPR=Φ(d′+Φ−1(FPR)),\mathrm{TPR} = \Phi\big(d' + \Phi^{-1}(\mathrm{FPR})\big),

and by the theorem, since S+−S−∼N(d′,2)S^+ - S^- \sim \Normal(d', 2),

AUC=P(S+−S−>0)=Φ(d′/2).\mathrm{AUC} = \Pr(S^+ - S^- > 0) = \Phi\big(d'/\sqrt{2}\big).

An AUC of 0.950.95 corresponds to d′=2 Φ−1(0.95)=2.326d' = \sqrt{2}\,\Phi^{-1}(0.95) = 2.326. With different variances, S+∼N(μ1,σ12)S^+ \sim \Normal(\mu_1, \sigma_1^2), the same calculation gives Φ((μ1−μ0)/σ02+σ12)\Phi\big((\mu_1 - \mu_0)/\sqrt{\sigma_0^2 + \sigma_1^2}\big).

Computing ROC: sort once

Computing TPR\mathrm{TPR} and FPR\mathrm{FPR} separately at every threshold costs O(n)\bigO(n) per threshold and O(n2)\bigO(n^2) overall. This is unnecessary: sorting scores descending means lowering the threshold to the next distinct score only adds examples with that score, so one pass accumulating VP\mathrm{VP} and FP\mathrm{FP} gives the entire curve in O(nlog⁡n)\bigO(n \log n) (sorting dominates). This is algorithm 1 of Fawcett (2006). The tricky detail is ties: emit a point only when the score changes, so all tied examples enter together and the curve moves diagonally. Processing them one by one makes the curve depend on the arbitrary order left by sorting: positives first yields an optimistic curve and negatives first a pessimistic one. You will see this in the lab and fix it in an exercise.

Multiclass AUC

With KK classes and a probability vector per example, there are two standard generalizations, both implemented by scikit-learn’s roc_auc_score:

  • One versus rest (multi_class="ovr"): for each class kk, binary AUC of score p^k\hat{p}_k with class kk positive and the rest negative; then take a macro or prevalence-weighted average. Since the composition of “the rest” changes with prevalence, it depends on prevalence.
  • One versus one (multi_class="ovo"): the measure of Hand and Till (2001). For each pair k≠lk \ne l, A(k∣l)A(k \given l) is the probability that an example of class kk has higher p^k\hat{p}_k than one of class ll, and 12(A(k∣l)+A(l∣k))\tfrac{1}{2}(A(k \given l) + A(l \given k)) is averaged over the K(K−1)/2K(K - 1)/2 pairs. It uses examples from only two classes at a time and does not depend on prevalence.

What AUC does not say

AUC averages over all thresholds, including those you would never use: with 1% positives and capacity to review 50 alerts a day, only the leftmost part of ROC matters, and two models with the same AUC can differ greatly there (their curves cross). Nor does it say anything about calibration, because it is invariant to increasing score transformations. As you will now see, it does not reflect how hard positives are to find when they are rare.

Precision-recall curves

The PR curve is not monotonic: as the threshold falls, recall never decreases, but precision rises or falls depending on whether a positive or negative enters, producing a sawtooth in small samples. Its baseline is not diagonal: a random-scoring classifier has precision π\pi at every threshold, so the reference is the horizontal line P=π\mathrm{P} = \pi and average precision of random scores is π\pi (in the population; slightly more in a finite sample), not 0.50.5.

For a fixed evaluation set, ROC and PR contain the same information: each point (FPR,TPR)(\mathrm{FPR}, \mathrm{TPR}) with TPR>0\mathrm{TPR} > 0 converts to a PR point with R=TPR\mathrm{R} = \mathrm{TPR} and the earlier Bayes formula for precision, and vice versa. Davis and Goadrich (2006) also showed that with fixed PP and NN, one curve dominates another in ROC space if and only if it dominates in PR space. But when curves cross, the summary changes: maximizing AUC does not maximize PR area, and the ordering of two models can reverse.

The practical difference is prevalence. ROC does not depend on π\pi; PR does, strongly, through precision.

InteractiveSame ROC, very different PR
ROC: independent of π
false-positive raterecall
PR with π = 1.0 %
precisionchance = π
  • ROC (same for every π)
  • PR at selected π
  • PR at π = 0.5, reference
  • operating point
1.0 %
Separation ability
0.80
AUC0.950
False-positive rate at the point0.0688
Precision at the point0.105
False alarms per true positive8.52
Average precision (chance: π)0.402 (0.010)
With AUC 0.95, only one in 10 flagged cases is positive.
The binormal model: each class's score distribution is fixed and only prevalence π\pi changes. The ROC curve does not move. PR sinks toward its random baseline, P=π\mathrm{P} = \pi; the dashed curve is PR with π=0.5\pi = 0.5 for reference. The marked point is the threshold at the indicated recall: it never moves on ROC, but does on PR. Start with π=1 %\pi = 1\,\% and AUC 0.95: read how many false alarms occur per hit. Raise prevalence to 50% and lower it to 0.1%. Then try AUC 0.99: is it enough to rescue precision at π=0.1 %\pi = 0.1\,\%?

The next cell calculates the interactive’s numbers for the binormal model with AUC 0.950.95, at recall 0.80.8.

[ ]Prevalence sinks PR without moving ROCBrowser
import numpy as np
from scipy.stats import norm

d = np.sqrt(2) * norm.ppf(0.95)                 # AUC = Phi(d / sqrt 2) = 0.95
t = np.linspace(-8, d + 8, 20001)               # umbrales de mayor a menor recorrido
tpr, fpr = norm.sf(t - d), norm.sf(t)
auc = -np.sum(np.diff(fpr) * (tpr[1:] + tpr[:-1]) / 2)
t08 = d - norm.ppf(0.8)                         # umbral con sensibilidad 0.8
fpr08 = norm.sf(t08)
print(f"d' = {d:.3f}   AUC = {auc:.4f}   FPR en sensibilidad 0.8 = {fpr08:.4f}")
for pi in [0.5, 0.1, 0.01, 0.001]:
    prec = pi * tpr / (pi * tpr + (1 - pi) * fpr)
    pm = -np.sum(np.diff(tpr) * prec[1:])       # precisión media = integral de P dR
    p08 = pi * 0.8 / (pi * 0.8 + (1 - pi) * fpr08)
    print(f"pi = {pi:<6}  precisión en R=0.8: {p08:.4f}   FP por VP: {(1 - pi) * fpr08 / (pi * 0.8):6.2f}   PM: {pm:.4f}")

With π=0.5\pi = 0.5, the point at recall 0.80.8 has precision 0.920.92 and average precision 0.950.95. With π=1 %\pi = 1\,\%, the same classifier, with the same ROC and a false-positive rate of only 0.0690.069, has precision 0.1050.105: 8.5 false alarms per hit. With π=0.1 %\pi = 0.1\,\%, precision is 0.0120.012 and average precision 0.130.13. This is the situation described by Saito and Rehmsmeier (2015): with imbalanced data a visual ROC reading can mislead about the reliability of positive predictions, due to an intuitive but incorrect interpretation of specificity: a “small” FPR is multiplied by a huge number of negatives. PR directly measures the fraction of correct positive predictions and therefore better anticipates performance in use. Their warning applies to many published studies evaluating ROC on highly imbalanced data.

This does not make ROC inferior. If deployment prevalence is unknown or will change, ROC (and AUC) describe separation ability without mixing in π\pi, while PR from an evaluation set with different prevalence would mislead in the opposite direction. A useful rule: use ROC to compare ranking ability; use PR at real prevalence to know the value of your alerts.

Why PR is not linearly interpolated

In ROC space the segment between two attainable points is attainable. In PR space it is not. Between consecutive thresholds AA and BB, randomization moves counts in a straight line: with x∈[0,VPB−VPA]x \in [0, \mathrm{VP}_B - \mathrm{VP}_A] additional positives, VP=VPA+x\mathrm{VP} = \mathrm{VP}_A + x and FP=FPA+kx\mathrm{FP} = \mathrm{FP}_A + kx, where k=(FPB−FPA)/(VPB−VPA)k = (\mathrm{FP}_B - \mathrm{FP}_A)/(\mathrm{VP}_B - \mathrm{VP}_A) is the number of negatives entering per positive. Precision along the segment is

P(x)=VPA+xVPA+FPA+(1+k)x,\mathrm{P}(x) = \frac{\mathrm{VP}_A + x}{\mathrm{VP}_A + \mathrm{FP}_A + (1 + k)x},

a hyperbola in recall (VPA+x)/P(\mathrm{VP}_A + x)/P, not a line. With a=VPAa = \mathrm{VP}_A and c=VPA+FPAc = \mathrm{VP}_A + \mathrm{FP}_A, differentiation gives P′(x)=(c−(1+k)a)/(c+(1+k)x)2\mathrm{P}'(x) = (c - (1 + k)a)/(c + (1 + k)x)^2 and P′′(x)=−2(1+k) P′(x)/(c+(1+k)x)\mathrm{P}''(x) = -2(1 + k)\,\mathrm{P}'(x)/(c + (1 + k)x): when precision decreases along the segment (P′<0\mathrm{P}' < 0, occurring when more negatives enter per positive than the cumulative ratio, k>FPA/VPAk > \mathrm{FP}_A/\mathrm{VP}_A, typical for a concave ROC), P′′>0\mathrm{P}'' > 0, the curve is convex and lies below the chord. Linear interpolation overestimates achievable precision, as Davis and Goadrich showed. The effect is negligible with one point per example and grows with few thresholds: a tree with few leaves, rounded scores, or many ties.

[ ]PR trapezoids versus correct interpolationBrowser
import numpy as np
from sklearn.metrics import precision_recall_curve, average_precision_score, auc, roc_curve

rng = np.random.default_rng(3)
n1, n0 = 200, 4000
s = np.r_[rng.normal(1.8, 1, n1), rng.normal(0, 1, n0)]
y = np.r_[np.ones(n1), np.zeros(n0)]

def area_pr_correcta(y, s, n1, n0):
    """Área bajo la PR alcanzable: interpola VP y FP en línea recta entre umbrales (Davis y Goadrich)."""
    fpr, tpr, _ = roc_curve(y, s, drop_intermediate=False)
    VP, FP = tpr * n1, fpr * n0
    area = 0.0
    for a in range(len(VP) - 1):
        if VP[a + 1] == VP[a]:
            continue                                   # tramo sin positivos nuevos: no suma sensibilidad
        k = (FP[a + 1] - FP[a]) / (VP[a + 1] - VP[a])
        x = np.linspace(0, VP[a + 1] - VP[a], 401)
        den = VP[a] + FP[a] + (1 + k) * x
        P = (VP[a] + x) / np.where(den > 0, den, 1.0)
        if VP[a] + FP[a] == 0:
            P[0] = P[1]                                # en el origen la precisión es el límite 1/(1+k)
        area += np.sum((P[1:] + P[:-1]) / 2 * np.diff(x)) / n1
    return area

for nombre, sc in [("continua", s), ("5 niveles", np.clip(np.round(s), -1, 3))]:
    prec, rec, _ = precision_recall_curve(y, sc)
    print(f"{nombre:10s} umbrales={len(prec) - 1:5d}  PM={average_precision_score(y, sc):.4f}  "
          f"trapecios={auc(rec, prec):.4f}  correcta={area_pr_correcta(y, sc, n1, n0):.4f}")

With continuous scores (4200 thresholds) the three figures agree nearly to the third decimal: 0.4810.481, 0.4800.480 and 0.4800.480. With the same scores rounded to 5 levels, trapezoids give 0.4980.498 when truly achievable area is 0.4120.412: an overestimate of 8.6 points that can decide a model comparison. Stepwise average precision (0.3580.358) is more conservative than the correct area, because each segment uses precision at its final endpoint, lowest when precision decreases. This is why scikit-learn computes AP without interpolation and warns that PR trapezoids can be overly optimistic.

Cost-sensitive decisions: the optimal threshold

Until now the threshold was a free parameter. If errors have costs, it ceases to be one. Let cFPc_{FP} be the cost of a false positive (wasted review of a healthy function) and cFNc_{FN} the cost of a false negative (a vulnerability reaching production), with correct decisions costing 0. If the model returns the true probability p(x)=P(Y=1∣X=x)p(\vb{x}) = \Pr(Y = 1 \given \vb{X} = \vb{x}) (a conditional probability), each decision has a conditional expected cost:

predecir 1: (1−p(x)) cFP,predecir 0: p(x) cFN.\text{predecir } 1: \ (1 - p(\vb{x}))\,c_{FP}, \qquad \text{predecir } 0: \ p(\vb{x})\,c_{FN}.

This is the cost-sensitive decision threshold, Elkan’s (2001) central result; he also notes that adding a constant to the costs for the same true class does not change the decision, so differences c10−c00c_{10} - c_{00} and c01−c11c_{01} - c_{11} suffice. The proof is short and you will reconstruct it in a guided exercise; the idea is that total cost is the average over x\vb{x} of conditional cost, minimized by choosing the best decision for each x\vb{x} separately. With cFN=49 cFPc_{FN} = 49\,c_{FP}, p∗=0.02p^* = 0.02: reviewing any function with over 2% probability of vulnerability is worthwhile.

The assumption matters: p(x)p(\vb{x}) must be the true probability. If a model ranks well but its numbers are not probabilities, the rule p∗p^* applies the right threshold on the wrong scale. Probabilities meaning what they say is called calibration, covered in later lessons.

InteractiveOptimal cost-sensitive threshold
Expected cost per case versus threshold tt applied to each model’s probability
0.20.40.60.81.00.0010.010.10.50.90.990.999p* = 0.091
  • calibrated
  • trained at 50%
  • overconfident
  • rule p∗p^* (circles: cost at p∗p^*)
  • minimum achievable cost
10
1
Prevalence π\pi
Rule p∗p^*0.0909
Optimal threshold, calibrated0.091
Optimal threshold, trained at 50%0.831
Optimal threshold, overconfident0.0099
Cost at p∗p^*, calibrated0.0949 (+0 %)
Cost at p∗p^*, trained at 50%0.4257 (+349 %)
Cost at p∗p^*, overconfident0.1106 (+17 %)
Minimum cost (same for all three)0.0949
All three models rank identically: their curves share the same shifted minimum. Only the calibrated model reaches it at p∗p^*.
Three models built on the binormal model with AUC 0.95. All rank identically because they are increasing functions of the same score: one is calibrated; another was trained as if prevalence were 0.5; the third is overconfident (its logit is twice the true one). Each curve is expected cost per case versus threshold tt applied to that model's probability, on a logit scale. The vertical line is rule p∗p^*; filled dots are the true minimum of each curve; circles show the cost of using p∗p^*. Change costs and prevalence: which curve always has its minimum on the line? Does the minimum height change?
[ ]Expected cost with three identically ranking modelsBrowser
import numpy as np
from scipy.stats import norm
from scipy.optimize import minimize_scalar
from scipy.special import expit, logit

d = np.sqrt(2) * norm.ppf(0.95)
pi, c_fp, c_fn = 0.02, 1.0, 10.0
p_star = c_fp / (c_fp + c_fn)

def coste(s):
    """Coste esperado por caso si se predice positivo cuando la puntuación binormal supera s."""
    return c_fp * (1 - pi) * norm.sf(s) + c_fn * pi * norm.cdf(s - d)

# umbral de puntuación s que corresponde a un umbral t (en logit) sobre la probabilidad de cada modelo
modelos = {
    "calibrado":          lambda lt: (lt - logit(pi) + d * d / 2) / d,   # logit q = d s - d²/2 + logit pi
    "entrenado al 50 %":  lambda lt: (lt + d * d / 2) / d,               # logit q = d s - d²/2
    "sobreconfiado":      lambda lt: (lt / 2 - logit(pi) + d * d / 2) / d,  # logit q = 2 logit p
}
print(f"p* = {p_star:.4f}   siempre negativo: {c_fn * pi:.3f}   siempre positivo: {c_fp * (1 - pi):.3f}")
for nombre, s_de in modelos.items():
    r = minimize_scalar(lambda lt: coste(s_de(lt)), bounds=(-12, 12), method="bounded", options={"xatol": 1e-10})
    c_p = coste(s_de(logit(p_star)))
    print(f"{nombre:18s} umbral óptimo = {expit(r.x):.4f}   coste mínimo = {r.fun:.5f}   "
          f"coste con p* = {c_p:.5f} (+{100 * (c_p / r.fun - 1):.0f} %)")

With π=2 %\pi = 2\,\%, cFP=1c_{FP} = 1 and cFN=10c_{FN} = 10, the rule gives p∗=0.0909p^* = 0.0909 and is exact for the calibrated model. The model trained at 50% reaches the same minimum cost, 0.09490.0949 per case, but at threshold 0.830.83: applying p∗p^* costs 0.4260.426 per case, 349% more, worse even than never flagging anything (0.20.2). The overconfident model’s optimum is 0.00990.0099 and it loses 17% using p∗p^*. The general lesson: miscalibration does not change how well a model can decide (the curve’s minimum), but where its good threshold lies. With calibrated probabilities the threshold follows from costs; otherwise search for it with data or recalibrate first.

The operating point in ROC space

The same calculation has a geometric interpretation. The expected cost per case at an ROC point is

C=cFP(1−π) FPR+cFN π (1−TPR),C = c_{FP}(1 - \pi)\,\mathrm{FPR} + c_{FN}\,\pi\,(1 - \mathrm{TPR}),

so equal-cost points lie on lines TPR=m FPR+cte\mathrm{TPR} = m\,\mathrm{FPR} + \text{cte} with slope m=cFP(1−π)/(cFN π)m = c_{FP}(1 - \pi)/(c_{FN}\,\pi), and the best point is the last touched by such a line as it moves upward and left: on a smooth concave ROC, where the curve’s slope equals mm. That slope is the likelihood ratio f1(τ)/f0(τ)f_1(\tau)/f_0(\tau), and by Bayes the posterior probabilities satisfy p/(1−p)=π1−π f1/f0=cFP/cFNp/(1 - p) = \tfrac{\pi}{1 - \pi}\,f_1/f_0 = c_{FP}/c_{FN}, that is, p=p∗p = p^*: both derivations give the same threshold. Geometry shows where the optimum falls: with high prevalence and similar costs, mm is small and the optimum lies at the top right; with rare positives, mm grows like (1−π)/π(1 - \pi)/\pi (unless cFN/cFPc_{FN}/c_{FP} compensates) and the optimum moves to ROC’s far left, the region barely weighted by AUC. It has a practical advantage: it works even for an uncalibrated model because it uses only counts.

Other operating-point criteria apply when costs cannot be quantified: minimum recall (“find 95% of vulnerabilities”), an alert budget (“review the 50 highest-scoring functions per day,” setting a quantile threshold), or the Neyman-Pearson formulation (maximum recall with FPR≤α\mathrm{FPR} \le \alpha). Choose all of these using validation data, never test data: optimizing a threshold on the test set makes it another training set and its figure no longer estimates production behavior (the same principle as holdout validation).

Class imbalance

One percent positives is not itself a disease of the model. If the classifier is trained with a loss estimating probabilities (log-loss is a proper scoring rule) and there is enough data, it also learns p(x)p(\vb{x}) for the rare class, and the cost rule handles decisions. Real problems are different: metrics hiding the rare class (accuracy), the default 0.50.5 threshold (optimal only if cFN=cFPc_{FN} = c_{FP}), variance from few positives, and some algorithms dedicating little capacity to them. Elkan (2001) summarizes that for standard Bayesian and decision-tree methods, changing training class proportions has little effect on the resulting classifier, and recommends training on data as received and deciding afterward using probabilities and costs.

Nevertheless rebalancing techniques are used daily, and we need to know exactly what they do to probabilities.

The first three change the effective prevalence seen in training, and thus the probabilities the model learns. The calculation is exact in the population. For weights: the minimizer of weighted log-loss at a point x\vb{x} maximizes w1 plog⁡q+w0(1−p)log⁡(1−q)w_1\,p\log q + w_0(1 - p)\log(1 - q) over qq; differentiation gives w1p/q=w0(1−p)/(1−q)w_1 p/q = w_0(1 - p)/(1 - q), so

q(x)=w1 p(x)w1 p(x)+w0 (1−p(x)),q1−q=w1w0⋅p1−p.q(\vb{x}) = \frac{w_1\,p(\vb{x})}{w_1\,p(\vb{x}) + w_0\,(1 - p(\vb{x}))}, \qquad \frac{q}{1 - q} = \frac{w_1}{w_0}\cdot\frac{p}{1 - p}.

Weights multiply odds by w1/w0w_1/w_0. Undersampling negatives at fraction β\beta is the same with w0=βw_0 = \beta, w1=1w_1 = 1 (in expectation, with less data), and replicating positives rr times is the same with w1=rw_1 = r. With class_weight="balanced" in a binary problem, w1/w0=n0/n1=(1−π)/πw_1/w_0 = n_0/n_1 = (1 - \pi)/\pi: the model learns odds for a population at 50% prevalence. An often overlooked consequence: applying threshold 0.50.5 to that model is equivalent to predicting positive when p(x)≥πp(\vb{x}) \ge \pi, which the cost theorem says is optimal only if cFN/cFP=(1−π)/πc_{FN}/c_{FP} = (1 - \pi)/\pi. With π=1 %\pi = 1\,\%, rebalancing and using 0.50.5 declares a false negative costs 99 false positives, whether you realize it or not.

The inverse operation is the correction of Saerens, Latinne and Decaestecker (2002).

Proof

By Bayes, p′(y∣x)=p(x∣y) πy′/p′(x)p'(y \given \vb{x}) = p(\vb{x} \given y)\,\pi'_y/p'(\vb{x}), hence p(x∣y)=p′(y∣x) p′(x)/πy′p(\vb{x} \given y) = p'(y \given \vb{x})\,p'(\vb{x})/\pi'_y. Substituting in p(y∣x)=p(x∣y) πy/∑y′p(x∣y′) πy′p(y \given \vb{x}) = p(\vb{x} \given y)\,\pi_y/\sum_{y'}p(\vb{x} \given y')\,\pi_{y'}, the factor p′(x)p'(\vb{x}) cancels, giving the formula. In the binary case, the ratio between y=1y = 1 and y=0y = 0 gives odds: p1−p=p′1−p′⋅π/π′(1−π)/(1−π′)\frac{p}{1 - p} = \frac{p'}{1 - p'}\cdot\frac{\pi/\pi'}{(1 - \pi)/(1 - \pi')}, and taking logs gives the second form.

∎

The assumption, called label shift, is exactly what holds when you cause the prevalence change by classwise resampling. Saerens et al. also propose an EM algorithm to estimate unknown new priors from predictions on unlabeled deployment data. Elkan (2001) uses the same calculation in reverse: if you want a resampled model’s usual threshold p0p_0 to correspond to the cost threshold p∗p^*, multiply the number of negatives by p∗1−p∗⋅1−p0p0\frac{p^*}{1 - p^*}\cdot\frac{1 - p_0}{p_0}.

Lab: imbalance and thresholds

A synthetic problem with 1% positives: six Gaussian features of variance 1, shifted for positives by μ=(1,0.8,0.6,0.4,0.2,0)\boldsymbol{\mu} = (1, 0.8, 0.6, 0.4, 0.2, 0). Since both classes are Gaussian with the same covariance, logistic regression is well specified (its true logit is linear), so differences among methods come from imbalance handling rather than an unsuitable model. Training, validation and test are independent samples; costs are cFP=1c_{FP} = 1 and cFN=50c_{FN} = 50, so p∗=1/51p^* = 1/51.

[ ]Lab: weights, undersampling, SMOTE and prior correctionBrowser
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, average_precision_score

rng = np.random.default_rng(0)
mu = np.array([1.0, 0.8, 0.6, 0.4, 0.2, 0.0])
def muestra(n, pi=0.01):
    y = (rng.random(n) < pi).astype(int)
    X = rng.normal(size=(n, len(mu))) + np.outer(y, mu)
    return X, y

Xtr, ytr = muestra(30_000)
Xva, yva = muestra(30_000)
Xte, yte = muestra(100_000)
print("positivos en entrenamiento, validación y test:", ytr.sum(), yva.sum(), yte.sum())

c_fp, c_fn = 1.0, 50.0
p_star = c_fp / (c_fp + c_fn)
def coste(y, yhat):
    return (c_fp * np.sum((yhat == 1) & (y == 0)) + c_fn * np.sum((yhat == 0) & (y == 1))) / len(y)

def corregir(p, pi_entreno, pi_real):
    """Corrección de priors binaria: desplaza el logit."""
    z = np.log(p / (1 - p)) + np.log(pi_real / (1 - pi_real)) - np.log(pi_entreno / (1 - pi_entreno))
    return 1 / (1 + np.exp(-z))

def smote(Xpos, n_nuevos, k=5):
    d2 = ((Xpos[:, None, :] - Xpos[None, :, :]) ** 2).sum(-1)
    np.fill_diagonal(d2, np.inf)
    vecinos = np.argsort(d2, axis=1)[:, :k]
    i = rng.integers(len(Xpos), size=n_nuevos)
    j = vecinos[i, rng.integers(k, size=n_nuevos)]
    u = rng.random((n_nuevos, 1))
    return Xpos[i] + u * (Xpos[j] - Xpos[i])

LR = lambda **kw: LogisticRegression(C=1e4, max_iter=1000, **kw)   # casi sin regularización
pi_tr = ytr.mean()
modelos = {}
modelos["tal cual"] = LR().fit(Xtr, ytr)
modelos["class_weight"] = LR(class_weight="balanced").fit(Xtr, ytr)
pos, neg = np.flatnonzero(ytr == 1), np.flatnonzero(ytr == 0)
sub = np.r_[pos, rng.choice(neg, size=len(pos), replace=False)]      # submuestreo hasta el 50 %
modelos["submuestreo"] = LR().fit(Xtr[sub], ytr[sub])
n_sint = len(neg) - len(pos)
Xs = np.r_[Xtr, smote(Xtr[pos], n_sint)]
ys = np.r_[ytr, np.ones(n_sint, dtype=int)]
modelos["SMOTE"] = LR().fit(Xs, ys)
p_te = {k: m.predict_proba(Xte)[:, 1] for k, m in modelos.items()}
[ ]Test resultsBrowser
filas = [("tal cual", "umbral 0.5", p_te["tal cual"], 0.5),
         ("tal cual", "umbral p*", p_te["tal cual"], p_star)]
for k in ["class_weight", "submuestreo", "SMOTE"]:
    filas.append((k, "umbral 0.5", p_te[k], 0.5))
    filas.append((k, "umbral p*", p_te[k], p_star))
    filas.append((k, "corregido + p*", corregir(p_te[k], 0.5, pi_tr), p_star))

# referencia: el clasificador de Bayes con el logit verdadero
logit_real = Xte @ mu - mu @ mu / 2 + np.log(0.01 / 0.99)
p_bayes = 1 / (1 + np.exp(-logit_real))

print(f"{'modelo':13s} {'decisión':15s}  AUC     PM     media p  sens.  prec.  coste")
for nombre, regla, p, t in filas + [("Bayes", "umbral p*", p_bayes, p_star)]:
    yhat = (p >= t).astype(int)
    sens = yhat[yte == 1].mean()
    prec = yte[yhat == 1].mean() if yhat.any() else float("nan")
    print(f"{nombre:13s} {regla:15s} {roc_auc_score(yte, p):.4f} {average_precision_score(yte, p):.4f} "
          f"{p.mean():.4f}  {sens:.3f}  {prec:.3f}  {coste(yte, yhat):.4f}")
print(f"no marcar nada: coste {c_fn * yte.mean():.4f}")

Read the table by columns.

  • AUC and average precision are nearly equal across all four models and close to the Bayes classifier’s. Weights, undersampling and SMOTE did not improve ranking: with a well-specified model they only change the probability scale (corrections are increasing, so they preserve order and leave AUC and AP unchanged).
  • Mean probability reveals the scale. The untreated model predicts 0.00980.0098 on average, the real prevalence; the three rebalanced models average between 0.310.31 and 0.330.33, over 30 times more: they think they live in a 50% population.
  • Cost separates decisions. Threshold 0.50.5 on the untreated model flags almost nothing (recall 0.0090.009) and costs 0.49950.4995 per case, almost the same as never flagging (0.5040.504). The same model with p∗p^* costs 0.31500.3150, close to the Bayes classifier’s 0.31260.3126. For rebalanced models, p∗p^* works badly: they flag almost everything (recall 1.0001.000, precision 0.0100.010) and cost between 0.960.96 and 0.980.98, because inflated probabilities are compared with a threshold intended for real probabilities. At 0.50.5 they land between these (0.3460.346 to 0.3490.349), optimal for cFN/cFP≈99c_{FN}/c_{FP} \approx 99, not 50. After prior correction, all three return to a mean near 0.010.01 and with p∗p^* cost between 0.31680.3168 and 0.31880.3188, 0.6% to 1.2% above the untreated model.

What about choosing the threshold directly on validation data, minimizing empirical cost? This is the alternative when calibration is untrustworthy. Its price is variance: with 280 validation positives, empirical cost is a noisy step function of the threshold.

[ ]Validation threshold versus p*: twenty repetitionsBrowser
p_va = modelos["tal cual"].predict_proba(Xva)[:, 1]
def umbral_validacion(p, y):
    """Umbral con el menor coste empírico: ordenar una vez y probar todos los cortes en O(n log n)."""
    orden = np.argsort(-p)
    vp = np.cumsum(y[orden])                         # VP si se marcan los k primeros
    fp = np.arange(1, len(p) + 1) - vp
    c = c_fp * fp + c_fn * (y.sum() - vp)
    return p[orden][np.argmin(c)]

t_val = umbral_validacion(p_va, yva)
yhat = lambda t: (p_te["tal cual"] >= t).astype(int)
print(f"esta validación: umbral {t_val:.4f}, coste en test {coste(yte, yhat(t_val)):.4f}   p* = {p_star:.4f}: {coste(yte, yhat(p_star)):.4f}")
costes = []
for r in range(20):                                  # otras 20 validaciones independientes del mismo tamaño
    Xv, yv = muestra(30_000)
    tv = umbral_validacion(modelos["tal cual"].predict_proba(Xv)[:, 1], yv)
    costes.append(coste(yte, yhat(tv)))
costes = np.array(costes)
print(f"umbral de validación en 20 repeticiones: coste en test medio {costes.mean():.4f}, "
      f"rango [{costes.min():.4f}, {costes.max():.4f}]; peor que p* en {np.sum(costes > coste(yte, yhat(p_star)))} de 20")

This validation’s threshold (0.02440.0244) costs 0.32040.3204 on test versus 0.31500.3150 for p∗=0.0196p^* = 0.0196. It is not bad luck: across 20 independent validations of the same size, empirical threshold cost averages 0.31740.3174, loses to p∗p^* in 15 of 20, and reaches 0.33560.3356 in the worst. With a well-calibrated model, p∗p^* has no selection variance and generally beats the validation-selected threshold; empirical selection pays off when calibration is doubtful, and then smoothing it (cross-validation, more validation data) or, better, recalibrating is advisable.

The last experiment illustrates a common error: resampling before splitting.

[ ]Oversampling before splitting: data leakageBrowser
from sklearn.tree import DecisionTreeClassifier

X, y = muestra(20_000)
rep = np.r_[np.arange(len(y)), np.repeat(np.flatnonzero(y == 1), 20)]   # cada positivo, 21 veces
perm = rng.permutation(len(rep))
a, b = rep[perm[: len(rep) // 2]], rep[perm[len(rep) // 2:]]          # dividir DESPUÉS de replicar
arbol = DecisionTreeClassifier(random_state=0).fit(X[a], y[a])
pv = arbol.predict_proba(X[b])[:, 1]
print(f"mal (replicar y luego dividir): AUC de validación = {roc_auc_score(y[b], pv):.3f}, PM = {average_precision_score(y[b], pv):.3f}")
print(f"   el mismo árbol en test limpio: AUC = {roc_auc_score(yte, arbol.predict_proba(Xte)[:, 1]):.3f}")

perm = rng.permutation(len(y))
a, b = perm[:10_000], perm[10_000:]                                       # dividir ANTES de replicar
a_rep = np.r_[a, np.repeat(a[y[a] == 1], 20)]
arbol = DecisionTreeClassifier(random_state=0).fit(X[a_rep], y[a_rep])
pv = arbol.predict_proba(X[b])[:, 1]
print(f"bien (dividir y luego replicar): AUC de validación = {roc_auc_score(y[b], pv):.3f}, PM = {average_precision_score(y[b], pv):.3f}")

Replicating before splitting leaves exact copies of almost all validation positives in training, and an unpruned tree memorizes them: validation promises an AUC near 1 when the same tree barely beats chance on clean data. Split first and validation tells the truth. SMOTE has the same issue because synthetic points interpolate positives that would end up on both sides of the split. This is a case of data leakage, covered in depth next lesson along with cross-validation, where resampling must happen inside each fold.

Regression metrics

Regression has no threshold; the question is which point prediction each metric rewards. The module’s first lesson answered for losses: squared error is minimized by the conditional mean and absolute error by the median. Evaluation metrics inherit that property, and those that are not a familiar loss hide their own functional.

What each rewards:

  • RMSE: the square root of mean squared error is an increasing transformation, so it shares the minimizer: the conditional mean. It is in units of yy and heavily weights large errors; one outlier can dominate it.
  • MAE: the conditional median. More robust, but indifferent to small versus large errors in the tail.
  • R2R^2: on a fixed set it is 1−MSE/Var⁡^(y)1 - \mathrm{MSE}/\widehat{\Var}(y), a decreasing transformation of MSE with the same minimizer. Its normalization depends on evaluation-set variance: the same model has a higher R2R^2 on a more dispersed test set, so do not compare it across sets. Outside training it may be negative (simply predict worse than the test mean) and does not equal squared correlation between yy and y^\hat{y}. A constant cc has R2=−(yˉ−c)2/Var⁡^(y)≤0R^2 = -(\bar{y} - c)^2/\widehat{\Var}(y) \le 0.
  • MAPE: a scale-independent relative error that is easy to communicate, but infinite if any yi=0y_i = 0 and explosive near zero. Its minimizer is not the median: Gneiting (2011) showed that for y>0y > 0, MAPE is consistent with the median of the distribution with density proportional to f(y)/yf(y)/y, never above the median (weight 1/y1/y shifts mass toward small values). MAPE rewards underprediction. See it without calculation: for fixed yy and nonnegative predictions, an underestimate costs at most 100%, while overestimates have no ceiling.
  • sMAPE: designed to correct that asymmetry, it partly reverses it. With y=100y = 100, predicting 150150 costs 2⋅50/250=40 %2\cdot 50/250 = 40\,\% and predicting 5050 costs 2⋅50/150=66.7 %2\cdot 50/150 = 66.7\,\%: same absolute error, different penalty, now against underprediction. Hyndman and Koehler (2006) review these pathologies and propose scaling errors by a naive predictor’s errors (MASE) when comparing series with different scales.
InteractiveWhich constant does each metric reward?
Density of Y and the three “best” constants
0.51.01.52.02.53.0
Each metric’s excess above its own minimum (0 = optimum)
+25 %+50 %+75 %+100 %0.51.01.52.02.53.0
  • RMSE (minimum at mean)
  • MAE (minimum at median)
  • MAPE (minimum below median)
  • your prediction cc
1.60
0.75
RMSE(c)1.184
MAE(c)0.881
MAPE(c)129.3 %
R²(c)−0.057
RMSE minimum: mean eσ2/2e^{\sigma^2/2}1.325
MAE minimum: median1.000
MAPE minimum: e−σ2e^{-\sigma^2}0.570
A positive skewed variable, Y∼LogNormal(0,σ2)Y \sim \mathrm{LogNormal}(0, \sigma^2), and a constant prediction cc. Above, density with three optimal constants: mean eσ2/2e^{\sigma^2/2} (RMSE), median 11 (MAE), and e−σ2e^{-\sigma^2} (MAPE). Below, each metric's relative excess over its minimum. Drag cc: no value is optimal for all three at once. Increase σ\sigma: how far apart do they move? Notice the R2R^2 of a constant.

The interactive’s model has exact minimizers. For Y∼LogNormal(0,σ2)Y \sim \mathrm{LogNormal}(0, \sigma^2), normalized density f(y)/yf(y)/y is another lognormal, LogNormal(−σ2,σ2)\mathrm{LogNormal}(-\sigma^2, \sigma^2) (multiplying by 1/y=e−log⁡y1/y = e^{-\log y} shifts the logarithm’s mean by −σ2-\sigma^2), whose median is e−σ2e^{-\sigma^2}. The cell checks this by numerically minimizing each metric on a sample, including sMAPE, which has no closed form.

[ ]The best constant for each metricBrowser
import numpy as np
from scipy.optimize import minimize_scalar

rng = np.random.default_rng(7)
s = 0.75
y = rng.lognormal(0.0, s, 50_000)

metricas = {
    "RMSE":  lambda c: np.sqrt(np.mean((y - c) ** 2)),
    "MAE":   lambda c: np.mean(np.abs(y - c)),
    "MAPE":  lambda c: 100 * np.mean(np.abs(y - c) / y),
    "sMAPE": lambda c: 100 * np.mean(2 * np.abs(y - c) / (y + c)),
}
teoria = {"RMSE": np.exp(s**2 / 2), "MAE": 1.0, "MAPE": np.exp(-s**2), "sMAPE": float("nan")}
for nombre, f in metricas.items():
    r = minimize_scalar(f, bounds=(0.05, 5), method="bounded")
    print(f"{nombre:6s} mejor constante = {r.x:.3f}   teoría = {teoria[nombre]:.3f}   valor = {r.fun:.3f}")

# el R^2 de las constantes y el MAPE cerca de cero
var = np.mean((y - y.mean()) ** 2)
for c in [y.mean(), 1.0, np.exp(-s**2)]:
    print(f"R² de la constante {c:.3f}: {1 - np.mean((y - c) ** 2) / var:+.3f}")
y_cero = np.r_[y[:999], 1e-6]                    # un solo valor real casi nulo entre 1000
print(f"MAPE de la mediana con 1000 valores: {100 * np.mean(np.abs(y[:1000] - 1) / y[:1000]):.1f} %;"
      f" cambiando uno por 1e-6: {100 * np.mean(np.abs(y_cero - 1) / y_cero):.1f} %")

The sample confirms theory: optimal constants are 1.3151.315, 0.9950.995 and 0.5710.571, versus population mean e0.28125=1.325e^{0.28125} = 1.325 (RMSE), median 11 (MAE) and e−0.5625=0.570e^{-0.5625} = 0.570 (MAPE); differences are sampling noise. For this distribution sMAPE chooses almost the median (0.9950.995), but not by a general principle: it corresponds to no simple functional. These are “best predictions” of the same distribution under reasonable metrics, and MAPE’s is 57% lower than RMSE’s. If evaluated on MAPE, a model trained with squared error will systematically predict above what the metric rewards: evaluation metric and training loss should estimate the same functional. Sample-mean R2R^2 is exactly 0, and that of any other constant is negative. The final two lines show the zero pathology: one true value of 10−610^{-6} among a thousand takes the median’s MAPE from 69.6 %69.6\,\% to over 100 000 %100\,000\,\%.

Implementation from scratch and sklearn.metrics equivalents

You already have the multiclass confusion matrix. Remaining are ROC, AUC in two ways, and average precision. Start with a naive ROC that processes examples one at a time to see what it does with ties.

[ ]Naive ROC, Mann-Whitney AUC and average precisionBrowser
import numpy as np
from sklearn.metrics import roc_auc_score, average_precision_score

def roc_ingenua(y, s, positivos_primero=False):
    """Un punto por EJEMPLO tras ordenar; los empates quedan en el orden en que los deje la ordenación."""
    y = np.asarray(y)
    clave = (-np.asarray(s, float), -y if positivos_primero else y)
    orden = np.lexsort(clave[::-1])                   # ordena por -s y, a igualdad, por la clase
    ys = y[orden]
    vp = np.r_[0, np.cumsum(ys)]
    fp = np.r_[0, np.cumsum(1 - ys)]
    return fp / fp[-1], vp / vp[-1]

def area_trapecios(x, h):
    return float(np.sum(np.diff(x) * (h[1:] + h[:-1]) / 2))

def rangos_medios(s):
    """Rangos 1..n con los empates promediados, en O(n log n)."""
    s = np.asarray(s, float)
    orden = np.argsort(s, kind="mergesort")
    ss = s[orden]
    ini = np.r_[0, np.flatnonzero(np.diff(ss)) + 1]
    fin = np.r_[ini[1:], len(s)]
    r = np.empty(len(s))
    r[orden] = np.repeat((ini + fin + 1) / 2, fin - ini)
    return r

def auc_mann_whitney(y, s):
    y = np.asarray(y)
    n1 = y.sum(); n0 = len(y) - n1
    U = rangos_medios(s)[y == 1].sum() - n1 * (n1 + 1) / 2
    return U / (n1 * n0)

def precision_media(y, s):
    """PM = suma de (R_k - R_{k-1}) P_k, con un punto por puntuación distinta."""
    y = np.asarray(y); s = np.asarray(s, float)
    _, grupo = np.unique(-s, return_inverse=True)            # grupo 0 = la puntuación más alta
    vp = np.cumsum(np.bincount(grupo.ravel(), weights=y))    # VP acumulados por umbral
    marcados = np.cumsum(np.bincount(grupo.ravel()))         # VP + FP acumulados
    R = np.r_[0, vp / y.sum()]
    return float(np.sum(np.diff(R) * vp / marcados))

rng = np.random.default_rng(1)
n = 200_000
y = (rng.random(n) < 0.05).astype(int)
s = np.round(rng.normal(size=n) + 1.5 * y, 1)     # redondeo a 0.1: muchísimos empates
for primero in [True, False]:
    f, t = roc_ingenua(y, s, positivos_primero=primero)
    print(f"ROC ingenua, empates con los {'positivos' if primero else 'negativos'} delante: AUC = {area_trapecios(f, t):.4f}")
print(f"Mann-Whitney con rangos medios:  AUC = {auc_mann_whitney(y, s):.4f}   sklearn: {roc_auc_score(y, s):.4f}")
print(f"precisión media desde cero:      PM  = {precision_media(y, s):.4f}   sklearn: {average_precision_score(y, s):.4f}")
s_cont = s + rng.normal(scale=1e-9, size=n)       # sin empates, la versión ingenua ya es correcta
f, t = roc_ingenua(y, s_cont)
print(f"sin empates: ingenua {area_trapecios(f, t):.4f}   Mann-Whitney {auc_mann_whitney(y, s_cont):.4f}   sklearn {roc_auc_score(y, s_cont):.4f}")

With 200,000 examples and scores rounded to one decimal, naive ROC gives two different AUCs depending on tie order, 0.86500.8650 with positives first and 0.84910.8491 with negatives first, while the correct value (Mann-Whitney with average ranks, counting each tie as half a pair), 0.85710.8571, matches scikit-learn and lies exactly between them: the optimistic version counts every tied pair as a win, the pessimistic one as a loss. Without ties all three agree. Writing the correct ROC, which groups ties in one step, is an exercise at the end. The table summarizes equivalent scikit-learn functions:

From scratchsklearn.metricsNotes
matriz_confusionconfusion_matrix(y, yhat)rows: true class; columns: predicted class
por_clase, promediosprecision_recall_fscore_support(..., average=None / "macro" / "micro" / "weighted"), classification_reportzero_division decides what to do with 0/0
FβF_\betafbeta_score(y, yhat, beta=2)
balanced accuracybalanced_accuracy_scoremacro recall
ROC by sweeproc_curve(y, s)default drop_intermediate=True removes collinear points
auc_mann_whitneyroc_auc_score(y, s); multiclass with multi_class="ovr" or "ovo""ovo" is the Hand and Till measure
precision_mediaaverage_precision_score(y, s), precision_recall_curvesteps, no interpolation
trapezoidal areaauc(x, y)general: on PR it overestimates with few thresholds
RMSE, MAE, R2R^2, MAPEmean_squared_error (and its square root), mean_absolute_error, r2_score, mean_absolute_percentage_errorsklearn MAPE is a fraction, not a percentage

Common mistakes

Exercises

NumericPrecision of a good detector
A detector has recall 0.90.9 and specificity 0.950.95 and is applied to a population with 1% positives. What is its precision (the fraction of its alerts that are true positives)?
QuizWhich averages equal accuracy?
In a multiclass problem with one label per example, which metrics always equal accuracy?

More than one answer may be correct.

ProofEmpirical AUC counts pairs
Prove: Consider a sample with positive scores s1+,…,sP+s^+_1, \dots, s^+_P and negative scores s1−,…,sN−s^-_1, \dots, s^-_N, and its empirical ROC, joining by straight segments the points (FP(τ)/N,VP(τ)/P)(\mathrm{FP}(\tau)/N, \mathrm{VP}(\tau)/P) at distinct score thresholds τ\tau in descending order, starting at (0,0)(0, 0). If X+X^+ and X−X^- are drawn uniformly and independently from positives and negatives, then AUC=P(X+>X−)+12P(X+=X−)\mathrm{AUC} = \Pr(X^+ > X^-) + \tfrac12\Pr(X^+ = X^-).
0
Consider the ROC segment adding threshold τ\tau: the examples scoring exactly τ\tau, namely aa positives and bb negatives. Before the segment the curve is at (F/N,V/P)(F/N, V/P), with VV the number of positives and FF the number of negatives scoring above τ\tau.

Step 1 of 4. What area lies under that segment?

ProofThe cost-minimizing threshold
Prove: If p(x)=P(Y=1∣X=x)p(\vb{x}) = \Pr(Y = 1 \given \vb{X} = \vb{x}) and costs are cFP>0c_{FP} > 0, cFN>0c_{FN} > 0 and zero for correct decisions, the rule minimizing E[c(Y^,Y)]\E[c(\hat{Y}, Y)] predicts positive if and only if p(x)>cFP/(cFP+cFN)p(\vb{x}) > c_{FP}/(c_{FP} + c_{FN}) (at equality either decision works).
0
A decision rule is any function y^:x↦{0,1}\hat{y}: \vb{x} \mapsto \{0, 1\}.

Step 1 of 5. How do you decompose the expected cost of a rule y^\hat{y}?

NumericA threshold with costs for correct decisions
Manually reviewing a flagged function costs 1 (whether vulnerable or not). An unflagged vulnerability costs 50, and an unflagged healthy function costs 0. With calibrated probabilities, what is optimal threshold p∗p^*?
NumericPrecision between two PR points
With 100 positives, a classifier has two consecutive thresholds: at AA, 40 true positives and 10 false positives; at BB, 80 and 120. Random tie-breaking reaches any intermediate ROC point. What precision is reached at recall 0.60.6?
NumericWhat a 0.5 threshold declares
At 1% prevalence, you train logistic regression with class_weight='balanced' and flag positive when its probability exceeds 0.50.5. Assuming the model exactly learns rescaled odds, for what cost ratio cFN/cFPc_{FN}/c_{FP} is that decision optimal?
NumericUndoing undersampling
You train a calibrated model retaining 10% of negatives and all positives. For a new case, the model returns 0.50.5. What is the real probability it is positive?
QuizTwo fraud detectors
Two fraud detectors are evaluated on the same set, with 0.2% positives. The first has AUC 0.970.97 and the second 0.960.96. Which statement is correct?
QuizTrue values near zero
You predict a building's hourly electricity consumption, which can be nearly zero overnight. Which regression metric is undefined or explosive when true values are near zero?
CodeROC and AUC with ties
Implement roc_curve_and_auc(y, scores), returning (fpr, tpr, auc): empirical ROC arrays, beginning at (0, 0) and then one point per distinct score in descending order (tied examples enter together), and trapezoidal area. It must match sklearn.metrics.roc_curve(y, scores, drop_intermediate=False) and roc_auc_score, and run in O(nlog⁡n)O(n \log n): no Python loops over examples or comparisons of all pairs.
import numpy as np

def roc_curve_and_auc(y, scores):
  """Devuelve (fpr, tpr, auc) con un punto por puntuación distinta y los empates juntos."""
  y = np.asarray(y)
  scores = np.asarray(scores, dtype=float)
  # tu código: ordenar de mayor a menor, localizar dónde cambia la puntuación,
  # acumular VP y FP en esos puntos y añadir el (0, 0) inicial
  fpr = np.array([0.0, 1.0])
  tpr = np.array([0.0, 1.0])
  auc = 0.0
  return fpr, tpr, auc
Shift+Enter to run
CodeMulticlass prior correction
Implement corregir_priors(P, pi_entreno, pi_real): P is an n×Kn\times K matrix of posterior probabilities from a model trained with priors pi_entreno (a vector of length KK), and the function returns the n×Kn\times K matrix of probabilities corrected to priors pi_real, assuming only priors change (label shift). Each row must sum to 1.
import numpy as np

def corregir_priors(P, pi_entreno, pi_real):
  """Corrige las probabilidades a posteriori de los priors de entrenamiento a los reales."""
  P = np.asarray(P, dtype=float)
  # tu código
  return P
Shift+Enter to run

Summary

Key idea
A metric answers a question: at a fixed threshold, how many correct decisions and errors of each kind; without a threshold, how well the model ranks; with costs, which decision pays off, requiring calibrated probabilities. Choosing the metric means choosing the question.
  • The confusion matrix summarizes one threshold. Recall, specificity and FPR are class-conditional and prevalence-independent; precision, accuracy and F1F_1 are not. In multiclass, micro and weighted averages count examples (micro equals accuracy) and macro counts classes.
  • ROC sweeps all thresholds, does not depend on π\pi and sees only ranking. Its area is the probability of correctly ordering a positive-negative pair, with ties worth half: the normalized Mann-Whitney statistic. Compute it in O(nlog⁡n)\bigO(n \log n) by grouping ties.
  • PR, with baseline π\pi, shows what ROC hides when positives are rare: an AUC of 0.95 can coexist with precision 0.1 if π=1 %\pi = 1\,\%. Stepwise average precision summarizes it; straight-line interpolation overestimates area.
  • With calibrated probabilities, the expected-cost-minimizing threshold is p∗=cFP/(cFP+cFN)p^* = c_{FP}/(c_{FP} + c_{FN}). A miscalibrated model reaches the same minimum cost at another threshold; choose the operating point on validation, never test.
  • Weights, undersampling, oversampling and SMOTE multiply odds; they do not improve a well-specified model’s ranking, and probabilities should be corrected using Saerens’ formula before use. Always resample after splitting.
  • In regression RMSE rewards the mean, MAE the median and MAPE a value below the median; R2R^2 depends on evaluation-set variance and MAPE explodes near zero. Metric and training loss should estimate the same thing.