Skip to content
BIASED

Classification metrics

The confusion matrix and the accuracy trap, precision, recall and F1, thresholds from requirements and from costs, the ROC curve and AUC as the probability of ordering a pair correctly, the precision–recall curve and average precision.

Two kinds of error

The topic Logistic regression ended with probabilities p(x)=σ(⟨w,x⟩+b)p(x) = \sigma(\langle w, x \rangle + b), and the reliability diagram showed how to check that they can be read literally. The classifiers of Linear classifiers and surrogate losses give scores without that promise. Classes here are {0,1}\{0, 1\}, and 1 is the positive class, the one being looked for: the sick patient, the fraud, the customer about to leave.

Two questions remain. Where should the threshold go that turns a probability into a decision? And how good is the classifier? Both need a language for errors, because the two kinds of error rarely cost the same.

Write s(x)s(x) for any score that is larger for "more positive" objects: a probability, a logit, a margin. A threshold tt turns the score into a decision:

y^=[ s(x)≥t ].\hat y = [\, s(x) \ge t \,].

At a fixed threshold every test object falls into one of four cells of the confusion matrix:

y^=1\hat y = 1 y^=0\hat y = 0
y=1y = 1 true positive (TP) false negative (FN)
y=0y = 0 false positive (FP) true negative (TN)

Take the screening test from Conditional probability and Bayes' formula: base rate 0.010.01, sensitivity 0.90.9, false-positive rate 0.090.09. Among 10,00010{,}000 people, 100 are sick, so TP=90\mathrm{TP} = 90 and FN=10\mathrm{FN} = 10. Of the 9,9009{,}900 healthy, FP=891\mathrm{FP} = 891 and TN=9,009\mathrm{TN} = 9{,}009. The row sums are fixed by the data, so only two of the four counts are free. One threshold needs two numbers, one per kind of error.

The obvious single number is accuracy, the share of correct answers, (TP+TN)/n(\mathrm{TP} + \mathrm{TN})/n. Let n+n_+ and n−n_- be the numbers of positives and negatives, and π=n+/n\pi = n_+/n the prevalence. Splitting the correct answers by true class shows what accuracy weighs:

accuracy=π⋅TPn++(1−π)⋅TNn−.\text{accuracy} = \pi \cdot \frac{\mathrm{TP}}{n_+} + (1 - \pi) \cdot \frac{\mathrm{TN}}{n_-}.

It averages the success rates on the two classes with the prevalence as weights. At π=0.01\pi = 0.01 the positives contribute one hundredth of the number. The screening test is right about 91.0%91.0\% of people. A "test" that declares everyone healthy is right about 99%99\%. So any accuracy must be read against the majority baseline max⁡(π,1−π)\max(\pi, 1 - \pi), the accuracy of always predicting the larger class.

Precision, recall and F1

Two rates describe the positive class. They condition on different events:

precision=TPTP+FP=P(y=1∣y^=1),recall=TPTP+FN=P(y^=1∣y=1).\text{precision} = \frac{\mathrm{TP}}{\mathrm{TP} + \mathrm{FP}} = P(y = 1 \mid \hat y = 1), \qquad \text{recall} = \frac{\mathrm{TP}}{\mathrm{TP} + \mathrm{FN}} = P(\hat y = 1 \mid y = 1).

Precision asks how many of the alarms are real. Recall, also called sensitivity or the true positive rate (TPR), asks how many of the real cases raise an alarm. The topic Conditional probability and Bayes' formula met this pair as P(D∣+)P(D \mid +) and P(+∣D)P(+ \mid D). The screening test has recall 0.90.9, and its precision is the posterior found there, 90/981≈0.09290/981 \approx 0.092: nine alarms in ten are false.

Recall looks at the positives alone. Precision mixes in the negatives, and through them the prevalence. With the false positive rate FPR=FP/n−\mathrm{FPR} = \mathrm{FP}/n_-, Bayes' formula in this notation reads

precision=π⋅recallπ⋅recall+(1−π)⋅FPR.\text{precision} = \frac{\pi \cdot \text{recall}}{\pi \cdot \text{recall} + (1 - \pi) \cdot \mathrm{FPR}}.

The same classifier has a different precision in a population with a different prevalence.

Either rate alone is easy to make perfect. Flag everything, and recall is 1. Flag only the single most certain case, and precision is usually 1. The F1 score combines the two by the harmonic mean, which stays close to the smaller one:

F1=2⋅precision⋅recallprecision+recall=2 TP2 TP+FP+FN.F_1 = \frac{2 \cdot \text{precision} \cdot \text{recall}}{\text{precision} + \text{recall}} = \frac{2\,\mathrm{TP}}{2\,\mathrm{TP} + \mathrm{FP} + \mathrm{FN}}.

The screening test has F1≈0.167F_1 \approx 0.167, far below the arithmetic mean 0.4960.496. The counting form shows a blind spot: true negatives do not enter at all. That helps when negatives are plentiful and uninteresting, and misleads when they matter. When recall is β\beta times as important as precision, the weighted version is used:

Fβ=(1+β2) TP(1+β2) TP+β2 FN+FP.F_\beta = \frac{(1 + \beta^2)\,\mathrm{TP}}{(1 + \beta^2)\,\mathrm{TP} + \beta^2\,\mathrm{FN} + \mathrm{FP}}.

With β=2\beta = 2 the screening test gets F2=450/1381≈0.326F_2 = 450/1381 \approx 0.326.

Choosing the threshold

A confusion matrix belongs to one threshold; the classifier is the whole family of them. Raising tt flags fewer objects. Recall can only fall, because flagged positives can only drop out. Precision usually rises, but not always: each negative that drops out raises it, and each positive that drops out lowers it.

Where to stop is a decision about the application. It is made on the validation set and never on the test set, as in Validation and overfitting. Four rules are common:

  • A recall floor. Screening: find at least 95% of the sick, and among the thresholds that do, take the most precise one.
  • A precision floor. Alerts that a person must read: at least half of them must be real.
  • A budget. A call centre can call 800 of its 4,000 customers. Rank them by churn probability and call the top 800. The threshold is the 800th highest score, and the metric is the precision among the top kk, precision@k.
  • The best F1, when nothing else is specified. For calibrated probabilities the F1-maximizing threshold equals half of the maximal F1 (Lipton, Elkan and Narayanaswamy, 2014). So it is never above 0.5, and it is low when the task is hard.

Here is the effect on a synthetic dataset with 5.9% positives, a stand-in for churn. Logistic regression is trained on half of it, the threshold is tuned for F1 on a quarter, and the last quarter is the test set:

import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score, precision_recall_curve
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=30_000, n_features=10, n_informative=4,
                           weights=[0.95], flip_y=0.02, random_state=1)
X_tr, X_rest, y_tr, y_rest = train_test_split(X, y, test_size=0.5, stratify=y, random_state=0)
X_va, X_te, y_va, y_te = train_test_split(X_rest, y_rest, test_size=0.5, stratify=y_rest, random_state=0)
model = LogisticRegression().fit(X_tr, y_tr)
p_va, p_te = model.predict_proba(X_va)[:, 1], model.predict_proba(X_te)[:, 1]
print(round(np.mean((p_te >= 0.5) == y_te), 4), round(1 - y_te.mean(), 4))
P, R, T = precision_recall_curve(y_va, p_va)
t_best = T[np.argmax(2 * P[:-1] * R[:-1] / (P[:-1] + R[:-1] + 1e-12))]
print(round(t_best, 3), round(f1_score(y_te, p_te >= 0.5), 3), round(f1_score(y_te, p_te >= t_best), 3))
0.9419 0.9409
0.152 0.121 0.339

At the default threshold the accuracy beats the majority baseline by a tenth of a percent: the model finds only 30 of the 443 test positives. The threshold 0.1520.152, chosen on validation data, nearly triples the test F1, from 0.1210.121 to 0.3390.339.

Costs set the threshold

When the two errors can be priced, the threshold follows from the probabilities. Let a false negative cost cFNc_{\mathrm{FN}}, a false positive cFPc_{\mathrm{FP}}, and correct decisions nothing. Take an object with calibrated probability p=P(y=1∣x)p = P(y = 1 \mid x). Flagging it costs (1−p) cFP(1 - p)\,c_{\mathrm{FP}} on average, and passing it costs p cFNp\,c_{\mathrm{FN}}. Flag it when the first is smaller, that is, when

p>t∗=cFPcFP+cFN.p > t^* = \frac{c_{\mathrm{FP}}}{c_{\mathrm{FP}} + c_{\mathrm{FN}}}.

Equal costs give the default t∗=0.5t^* = 0.5; any other costs move it (Elkan, 2001). If a missed fraud costs 500 and a needless review of a legitimate transaction costs 5, then t∗=5/505≈0.0099t^* = 5/505 \approx 0.0099: review every transaction with a fraud probability above 1%. Price the errors of the model above this way. The total test cost is 206,615 at the threshold 0.5, 127,520 at the F1 threshold and 36,435 at t∗t^*.

The rule needs calibrated probabilities, and this is where the calibration of Logistic regression pays off. With raw scores the threshold has to be searched on validation data instead.

Imbalance is not a problem in itself. A calibrated model with the cost threshold already handles a rare class. Weighting the classes (class_weight in scikit-learn) or resampling the training set changes the probabilities the model learns, not the decision rule. With weight cc on the positives, the threshold 0.5 on the new outputs equals the threshold 1/(1+c)1/(1 + c) on the true probability. Weighting is one more way to move the threshold, and its price is probabilities that are no longer calibrated.

The ROC curve

A threshold picks one operating point. To see all of them at once, let tt fall from +∞+\infty to −∞-\infty: the classifier moves from flagging nothing to flagging everything. The ROC curve (receiver operating characteristic) plots recall, the TPR, against the FPR along the way, from (0,0)(0, 0) to (1,1)(1, 1). Both coordinates condition on the true class.

On a finite test set the curve is a staircase. Sort the objects by decreasing score and walk down the list. Each positive moves the curve up by 1/n+1/n_+, each negative moves it right by 1/n−1/n_-. A perfect ranking climbs to (0,1)(0, 1) before it moves right. A random ranking stays near the diagonal.

Eight test objects, sorted by score:

Score 0.9 0.8 0.7 0.6 0.4 0.3 0.2 0.1
Label 1 1 0 1 0 1 0 0

Here n+=n−=4n_+ = n_- = 4, and the walk goes up, up, right, up, right, up, right, right. The area under it is the AUC, the area under the curve. Put one strip of width 1/41/4 under each step to the right. The strips have heights 2/4,3/4,4/4,4/42/4, 3/4, 4/4, 4/4, so

AUC=2+3+4+416=1316=0.8125.\mathrm{AUC} = \frac{2 + 3 + 4 + 4}{16} = \frac{13}{16} = 0.8125.

The construction uses only the order of the scores. Any strictly increasing transformation of them, Platt's calibration map included, leaves the curve unchanged. The ROC curve measures ranking, not probabilities.

AUC as a ranking probability

The staircase hides a simpler reading of its area. Let P\mathcal P and N\mathcal N be the positives and the negatives of the test set. The AUC is the share of (positive, negative) pairs that the scores put in the right order, with ties counting one half:

AUC=1n+n−∑i∈P∑j∈N([si>sj]+12[si=sj]).\mathrm{AUC} = \frac{1}{n_+ n_-} \sum_{i \in \mathcal P} \sum_{j \in \mathcal N} \Big( [s_i > s_j] + \tfrac12 [s_i = s_j] \Big).

Proof. Assume first that the scores are distinct. The area is the sum of the strips under the steps to the right, one per negative jj, each of width 1/n−1/n_-. When the walk reaches negative jj, it has passed exactly the positives that score above sjs_j. So the strip has height #{i∈P:si>sj}/n+\#\{i \in \mathcal P : s_i > s_j\}/n_+, and summing over the negatives gives the double sum. A tie between a positive and a negative moves the walk diagonally, and the area under that segment is half a rectangle: a tied pair counts 12\tfrac12. □\square

In the eight-object table the four positives outrank 4,4,34, 4, 3 and 22 of the negatives: 13 pairs out of 16, as before. The double sum is the Mann–Whitney UU statistic divided by n+n−n_+ n_- (Hanley and McNeil, 1982). Let S+S_+ and S−S_- be the scores of a random positive and a random negative from the population. As both classes of an independent test sample grow, the pair share converges to

AUC=P(S+>S−)+12P(S+=S−).\mathrm{AUC} = P(S_+ > S_-) + \tfrac12 P(S_+ = S_-).

An AUC of 0.5 is a coin toss; 1 is a perfect ranking. Credit scoring reports the same number as the Gini coefficient 2 AUC−12\,\mathrm{AUC} - 1.

A worked case. Negatives score N(0,1)N(0, 1) and positives N(μ,σ2)N(\mu, \sigma^2), independently. Then S+−S−∼N(μ,1+σ2)S_+ - S_- \sim N(\mu, 1 + \sigma^2), and

AUC=Φ ⁣(μ1+σ2).\mathrm{AUC} = \Phi\!\left( \frac{\mu}{\sqrt{1 + \sigma^2}} \right).

Classifier A, with μ=1.5\mu = 1.5 and σ=1\sigma = 1, has Φ(1.5/2)≈0.856\Phi(1.5/\sqrt2) \approx 0.856. Classifier B, with the same mean and σ=2\sigma = 2, has Φ(1.5/5)≈0.749\Phi(1.5/\sqrt5) \approx 0.749.

Every pair counts the same, whether it sits at the top of the list, which someone acts on, or at the bottom, which nobody sees. That is the limit of the AUC.

The precision–recall curve

When positives are rare, the FPR divides by a huge n−n_-. A detector with recall 0.90.9 at FPR=0.01\mathrm{FPR} = 0.01 sits near the top-left corner of the ROC plane. Yet with 1,000 positives among a million negatives it raises 10,000 false alarms for 900 true ones, a precision of 0.0830.083.

The precision–recall curve plots precision against recall as the threshold moves. Its baseline is not the diagonal but the horizontal line at precision π\pi, which flagging at random achieves. Its usual summary is the average precision (AP): the precision at the rank of each positive, averaged over the positives. With y(k)y_{(k)} the label of the kk-th highest score,

AP=1n+∑k : y(k)=1precision@k.\mathrm{AP} = \frac{1}{n_+} \sum_{k \,:\, y_{(k)} = 1} \text{precision@}k.

In the eight-object table the positives sit at ranks 1, 2, 4 and 6, with precisions 1,1,3/4,4/61, 1, 3/4, 4/6, so AP≈0.854\mathrm{AP} \approx 0.854. AP is the area under the precision–recall staircase. Joining the points by straight lines would overstate the area (Davis and Goadrich, 2006).

The two curves are tied together. For fixed class sizes, one classifier's ROC curve lies above another's everywhere exactly when its precision–recall curve does. They disagree only when the curves cross, and classifiers A and B cross. Simulate them with 5% positives. A ranks better on average: AUC 0.8570.857 against 0.7500.750. But B's positives are more spread out, and some of them land far above every negative. At an FPR of 1% B already finds about 34% of the positives, A about 20%. That region is a sliver of the ROC plot and the start of the precision–recall plot, and B wins on AP, 0.440.44 against 0.340.34.

Which to report. Prefer the precision–recall curve and AP when positives are rare and only the top of the ranking is acted on: fraud alerts, retrieval, screening with limited follow-up. Prefer ROC and AUC when both classes matter, when the classifier will serve several operating points, or when the prevalence will change. ROC ignores prevalence; the same classifier's AP falls as positives become rarer. So report the prevalence next to any AP, and never compare APs across datasets with different prevalences.

Error bars and what comes next

Every number in this topic comes from a finite test set and carries sampling error. Recall is a proportion over the n+n_+ positives only. Its noise therefore depends on how many positives the test set has, not on its total size. Forty detections among 50 positives give recall 0.80.8 with a 95% Wilson interval [0.67,0.89][0.67, 0.89], as in Confidence intervals and the bootstrap. AUC, AP and F1 have no simple formula, so the bootstrap from the same topic resamples the test set. For the model of the code above, 500 resamples give AUC 0.8010.801 with the interval [0.779,0.823][0.779, 0.823] and AP 0.2660.266 with [0.229,0.310][0.229, 0.310]. The rare-class metric is the noisier one. Two models on one test set are compared with the paired bootstrap. A threshold tuned on a small validation set fits its noise as well.

These metrics judge a classifier once it is trained. They do not say which of many equally good classifiers to train. When the classes can be separated, infinitely many hyperplanes have zero training error. The logistic loss then drives the weights to infinity, as Logistic regression showed. The hinge loss of Linear classifiers and surrogate losses stops choosing once every margin exceeds 1. The next topic, Support vector machines, answers with geometry: among the separating hyperplanes it takes the one with the widest margin. Its dual will show that the answer depends on a handful of training points. Classes there switch to {−1,+1}\{-1, +1\}, as margins require.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Go deeper — optional

Code and labs do not count toward the main percentage or the certificate.

  • Precision, recall and F1 from a confusion matrixoptional

    Compute TP/FP/FN → P/R/F1; match expected numbers. Self-check in the notebook.

    ~15 min · easier on a computer · Classification metrics topic read.

    Self-check in the notebook — not part of mastery or the certificate.

Full notes

Answers are saved on the server and tied to this browser until you sign in.