Simple Algorithm
Machine Learning · Descent · 22 min

Measuring Performance

Accuracy, precision, recall, ROC curves and choosing what to optimize.

One number often decides which model ships, so choosing that number is a modeling decision in its own right. This lesson builds every common metric from the confusion matrix, shows exactly how each depends on the threshold and the class balance, extends them to many classes and to regression, and ends with the scores that judge probabilities themselves.

What you’ll learn

  • Derive accuracy, precision, recall, specificity, the F-scores and the Matthews correlation from a confusion matrix, and express precision through prevalence with Bayes' rule.
  • Turn misclassification costs into an expected-cost criterion, and explain how ROC and precision–recall curves summarize all thresholds and how each reacts to prevalence.
  • Compute macro, micro and weighted averages for multiclass problems, and the MSE, RMSE, MAE, R2R^2 and MAPE of a regression, knowing which statistic each one rewards.
  • Prove that log loss and the Brier score are strictly proper, and separate calibration from discrimination.
  • Choose a metric from the decision the model supports.

The confusion matrix and its rates

Take binary labels y∈{0,1}y\in\{0,1\}, with 11 the positive class, and a classifier y^(x)=1{s(x)≥t}\hat y(\mathbf x)=\mathbf 1\{s(\mathbf x)\ge t\} that compares a score ss with a threshold tt. On a test set of nn examples, the confusion matrix counts true and false positives and negatives, TP, FP, FN and TN, and the prevalence is π=(TP+FN)/n\pi=(TP+FN)/n.

Every common metric normalizes one row of the matrix (a true class), one column (a predicted class), or all of it. That choice decides whether the metric moves when the class balance changes.

MetricFormulaNormalizes byAlso called
AccuracyTP+TNn\dfrac{TP+TN}{n}everything1−1- error rate
RecallTPTP+FN\dfrac{TP}{TP+FN}actual positives (row)sensitivity, true-positive rate (TPR)
SpecificityTNTN+FP\dfrac{TN}{TN+FP}actual negatives (row)true-negative rate; FPR =1−=1- specificity
PrecisionTPTP+FP\dfrac{TP}{TP+FP}predicted positives (column)positive predictive value (PPV)
NPVTNTN+FN\dfrac{TN}{TN+FN}predicted negatives (column)negative predictive value
F12TP2TP+FP+FN\dfrac{2TP}{2TP+FP+FN}ignores TNharmonic mean of precision and recall
Balanced accuracy12(TPR+TNR)\tfrac12(\text{TPR}+\text{TNR})both rows, equally1−1- balanced error rate
MCCTP⋅TN−FP⋅FN(TP+FP)(TP+FN)(TN+FP)(TN+FN)\dfrac{TP\cdot TN-FP\cdot FN}{\sqrt{(TP+FP)(TP+FN)(TN+FP)(TN+FN)}}everythingMatthews correlation: Pearson's rr between y^\hat y and yy
Row rates (recall, specificity, FPR) describe the classifier on each class separately and do not depend on prevalence. Column rates (precision, NPV) and accuracy mix the classes, so they do. F1 treats the classes asymmetrically: relabel which class is "positive" and it changes, while accuracy, balanced accuracy and MCC do not.
DerivationHow precision depends on prevalence
  1. precision=P(y=1∣y^=1)=P(y^=1∣y=1) P(y=1)P(y^=1)=π TPRπ TPR+(1−π) FPR\text{precision}=P(y=1\mid\hat y=1)=\frac{P(\hat y=1\mid y=1)\,P(y=1)}{P(\hat y=1)}=\frac{\pi\,\text{TPR}}{\pi\,\text{TPR}+(1-\pi)\,\text{FPR}}

    Precision is a conditional probability, so Bayes' rule applies, with TPR =P(y^=1∣y=1)=P(\hat y=1\mid y=1) and FPR =P(y^=1∣y=0)=P(\hat y=1\mid y=0):

  2. precision1−precision=π1−π⏟prior odds×TPRFPR⏟likelihood ratio\frac{\text{precision}}{1-\text{precision}}=\underbrace{\frac{\pi}{1-\pi}}_{\text{prior odds}}\times\underbrace{\frac{\text{TPR}}{\text{FPR}}}_{\text{likelihood ratio}}

    In odds form the structure is clearer: the posterior odds of a flagged case being positive are the prior odds times the positive likelihood ratio TPR/FPR\text{TPR}/\text{FPR}, a property of the classifier alone.

  3. π→0⟹precision≈π1−π⋅TPRFPR→0\pi\to0\quad\Longrightarrow\quad\text{precision}\approx\frac{\pi}{1-\pi}\cdot\frac{\text{TPR}}{\text{FPR}}\to0

    So a classifier with fixed error rates has precision that falls toward zero as π→0\pi\to0. At π=1%\pi=1\% the prior odds are 1/991/99, and even a likelihood ratio of 18 (recall 0.9, FPR 0.05) leaves posterior odds of 18/9918/99: precision 15%.

Predict before you look

A screening model has recall 0.9, and 1% of the people screened have the condition. What specificity (in %) does it need for at least half of its positive calls to be correct?

Show the answer

99.1 %

Precision ≥12\ge\tfrac12 means posterior odds ≥1\ge1, so the likelihood ratio must reach the inverse prior odds: TPR/FPR≥99\text{TPR}/\text{FPR}\ge99, i.e. FPR≤0.9/99≈0.0091\text{FPR}\le0.9/99\approx0.0091. Specificity must be at least about 99.1%. A specificity of 95%, which sounds excellent, gives precision of only 15% at this prevalence.

Thresholds, costs and F-scores

A scoring model is a whole family of classifiers, one per threshold. If a false negative costs cFNc_{\mathrm{FN}} and a false positive cFPc_{\mathrm{FP}}, the expected cost per example at threshold tt is

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

Error rate is the special case cFN=cFPc_{\mathrm{FN}}=c_{\mathrm{FP}}. If the scores are calibrated probabilities, the minimizer is the rule p(x)≥cFP/(cFP+cFN)p(\mathbf x)\ge c_{\mathrm{FP}}/(c_{\mathrm{FP}}+c_{\mathrm{FN}}), derived in Logistic Regression & Linear Classifiers; otherwise choose tt by minimizing the empirical cost on a validation set, never on the test set.

When costs are hard to state, the F-scores are a common compromise. With PP for precision and RR for recall,

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

so β>1\beta>1 weighs missed positives more and β<1\beta<1 false alarms; F1F_1 is the harmonic mean of PP and RR, which is dragged toward the smaller of the two. F-scores ignore TN entirely. That suits retrieval, where the negatives are an enormous uninteresting background, but it also means F1 is not an expected cost: its implicit price per error depends on the confusion matrix itself, and its best threshold moves with prevalence. When the scores are calibrated probabilities p=P(y=1∣x)p=P(y=1\mid\mathbf x) and F1 is computed from expected counts (a very large test set), that best threshold has a neat form: it is half the best achievable F1 (Lipton, Elkan & Narayanaswamy, 2014).

Check your understanding

A model has precision 0.5 and recall 1.0. What is its F1 score?

  1. 0.75
  2. about 0.667
  3. 0.5
  4. about 0.707
Show the answer

B. about 0.667

F1=2PR/(P+R)=2⋅0.5⋅1/1.5=2/3F_1=2PR/(P+R)=2\cdot0.5\cdot1/1.5=2/3. The harmonic mean sits below the arithmetic mean (0.75) and the geometric mean (0.707), closer to the weaker of the two rates, so a classifier cannot buy a high F1 with recall alone.

ROC and precision–recall curves

As tt falls from +∞+\infty to −∞-\infty, the point (FPR(t),TPR(t))(\text{FPR}(t),\text{TPR}(t)) traces the ROC curve from (0,0)(0,0) to (1,1)(1,1). A classifier that flags each case with probability qq, ignoring x\mathbf x, sits on the diagonal at (q,q)(q,q), so the diagonal is the chance baseline. The area under the curve, the AUC, has a clean meaning: it is the probability that a randomly drawn positive outscores a randomly drawn negative, with ties counted as one half. On data it is the fraction of positive–negative pairs ranked correctly, which is the Mann–Whitney UU statistic divided by n+n−n_+n_-:

AUC^=1n+n−∑i: yi=1 ∑j: yj=0(1{si>sj}+12 1{si=sj})\widehat{\mathrm{AUC}}=\frac{1}{n_+n_-}\sum_{i:\,y_i=1}\ \sum_{j:\,y_j=0}\Big(\mathbf 1\{s_i>s_j\}+\tfrac12\,\mathbf 1\{s_i=s_j\}\Big)
Sorting the scores computes it in O(nlog⁡n)O(n\log n). It depends only on the ranking, so any strictly increasing transformation of the scores leaves it unchanged, and it does not depend on the prevalence. The Convergence lesson proves the equivalence and gives its standard error.

The precision–recall (PR) curve plots precision against recall over the same thresholds. It is the curve to watch when positives are rare and the top of the ranking is what gets acted on, because precision feels the flood of negatives that a small FPR still lets through. Its chance baseline is a horizontal line at precision =π=\pi, and its usual summary, average precision, is AP=∑k(Rk−Rk−1)Pk\mathrm{AP}=\sum_k(R_k-R_{k-1})P_k over the thresholds in decreasing order.

PropertyROC curvePrecision–recall curve
AxesFPR (x), TPR (y)recall (x), precision (y)
Chance baselinethe diagonal; AUC = 0.5precision =π=\pi; AP ≈π\approx\pi
Depends on prevalence?no: both rates condition on the true classyes, through precision
Perfect classifierpasses through (0,1)(0,1); AUC = 1passes through (1,1)(1,1); AP = 1
Best forthe whole ranking; comparing models across settingsrare positives, where the top of the ranking matters
Interpolating between pointsa straight line, achievable by randomizing between two thresholdsnot a straight line: precision is not linear along that segment
For a fixed dataset the two curves carry the same information, point for point, and a model whose ROC curve dominates another's also dominates in PR space (Davis & Goadrich, 2006). What differs is what each picture makes visible.
Think first Two models have the same AUC, 0.90. Must they be equally good for your application?

No. ROC curves can cross: one model may be better at low false-positive rates, which matters for screening a large population where false alarms are expensive, and the other at high recall. AUC averages over every threshold, including thresholds you would never use. Look at the part of the curve where you will operate, or use a partial AUC over that range of FPR; the Convergence lesson ROC, AUC & Precision–Recall in Depth also explains why the AUC has been criticized as a measure of misclassification cost.

Many classes, and numbers instead of classes

With KK classes the confusion matrix is K×KK\times K, and each class gets its own one-vs-rest precision, recall and F1. Three ways to average them answer different questions:

  • Macro: the plain mean over classes. Every class counts equally, however rare.
  • Weighted: the mean weighted by each class's number of true examples (its support).
  • Micro: pool TP, FP and FN over all classes, then compute. In single-label problems each error is one FP (for the predicted class) and one FN (for the true class), so micro-precision, micro-recall and micro-F1 all equal accuracy.
True class (count)Predicted APredicted BPredicted CPrecisionRecallF1
A (800)7801550.9450.9750.960
B (150)2012550.8620.8330.847
C (50)255200.6670.4000.500
Accuracy, and so micro-F1, is 925/1000=0.925925/1000=0.925. Weighted F1 is 0.920. Macro-F1 is (0.960+0.847+0.500)/3=0.769(0.960+0.847+0.500)/3=0.769: it alone reveals that the rare class C is missed 60% of the time. Report per-class numbers whenever a small class matters (Sokolova & Lapalme, 2009, survey these measures).

For regression, with errors ei=y^i−yie_i=\hat y_i-y_i on nn test points:

MSE=1n∑iei2,RMSE=MSE,MAE=1n∑i∣ei∣,R2=1−∑iei2∑i(yi−yˉ)2,MAPE=1n∑i∣ei∣∣yi∣.\mathrm{MSE}=\frac1n\sum_ie_i^2,\quad\mathrm{RMSE}=\sqrt{\mathrm{MSE}},\quad\mathrm{MAE}=\frac1n\sum_i\abs{e_i},\quad R^2=1-\frac{\sum_ie_i^2}{\sum_i(y_i-\bar y)^2},\quad\mathrm{MAPE}=\frac1n\sum_i\frac{\abs{e_i}}{\abs{y_i}}.

RMSE is in the units of yy and punishes large errors heavily; MAE is robust to a few wild ones. R2R^2 compares the model with predicting the evaluation set's own mean, so out of sample it can be negative. For example, house prices (200,150,320,90,240)(200,150,320,90,240) in thousands predicted as (210,140,290,120,250)(210,140,290,120,250) give MSE 420, RMSE 20.5, MAE 18, R2=1−2100/30600=0.931R^2=1-2100/30600=0.931 and MAPE 11.7%, more than half of which comes from the 33% error on the cheapest house.

DerivationWhich number does each loss reward?
  1. E[(Y−c)2]=Var⁡(Y)+(EY−c)2⟹c⋆=EY\E\big[(Y-c)^2\big]=\Var(Y)+\big(\E Y-c\big)^2\quad\Longrightarrow\quad c^\star=\E Y

    Suppose you must predict a random target YY with a single number cc, as a model must at each input. Squared error splits into a variance and a bias term, so the mean is optimal:

  2. ddc E∣Y−c∣=P(Y<c)−P(Y>c)=0⟹c⋆=median⁡(Y)\frac{d}{dc}\,\E\abs{Y-c}=P(Y<c)-P(Y>c)=0\quad\Longrightarrow\quad c^\star=\operatorname{median}(Y)

    For absolute error, the derivative in cc is the probability mass below cc minus the mass above; it vanishes at the median:

  3. E∣Y−c∣Y=E[1Y]⋅EY~∣Y~−c∣,p~(y)∝p(y)y⟹c⋆=median⁡(Y~)\E\frac{\abs{Y-c}}{Y}=\E\Big[\tfrac1Y\Big]\cdot\E_{\tilde Y}\abs{\tilde Y-c},\qquad\tilde p(y)\propto\frac{p(y)}{y}\quad\Longrightarrow\quad c^\star=\operatorname{median}(\tilde Y)

    For positive YY, absolute percentage error is absolute error with weight 1/Y1/Y, so its minimizer is the median of the distribution reweighted by 1/y1/y, which favors small values: MAPE rewards under-forecasting, and it is undefined whenever y=0y=0. Scaled errors, which divide by the error of a simple benchmark forecast, avoid both problems (Hyndman & Koehler, 2006).

Predict before you look

Tomorrow's demand will be either 50 or 150 units, each with probability ½. Which single forecast minimizes the expected MAPE?

Show the answer

50 units

For a forecast ff between 50 and 150 the expected absolute percentage error is 12⋅f−5050+12⋅150−f150=f150\tfrac12\cdot\frac{f-50}{50}+\tfrac12\cdot\frac{150-f}{150}=\frac{f}{150}, which grows with ff, and below 50 it grows again. So the best forecast is 50, with expected MAPE 33%. Squared error would choose the mean, 100; absolute error is indifferent across [50,150][50,150]. A team rewarded on MAPE learns to forecast low.

Scoring probabilities, and choosing the metric

When a model outputs probabilities p^(x)\hat p(\mathbf x), judge the probabilities themselves with a scoring rule: the log loss −[ylog⁡p^+(1−y)log⁡(1−p^)]-\big[y\log\hat p+(1-y)\log(1-\hat p)\big] or the Brier score (p^−y)2(\hat p-y)^2 (Brier, 1950), averaged over the test set. A scoring rule is strictly proper if, whenever Y∼Bernoulli(p)Y\sim\mathrm{Bernoulli}(p), its expected value is minimized only by reporting p^=p\hat p=p: honesty is the unique best strategy (proper scoring rules; Gneiting & Raftery, 2007).

DerivationLog loss and the Brier score are strictly proper
  1. E[(q−Y)2]=(q−p)2+E[(p−Y)2]=(q−p)2+p(1−p)\E\big[(q-Y)^2\big]=(q-p)^2+\E\big[(p-Y)^2\big]=(q-p)^2+p(1-p)

    Brier. Expand around pp; the cross term vanishes because E[Y−p]=0\E[Y-p]=0:

  2. E[−Ylog⁡q−(1−Y)log⁡(1−q)]=H(p)+DKL(Ber(p) ∥ Ber(q))\E\big[-Y\log q-(1-Y)\log(1-q)\big]=H(p)+\KL\big(\mathrm{Ber}(p)\,\|\,\mathrm{Ber}(q)\big)

    The first term is zero only at q=pq=p; the second, p(1−p)p(1-p), is the irreducible uncertainty of the outcome. Log loss. The expected loss is the binary entropy of pp plus a Kullback–Leibler divergence, which by Gibbs' inequality is positive unless q=pq=p:

  3. E[1{1{q≥12}=Y}]={p,q≥121−p,q<12\E\big[\mathbf 1\{\mathbf 1\{q\ge\tfrac12\}=Y\}\big]=\begin{cases}p,&q\ge\tfrac12\\1-p,&q<\tfrac12\end{cases}

    Accuracy is not strictly proper. Scoring a probability by whether 1{q≥12}\mathbf 1\{q\ge\tfrac12\} matches yy gives every q≥12q\ge\tfrac12 the same expected score when p>12p>\tfrac12: reporting 0.51 or 0.99 makes no difference, so accuracy cannot reward good probabilities.

Proper scores measure two things at once. Discrimination is how well the scores separate the classes, which is all the AUC sees. Calibration is whether the stated probabilities match observed frequencies. A model can rank perfectly and be badly calibrated, and when the distortion is monotone, as it usually is, recalibration with a strictly increasing map repairs calibration without touching the ranking.

The decision the model supportsMetric to report
A fixed cut-off with known costsexpected cost at the chosen threshold (error rate only if costs are equal)
Act on the top kk cases of a ranked list (a budget of calls, audits, inspections)precision at kk, recall at kk
Threshold chosen later, or by different users; positives not rareROC AUC, as a summary of the ranking
Rare positives; the top of the ranking mattersthe PR curve and average precision
Probabilities feed further computation (pricing, triage, expected values)log loss or Brier score, with a reliability diagram
Several classes that matter equallymacro-averaged scores, and per-class tables
Regression: cost grows with squared error / absolute error / relative error(R)MSE / MAE / MAPE only with no zeros and with care, or scaled errors
Decide on the metric before looking at the results. Choosing it afterwards, among several that disagree, is another way to fit the test set.

Key takeaways

  • Every metric normalizes part of the confusion matrix. Recall, specificity and FPR condition on the true class and ignore prevalence; precision and accuracy mix the classes, with precision odds = prior odds × TPR/FPR.
  • A score plus a threshold is a classifier. Choose the threshold from costs on validation data, and summarize all thresholds with the ROC curve (prevalence-free) or the PR curve (prevalence-aware, honest about rare positives).
  • Micro-averaging over classes gives accuracy; macro-averaging lets rare classes count. In regression, MSE rewards the conditional mean, MAE the median, and MAPE rewards under-forecasting.
  • Log loss and the Brier score are strictly proper: they reward honest probabilities and see calibration, which AUC, a pure ranking measure, cannot.
  • Pick the metric from the decision the model supports, and do it before looking at the results.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A classifier for three classes has micro-averaged F1 0.93 and macro-averaged F1 0.71. What does this most likely mean?

  1. The classifier is well balanced across classes; the two averages always differ by about this much
  2. It performs poorly on at least one class, most likely a rare one
  3. Macro-averaging is wrong for multiclass problems
  4. Its accuracy is 0.71
Show the answer

B. It performs poorly on at least one class, most likely a rare one

Micro-F1 pools every decision, so for single-label problems it equals accuracy and is dominated by the large classes. Macro-F1 averages the per-class F1 scores, so one class with a low F1 pulls it down. A gap this large usually means a small class is handled badly.

Question 2

A regression model scores R2=−0.2R^2=-0.2 on a held-out test set. What does that mean?

  1. The computation must be wrong: R2R^2 lies between 0 and 1
  2. The predictions are negatively correlated with the targets
  3. The model explains 20% of the variance, with the opposite sign
  4. Its squared error is larger than that of predicting the test set's mean for every example
Show the answer

D. Its squared error is larger than that of predicting the test set's mean for every example

R2=1−SSE/SSTR^2=1-\mathrm{SSE}/\mathrm{SST}, where SST is the squared error of the constant prediction yˉtest\bar y_{\text{test}}. Out of sample nothing forces SSE below SST, so R2<0R^2<0 simply means the model is worse than that constant. Only in-sample least squares with an intercept guarantees R2≥0R^2\ge0.

Question 3

You replace a classifier's scores ss by s3s^3, a strictly increasing transformation. Which quantity is guaranteed not to change?

  1. The ROC AUC
  2. The log loss of the probabilities σ(s3)\sigma(s^3)
  3. The accuracy at threshold t=1/2t=1/2
  4. The Brier score
Show the answer

A. The ROC AUC

AUC depends only on how the scores order the positives against the negatives, and a strictly increasing map preserves every order. Log loss and Brier score depend on the probability values, and a fixed threshold now cuts the scores at a different place (s3≥12s^3\ge\tfrac12 means s≥0.79s\ge0.79).

Question 4

A diagnostic test has the same sensitivity and specificity in two hospitals, but the disease is ten times more common in the first. Which quantity differs between the hospitals?

  1. The ROC curve
  2. The recall
  3. The precision (positive predictive value)
  4. The false-positive rate
Show the answer

C. The precision (positive predictive value)

Sensitivity (recall), specificity and hence the ROC curve condition on the true class and stay the same. Precision mixes the classes: its odds are the prior odds times TPR/FPR\text{TPR}/\text{FPR}, so the hospital with ten times the prevalence (at low prevalence) sees roughly ten times the precision odds.

Question 5

You swap which class is called "positive" and recompute. Which metric changes?

  1. F1
  2. Accuracy
  3. Balanced accuracy
  4. The Matthews correlation coefficient
Show the answer

A. F1

Swapping the labels exchanges TP with TN and FP with FN. Accuracy, balanced accuracy and MCC are symmetric under that exchange. F1 =2TP/(2TP+FP+FN)=2TP/(2TP+FP+FN) ignores TN, so it measures something different after the swap: performance on the other class.

Go deeper

Further reading

  • T. Fawcett, "An introduction to ROC analysis," Pattern Recognition Letters 27(8), 861–874 (2006).
  • T. Saito & M. Rehmsmeier, "The precision-recall plot is more informative than the ROC plot when evaluating binary classifiers on imbalanced datasets," PLOS ONE 10(3), e0118432 (2015).
  • R. J. Hyndman & A. B. Koehler, "Another look at measures of forecast accuracy," International Journal of Forecasting 22(4), 679–688 (2006).
  • T. Gneiting & A. E. Raftery, "Strictly proper scoring rules, prediction, and estimation," Journal of the American Statistical Association 102(477), 359–378 (2007).