Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 3: Classical Machine LearningCore Concepts

Evaluation metrics

P3.A945 min●○○ BeginnerReviewed Dec 2, 2026

Why this matters for machine learning

A model is only as good as the number you judge it by, and the wrong number can make a useless model look excellent: a screening test that calls everyone healthy is 99% accurate when 1 in 100 has the disease.

  • Choosing hyperparameters and models on a validation set needs a metric that matches the goal, and one final test-set number to report. (P3.A4: Train, validation and test sets)
  • When one class is rare (fraud, disease, defects), accuracy hides the failures, so the choice of metric and threshold decides whether the system is useful. (P3.A10: Calibration and class imbalance)
  • Object detectors are scored with precision-recall curves, so average precision is the headline number of their benchmarks. (P5.11: Object detection basics)
  • A deployed model is watched by tracking its metrics as true labels arrive, and a falling recall or precision is the first sign of drift. (P12.5: Monitoring and drift, coming soon)

Before this: The supervised learning setup, Bayes' theorem, Logistic regression

After this lesson you can

  • Fill a confusion matrix from predictions and compute accuracy, precision, recall, specificity, false positive rate and F1 from it
  • Explain why accuracy misleads when one class is rare, and why precision, unlike recall, depends on how common the positive class is
  • Say what a threshold does, draw the ROC curve from scores, and state what the AUC means as a probability
  • Choose between the ROC curve and the precision-recall curve, and read average precision against its no-skill baseline
  • Average per-class metrics over many classes (macro, micro, weighted), compute the common regression metrics, and pick a metric from the costs of the two kinds of mistake

A hospital tests a model that looks for a rare disease. One person in a hundred has it. The model says “healthy” to everybody, and its accuracy is 99%. It has also never found a single sick person. The number was correct and told nothing useful.

P3.A1 said that a loss is a tool for training and a metric is the number you report. This lesson is about metrics for classification, and a short look at regression. All of them start from a small table of counts. You will meet the Bayes’ theorem numbers of P1.D6 again, now as precision and recall, and the confusion matrix of P2.4, now with the metrics built on it.

Four outcomes: the confusion matrix

Take a binary classifier, with two classes. Call one of them the positive class: the thing you are looking for (spam, disease, fraud). The other is the negative class. For one example, the truth and the prediction can combine in four ways:

  • True positive (TP): truly positive, predicted positive. A hit.
  • False positive (FP): truly negative, predicted positive. A false alarm.
  • False negative (FN): truly positive, predicted negative. A miss.
  • True negative (TN): truly negative, predicted negative. A correct “nothing here”.

The confusion matrix counts them. Here is a spam filter tested on 200 emails, 20 of them spam. The numbers are made up for teaching; the code below checks every one.

predicted spampredicted not spam
actually spamTP = 14FN = 6
actually not spamFP = 10TN = 170

Rows are the truth and columns the prediction, as in P2.4. The row totals are the class sizes (14+6=2014+6=20 spam, 10+170=18010+170=180 not spam). Books and libraries do not all use this layout, so check which axis is which. scikit-learn puts the true class in the rows, and for labels 0 and 1 it prints [[TN, FP], [FN, TP]], with the negative class first.

For more than two classes the matrix grows to K×KK\times K, and the correct predictions sit on the diagonal (the multi-class section below).

Accuracy, and why it misleads

Accuracy is the share of correct predictions:

accuracy=TP+TNN=14+170200=0.92,\text{accuracy}=\frac{\mathrm{TP}+\mathrm{TN}}{N}=\frac{14+170}{200}=0.92,

where NN is the total number of examples.

It is the same as one minus the error rate, the average 0-1 loss of P3.A1. Is 0.920.92 good? Compare it with a model that does no work: one that says “not spam” for every email. It is right on all 180 non-spam emails, so its accuracy is 180/200=0.90180/200=0.90. Our filter beats that by two points, and catches 14 of the 20 spam emails. The baseline catches none.

So accuracy depends heavily on how common each class is. The baseline of always predicting the majority class is the first number to compute for any classification problem, and a model has to be judged against it. With 1% positives the baseline is 99%, as in the hospital.

Accuracy also treats both mistakes as equally bad. A missed spam and a real email sent to the spam folder cost different amounts, and so do a missed tumour and a false alarm. The other metrics let you look at the two mistakes separately.

Precision and recall

Two questions about the spam filter are worth asking separately.

  • Recall: of the 20 spam emails, how many did it catch? TPTP+FN=1420=0.70\dfrac{\mathrm{TP}}{\mathrm{TP}+\mathrm{FN}}=\dfrac{14}{20}=0.70. It is also called sensitivity or the true positive rate (TPR).
  • Precision: of the 24 emails it flagged, how many were really spam? TPTP+FP=1424=0.583\dfrac{\mathrm{TP}}{\mathrm{TP}+\mathrm{FP}}=\dfrac{14}{24}=0.583. It is also called the positive predictive value.

Two companions describe the negative class:

  • Specificity (true negative rate): of the 180 non-spam emails, how many were left alone? TNTN+FP=170180=0.944\dfrac{\mathrm{TN}}{\mathrm{TN}+\mathrm{FP}}=\dfrac{170}{180}=0.944.
  • False positive rate (FPR): of the 180 non-spam emails, how many were flagged? FPFP+TN=10180=0.056\dfrac{\mathrm{FP}}{\mathrm{FP}+\mathrm{TN}}=\dfrac{10}{180}=0.056, which is 1−specificity1-\text{specificity}.

A way to keep them apart is to ask which total is in the denominator. Recall, specificity and FPR divide by a row of the matrix, the number of real positives or real negatives, so each is a rate inside one class. Precision divides by a column, the number of cases the model flagged. That difference matters in the next paragraph. If nothing is flagged, precision is 0/00/0, which is undefined; libraries return 0 or a warning, depending on a setting.

Precision is a posterior

P1.D6 gave a medical test with recall 0.90.9 and a false positive rate of 0.10.1, and showed that its precision depends on how common the disease is. Here are those counts for 10000 people, of whom 1% (100) are positive:

  • Recall 0.90.9 finds 9090 of the 100 sick people (TP=90\mathrm{TP}=90, FN=10\mathrm{FN}=10).
  • An FPR of 0.10.1 flags 990990 of the 9900 healthy people (FP=990\mathrm{FP}=990, TN=8910\mathrm{TN}=8910).
  • Precision is 90/(90+990)=8.3%90/(90+990)=8.3\%. Most alarms are false.

If half the people were sick, the same recall and FPR would give a precision of 90%90\%. If the FPR drops to 1%1\% with 1% sick, precision rises to 90/(90+99)≈47.6%90/(90+99)\approx47.6\%. The recall and FPR describe the test, and they do not change with the mix of people. Precision is P(positive∣predicted positive)\mathbb{P}(\text{positive}\mid\text{predicted positive}), a posterior, so it moves with the prior (the base rate). A precision measured on a balanced test set does not carry over to a population where positives are rare. P3.A10 deals with what to do about that.

F1: one number for precision and recall

Often you want a single number that is high only when precision and recall are high. The F1 score is their harmonic mean:

F1=2PRP+R=2 TP2 TP+FP+FN.F_1=\frac{2PR}{P+R}=\frac{2\,\mathrm{TP}}{2\,\mathrm{TP}+\mathrm{FP}+\mathrm{FN}}.

For the spam filter, F1=28/(28+10+6)=0.636F_1=28/(28+10+6)=0.636.

Why the harmonic mean and not the ordinary one? Take a filter that flags one email, a certain spam, and nothing else. Its precision is 11 and its recall is 1/20=0.051/20=0.05. The ordinary mean is 0.5250.525, which sounds acceptable for a filter that finds 5% of the spam. The harmonic mean is 0.0950.095. The harmonic mean is pulled toward the smaller of the two numbers, so a model cannot hide a very poor recall behind a perfect precision.

Two things to remember about F1. It ignores true negatives, so it says nothing about how well the model leaves the negative class alone. And it is not symmetric between the classes: which class you call positive changes the score.

F-beta shifts the balance. FβF_\beta treats recall as β\beta times as important as precision:

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}}.

For the spam filter F2=0.673F_2=0.673 (recall-heavy, because FN\mathrm{FN} gets weight 4) and F0.5=0.603F_{0.5}=0.603 (precision-heavy). β=1\beta=1 gives F1F_1.

Scores and thresholds

Most classifiers do not output a label directly. Logistic regression (P3.A7) outputs a probability-like score between 0 and 1, and the label comes from a rule: predict positive when the score is at least the threshold tt. The usual default is t=0.5t=0.5, but it is a choice, not part of the model.

Moving tt trades one mistake for the other. A low threshold calls many examples positive: you catch nearly every real positive (high recall) but also flag many negatives (many false alarms, a higher FPR, usually lower precision). A high threshold flags only the surest cases: fewer false alarms and a higher precision, but more misses. Recall and FPR can only go down together as tt rises, and neither threshold is “correct”. The right one depends on what each mistake costs.

The widget below makes this concrete. The scores are made up: 100 positives and 100 negatives whose scores overlap, as real ones do. Slide the threshold and watch the confusion matrix and the metrics change. Each threshold gives one point (FPR, recall); the ROC curve is the path of that point as tt goes from 1 down to 0. Try these:

  1. Set the threshold to 0.5 with 1:1. The counts are TP 90, FN 10, FP 10, TN 90: recall 0.90.9 and FPR 0.10.1, the numbers of the medical test above.
  2. Switch the ratio to 99:1 (1% positive) without moving the threshold. Recall and FPR stay the same, the marker on the ROC curve does not move, and precision collapses. Compare the accuracy with the “always say negative” line.
  3. Open the precision-recall tab and compare the curve at 1:1 and at 99:1.

Move the threshold through the scores

Made-up scores from a classifier: 100 positives and 100 negatives; the ratio below repeats every negative that many times in the counts, ROC and PR curves (not in the histogram). An example is called positive when its score is at least the threshold.

Scores, as a share of each class

00.20.40.60.8100.050.10.15

positives (blue) negatives (pink) threshold

Negatives per positive
predicted positivepredicted negative
actually positiveTP90FN10
actually negativeFP10TN90

200 examples; 50% are positive.

Accuracy
0.9
Always say negative
0.5
Precision
0.9
Recall (TPR)
0.9
Specificity
0.9
FPR
0.1
F1
0.9

Vertical: recall (TPR). Horizontal: false positive rate (FPR).

00.20.40.60.8100.20.40.60.81

AUC (blue area) = 0.966 for every ratio. The dashed line is random guessing, area 0.5.

Made-up scores for 100 positives (blue) and 100 negatives (pink), each class drawn as a share of its own size, so the histogram does not change with the ratio. The dashed line is the threshold. The table is the confusion matrix and the list gives the metrics at that threshold. The ROC tab shows recall against the false positive rate with the current threshold as a ringed dot and the area under the curve shaded; the precision-recall tab shows precision against recall with the dashed no-skill level. The ratio control repeats every negative score that many times in the counts and curves (so 99:1 means 1% of the examples are positive): the ROC curve does not change, the precision-recall curve does. The scores are not calibrated probabilities.

The ROC curve and the AUC

The ROC curve (receiver operating characteristic, a name from radar engineering) plots, for every threshold, the false positive rate on the horizontal axis and the recall on the vertical axis. Some points to know:

  • (0,0)(0,0): the threshold is so high that nothing is called positive. (1,1)(1,1): so low that everything is.
  • (0,1)(0,1), the top-left corner, is perfect: every positive caught, no false alarm. A better classifier has a curve closer to that corner.
  • The diagonal from (0,0)(0,0) to (1,1)(1,1) is a classifier that ignores its input. If it calls each example positive with probability qq, then recall and FPR both equal qq.
  • A curve below the diagonal means the scores point the wrong way: flipping the prediction would help.

A small example, by hand

Four positives and four negatives, with these made-up scores (some equal, as happens when a model gives the same score to several cases):

scorepositivesnegatives
0.921
0.711
0.412

Lower the threshold step by step. At t=0.9t=0.9 the model flags 2 positives and 1 negative, so recall =2/4=0.5=2/4=0.5 and FPR =1/4=0.25=1/4=0.25. At t=0.7t=0.7: 3 positives and 2 negatives, which is (0.5, 0.75)(0.5,\,0.75). At t=0.4t=0.4 everything is flagged: (1,1)(1,1). The ROC points are

(0,0), (0.25, 0.5), (0.5, 0.75), (1, 1).(0,0),\ (0.25,\,0.5),\ (0.5,\,0.75),\ (1,\,1).

The AUC is the area under the curve, found with the trapezoid rule of P1.C9. The three trapezoids have areas 0.06250.0625, 0.156250.15625 and 0.43750.4375, and

AUC=0.0625+0.15625+0.4375=0.65625.\text{AUC}=0.0625+0.15625+0.4375=0.65625.

A segment such as (0.5,0.75)→(1,1)(0.5,0.75)\to(1,1) is slanted because 1 positive and 2 negatives share the score 0.4: lowering the threshold past 0.4 adds all three at once.

What the AUC means

The area has a second meaning that needs no integral: the AUC is the probability that a randomly chosen positive gets a higher score than a randomly chosen negative, counting a tie as one half. Check it on the example. There are 4×4=164\times4=16 positive-negative pairs. The two positives scoring 0.9 beat the negatives at 0.7, 0.4 and 0.4 and tie with the negative at 0.9, so each is worth 3.53.5 and together 77. The positive at 0.7 beats two negatives and ties with one: 2.52.5. The positive at 0.4 ties with two negatives: 11. The total is 10.510.5, and 10.5/16=0.6562510.5/16=0.65625, the same number. The cells below confirm this, and the same equality on random data.

Three consequences follow from the pair view:

  • The AUC is free of the threshold. It judges the whole ranking, not one cut-off. A model with an AUC of 0.50.5 ranks positives and negatives like a coin flip; 11 means every positive is above every negative. There is no universal “good” value, since what counts depends on the problem.
  • Only the order of the scores matters. Squaring or exponentiating all scores keeps the order and the AUC. So the AUC says nothing about whether the scores are good probabilities (P3.A10).
  • It does not depend on the class balance. Recall and FPR are rates within a class, so the ROC curve and the AUC do not change if you add more negatives of the same kind. This is both a strength and a weakness (next section).
Go deeper The AUC as a rank statistic

The pair-counting probability equals the Mann-Whitney U statistic divided by n+n−n_+n_-, where n+n_+ and n−n_- are the numbers of positives and negatives. In practice it is computed from the ranks of the scores (sort all scores, sum the ranks of the positives), which takes time of order nlog⁡nn\log n instead of looking at all n+n−n_+n_- pairs. scikit-learn instead sorts the scores, builds the ROC curve and takes the trapezoid area. Every route gives the same number, ties included.

When positives are rare: the precision-recall curve

At 99:1 the widget’s ROC curve and its AUC of 0.9660.966 are exactly what they were at 1:1, but at threshold 0.5 the precision has fallen to 0.0830.083. How can both be true? FPR measures false alarms against the number of negatives. With 9900 negatives, an FPR of 0.10.1 is 990990 false alarms, ten times the 90 hits. The ROC curve looks the same because it is computed inside each class, and it cannot see that the negative class is huge. If you care about the cases the model flags, the ROC curve and the AUC can be too hopeful.

The precision-recall (PR) curve answers that question. For every threshold it plots precision against recall. It uses no true negatives, so it responds to the class balance. Its summary is the average precision (AP), and its reference line is the no-skill level: a classifier that ranks at random has a precision equal to the positive rate, whatever the recall. In the widget the AP is 0.9670.967 at 1:1, 0.9020.902 at 4:1, 0.8370.837 at 9:1 and 0.6000.600 at 99:1, against no-skill levels of 0.50.5, 0.20.2, 0.10.1 and 0.010.01. A model with an AP of 0.60.6 at 1% positives is far better than random (0.01) and far from perfect.

scikit-learn’s average_precision_score computes AP as a step sum over the thresholds, not as a trapezoid area (details in the box below).

Go deeper AP is a step sum, not a trapezoid

AP is a weighted sum over the thresholds, where each weight is the gain in recall:

AP=∑n(Rn−Rn−1) Pn.\text{AP}=\sum_n (R_n-R_{n-1})\,P_n.

It is not the trapezoid area under the PR curve, because straight lines between PR points are too optimistic. For the four-and-four example, AP is 0.5⋅23+0.25⋅0.6+0.25⋅0.5=0.60830.5\cdot\tfrac23+0.25\cdot0.6+0.25\cdot0.5=0.6083 (the three steps are at t=0.9,0.7,0.4t=0.9,0.7,0.4), while the trapezoid area from scikit-learn’s curve is 0.71250.7125.

Which curve? Use the ROC curve and AUC when you care about both classes and they are of comparable size, or when you want a measure of ranking quality that does not move with the class mix. Use the PR curve and AP when the positive class is rare and the positives are what you care about. Neither picks the threshold for you. And the ROC curve is not wrong under imbalance: it answers a different question, whether a positive tends to outrank a negative.

Go deeper Other single numbers: balanced accuracy and MCC

Balanced accuracy is the mean of recall and specificity, (0.70+0.944)/2=0.822(0.70+0.944)/2=0.822 for the spam filter. It stays low when the model ignores the rare class, and “always not spam” scores 0.50.5. The Matthews correlation coefficient uses all four counts. Its numerator is TP⋅TN−FP⋅FN\mathrm{TP}\cdot\mathrm{TN}-\mathrm{FP}\cdot\mathrm{FN} and its denominator is the square root of the product of the four totals (two row totals and two column totals). It is 0.5950.595 here. It ranges from −1-1 to 11 and is 00 when the predictions are unrelated to the true labels. Both give one number that is harder to inflate than accuracy, but neither tells you which kind of mistake you are making.

Many classes

With KK classes the confusion matrix is K×KK\times K. Here is the one from P2.4 (rows are the true class): 150 images, of which 133 are correct, so the accuracy is 133/150=0.887133/150=0.887.

called catcalled dogcalled bird
true cat4820
true dog5405
true bird1445

Precision and recall are defined per class, by treating that class as positive and every other class as negative. For dog: recall is the diagonal entry over its row, 40/50=0.8040/50=0.80 (the 5 true dogs called cats and the 5 called birds are misses), and precision is the diagonal entry over its column, 40/(2+40+4)=40/46=0.87040/(2+40+4)=40/46=0.870.

classprecisionrecallF1
cat0.8890.9600.923
dog0.8700.8000.833
bird0.9000.9000.900

To get one number from several, there are three ways to average:

  • Macro: the plain mean of the per-class values. Every class counts equally, so a poor rare class pulls it down.
  • Weighted: the mean weighted by each class’s number of examples (its support). It follows the big classes.
  • Micro: pool the counts of all classes first (total TP, FP, FN), then compute the metric. For a problem where each example has exactly one label, micro precision, micro recall and micro F1 all equal the accuracy.

Here the three classes have 50 examples each, so macro and weighted F1 agree (0.8850.885) and the micro value is the accuracy, 0.8870.887. They separate when class sizes differ. In the made-up unbalanced matrix of the code below (classes of 100, 10 and 10 examples) the macro F1 is 0.6570.657 against a micro value (the accuracy) of 0.8500.850, because the two small classes are handled poorly, and only the macro average shows it. The macro F1 is the mean of the per-class F1 values, not the harmonic mean of the macro precision and macro recall.

For ROC curves with many classes, use one-vs-rest: one curve and AUC per class, then average (scores from softmax regression, P3.A8).

Regression metrics

For a numeric target the metrics are built from the errors ei=yi−y^ie_i=y_i-\hat y_i. Use the best line y^=2.5x−1\hat y=2.5x-1 for the three points (1,2),(2,3),(3,7)(1,2),(2,3),(3,7) of P3.A1 (fitted in P3.A2): the errors are 0.5, −1, 0.50.5,\,-1,\,0.5.

  • Mean absolute error: MAE=1N∑∣ei∣=0.667\text{MAE}=\frac1N\sum|e_i|=0.667. In the units of yy, and each error counts in proportion to its size.
  • Mean squared error: MSE=1N∑ei2=0.5\text{MSE}=\frac1N\sum e_i^2=0.5. It punishes large errors more, and it is the training loss of P3.A2. RMSE =MSE=0.707=\sqrt{\text{MSE}}=0.707 is back in the units of yy.
  • R-squared: R2=1−∑ei2∑(yi−yˉ)2=1−1.514=0.893R^2=1-\dfrac{\sum e_i^2}{\sum(y_i-\bar y)^2}=1-\dfrac{1.5}{14}=0.893. It compares the model with the baseline that predicts the mean yˉ\bar y for every example: R2=0R^2=0 means no better than that baseline, and it is negative for a model that is worse (a constant 5 gives −0.214-0.214). It depends on how spread out the test targets are, so compare it only on the same data.

Report errors on held-out data, not the training set (P3.A4). Because MSE squares the errors, one huge miss can dominate it, while MAE barely moves; which behaviour is right depends on whether a big miss is truly worse than two small ones.

Choosing a metric from the costs

Pick the metric from what the mistakes cost. A missed case costs something different from a false alarm:

  • Cancer screening. A false negative is a missed cancer, and a false positive means one more test. A miss costs far more, so recall comes first and the threshold goes low.
  • Spam folder. A false positive hides a real email, and a false negative leaves one junk email in the inbox. Here the threshold goes high and precision matters more.
  • Ranking a few candidates for a person to review (the top 20 flagged transactions): precision among the flagged ones counts.

If the costs can be put in numbers, say cFNc_{\mathrm{FN}} per miss and cFPc_{\mathrm{FP}} per false alarm, the cost to minimize is cFN FN+cFP FPc_{\mathrm{FN}}\,\mathrm{FN}+c_{\mathrm{FP}}\,\mathrm{FP}. On the widget’s scores at 1:1, with equal costs the best threshold is around 0.5 (a cost of 20). If a miss costs ten times a false alarm, the best threshold is 0.290.29 (1 miss and 35 false alarms, a cost of 45) instead of 0.50.5 (a cost of 110). If a false alarm costs ten times a miss, it is 0.710.71 (also a cost of 45). The threshold is a decision, and the data and the costs decide it.

Go deeper The threshold from the costs, for calibrated probabilities

If a model’s score is a true (calibrated) probability pp of the positive class, and correct decisions cost nothing, predicting positive is the cheaper choice when p cFN≥(1−p) cFPp\,c_{\mathrm{FN}}\ge(1-p)\,c_{\mathrm{FP}}, which gives the threshold t∗=cFPcFP+cFNt^*=\dfrac{c_{\mathrm{FP}}}{c_{\mathrm{FP}}+c_{\mathrm{FN}}}. With a miss ten times as costly, t∗=1/11≈0.09t^*=1/11\approx0.09. The conditions matter: calibrated scores and zero cost for correct predictions. The widget’s scores are not calibrated probabilities, so this formula does not apply to them, and the best thresholds above were found by trying them. How to check and repair calibration is P3.A10.

Three more points about practice.

  • The metric is not the training loss. A classifier is trained with a smooth loss such as cross-entropy (P3.A7), and judged with the metric the goal needs. They can disagree, and the metric is what you report (P3.A1).
  • Choose on validation data, report on test data. Tuning a threshold or a model against the test set uses it up (P3.A4).
  • A metric is an estimate. The accuracy on 1000 test examples has a standard error of about 0.00950.0095 near 0.900.90 (P1.D8). A recall of 0.700.70 measured on only 20 positives has a standard error of 0.7⋅0.3/20=0.10\sqrt{0.7\cdot0.3/20}=0.10, so a rough 95% interval is about ±0.20\pm0.20. Rare classes make metrics noisy, and a gap between two models of a point or two is often within that noise (P1.D13).

Intuition

Think of fishing with a net. Recall is the share of all the fish in the lake that you caught. Precision is the share of your catch that is fish and not boots. A wide mesh (a low threshold) catches nearly every fish and a lot of boots; a fine one (a high threshold) catches mostly fish but misses many. The ROC curve shows, for every mesh size, how many fish you catch against how many boots you catch, and the AUC is the chance that a random fish is “more fish-like” than a random boot. The picture breaks in one place: in the lake, the boots could be a thousand times more numerous than the fish. The ROC curve ignores that, and precision does not.

Math

Counts: TP,FP,FN,TN\mathrm{TP},\mathrm{FP},\mathrm{FN},\mathrm{TN}; NN is their sum; P=TP+FNP=\mathrm{TP}+\mathrm{FN} real positives.

accuracy=TP+TNN,precision=TPTP+FP,recall=TPP,\text{accuracy}=\frac{\mathrm{TP}+\mathrm{TN}}{N},\quad \text{precision}=\frac{\mathrm{TP}}{\mathrm{TP}+\mathrm{FP}},\quad \text{recall}=\frac{\mathrm{TP}}{P},

specificity=TNTN+FP,FPR=1−specificity,Fβ=(1+β2) TP(1+β2) TP+β2 FN+FP.\text{specificity}=\frac{\mathrm{TN}}{\mathrm{TN}+\mathrm{FP}},\quad \text{FPR}=1-\text{specificity},\quad F_\beta=\frac{(1+\beta^2)\,\mathrm{TP}}{(1+\beta^2)\,\mathrm{TP}+\beta^2\,\mathrm{FN}+\mathrm{FP}}.

With positive rate π=P/N\pi=P/N, recall rr and false positive rate ff, Bayes’ theorem gives the precision

precision=r πr π+f (1−π).\text{precision}=\frac{r\,\pi}{r\,\pi+f\,(1-\pi)}.

For scores ss and a threshold tt: predict positive when s≥ts\ge t. ROC curve: the points (FPR(t),TPR(t))(\text{FPR}(t),\text{TPR}(t)). With scores s+s^+ of positives and s−s^- of negatives,

AUC=P(s+>s−)+12 P(s+=s−)=∫01TPR  d FPR.\text{AUC}=\mathbb{P}(s^+>s^-)+\tfrac12\,\mathbb{P}(s^+=s^-)=\int_0^1 \text{TPR}\;d\,\text{FPR}.

Average precision: AP=∑n(Rn−Rn−1)Pn\text{AP}=\sum_n (R_n-R_{n-1})P_n over the distinct thresholds, with R0=0R_0=0. Macro average: 1K∑kmk\frac1K\sum_k m_k; weighted: ∑knkNmk\sum_k\frac{n_k}{N}m_k; micro: the metric of the summed counts. Regression: MAE=1N∑∣ei∣\text{MAE}=\frac1N\sum|e_i|, RMSE=1N∑ei2\text{RMSE}=\sqrt{\frac1N\sum e_i^2}, R2=1−∑ei2/∑(yi−yˉ)2R^2=1-\sum e_i^2/\sum(y_i-\bar y)^2.

Code

The same metrics in scikit-learn. This block is not runnable here, because scikit-learn is not available in the browser; the output shown is from a real run on the machine used for this lesson (scikit-learn 1.8). The Try it cells below use only NumPy.

import numpy as np
from sklearn.metrics import (confusion_matrix, classification_report,
                             roc_auc_score, average_precision_score)

# The spam test: 20 spam (1), 180 not spam (0).
y_true = np.r_[np.ones(20), np.zeros(180)].astype(int)
y_pred = np.r_[np.ones(14), np.zeros(6),
               np.ones(10), np.zeros(170)].astype(int)
print(confusion_matrix(y_true, y_pred))
print(classification_report(y_true, y_pred,
                            target_names=["ham", "spam"]))

# Scores of the four-and-four example.
y = np.array([1, 1, 1, 1, 0, 0, 0, 0])
s = np.array([.9, .9, .7, .4, .9, .7, .4, .4])
print("AUC", roc_auc_score(y, s))
print("AP ", round(average_precision_score(y, s), 4))
[[170  10]
 [  6  14]]
              precision    recall  f1-score   support

         ham       0.97      0.94      0.96       180
        spam       0.58      0.70      0.64        20

    accuracy                           0.92       200
   macro avg       0.77      0.82      0.80       200
weighted avg       0.93      0.92      0.92       200

AUC 0.65625
AP  0.6083

The report has one row per class, and the accuracy row is the micro average for a single-label problem. roc_auc_score takes the scores, not the hard predictions: feeding it labels gives a one-point ROC curve that throws away the ranking. average_precision_score also takes scores.

Try it

Cell 1: the confusion matrix, metrics and F-beta for the spam filter. It prints accuracy 0.9200.920 against 0.9000.900 for always saying “not spam”, precision 0.5830.583, recall 0.7000.700, specificity 0.9440.944, FPR 0.0560.056, F1=0.636F_1=0.636, F2=0.673F_2=0.673, F0.5=0.603F_{0.5}=0.603, and the mean 0.5250.525 against the harmonic mean 0.0950.095 for the filter that flags one email.

Metrics from a confusion matrix

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Cell 2: ROC, AUC and average precision from scores. It builds the ROC points by lowering the threshold, finds the AUC two ways (trapezoid and by comparing pairs), then checks on random scores that taking exp of the scores and adding ten times more negatives leave the AUC alone, while the AP falls. It prints the four ROC points, AUC 0.656250.65625 both ways, AP 0.60830.6083, and on the random data AUC 0.85360.8536 in all three cases, with AP 0.8670.867 at a positive rate of 0.5000.500 and 0.5700.570 at 0.0910.091.

ROC, AUC and AP from scores

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Cell 3: per-class metrics and the three averages. The P2.4 matrix first (macro and weighted F1 both 0.8850.885, micro 0.8870.887), then the unbalanced matrix (macro 0.6570.657, weighted 0.8600.860, micro 0.8500.850). Change the matrix to see which average reacts.

Macro, weighted and micro averages

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Cell 4: regression metrics for the line of P3.A1. It prints MAE 0.6670.667, MSE 0.5000.500, RMSE 0.7070.707 and R2=0.893R^2=0.893, then R2=0.000R^2=0.000 for predicting the mean and −0.214-0.214 for predicting the constant 5.

MAE, RMSE and R-squared

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Check your understanding

  1. A fraud model is tested on 2000 transactions, 20 of them fraud. Model A says “not fraud” for every transaction. Model B catches 15 of the frauds and wrongly flags 40 honest transactions. Which statement is correct?

  2. A classifier has precision 0.90.9 and recall 0.10.1. What is its F1 score?

  3. A model has an AUC of 0.80.8. What does this say?

  4. A model has an AUC of 0.970.97 on a data set where 0.5%0.5\% of the examples are positive. Which statement can still be true?

  5. A problem has three classes with 1000, 30 and 20 examples. The model is excellent on the largest class and poor on the two small ones. Which single number shows the problem most clearly?

Exercises

  1. A test set has 40 positives and 960 negatives. The model gives TP=30\mathrm{TP}=30 and FP=60\mathrm{FP}=60. Find FN\mathrm{FN}, TN\mathrm{TN}, accuracy, precision, recall, FPR and F1, and the accuracy of always predicting negative.
    Show answerFN=10\mathrm{FN}=10 and TN=900\mathrm{TN}=900. Accuracy is 930/1000=0.93930/1000=0.93, precision 30/90=0.33330/90=0.333, recall 30/40=0.7530/40=0.75, FPR 60/960=0.062560/960=0.0625 and F1=60/(60+60+10)=0.462F_1=60/(60+60+10)=0.462. Always negative scores 960/1000=0.96960/1000=0.96, higher than the model’s accuracy, so the model needs a metric other than accuracy.
  2. A test has recall 0.80.8 and a false positive rate of 0.050.05. Its precision if 2%2\% of the people tested are positive?
    Show answerPer 1000 people: 2020 positive, so TP=16\mathrm{TP}=16; 980980 negative, so FP=49\mathrm{FP}=49. Precision is 16/(16+49)=0.24616/(16+49)=0.246. Three of four alarms are false, though the test looks good by recall and FPR.
  3. Positives score 0.8, 0.6, 0.30.8,\,0.6,\,0.3 and negatives score 0.7, 0.4, 0.20.7,\,0.4,\,0.2. Find the AUC by comparing pairs and describe the ROC curve.
    Show answerPositive 0.80.8 beats all 3 negatives, 0.60.6 beats 2 (0.4 and 0.2), 0.30.3 beats 1 (0.2): 66 of 99 pairs, so AUC =0.667=0.667. Going down the thresholds, the ROC curve steps up, right, up, right, up, right, each step 13\tfrac13 long, from (0,0)(0,0) to (1,1)(1,1).
  4. A 3-class matrix has rows (18,1,1)(18,1,1), (1,1,0)(1,1,0) and (0,1,3)(0,1,3) (true class in rows). Find the accuracy and the macro-averaged recall.
    Show answerAccuracy is (18+1+3)/26=0.846(18+1+3)/26=0.846. The recalls are 18/20=0.9018/20=0.90, 1/2=0.501/2=0.50 and 3/4=0.753/4=0.75, so the macro recall is 0.7170.717. The small classes pull the macro value far below the accuracy.
  5. For targets (3,5,8)(3,5,8) and predictions (2,6,8)(2,6,8) find MAE, RMSE and R2R^2.
    Show answerThe errors are 1,−1,01,-1,0. MAE =0.667=0.667, MSE =0.667=0.667 and RMSE =0.816=0.816. The mean of the targets is 5.3335.333, so ∑(yi−yˉ)2=12.667\sum(y_i-\bar y)^2=12.667 and R2=1−2/12.667=0.842R^2=1-2/12.667=0.842.
  6. Choose a threshold direction (raise it or lower it) and a metric to watch: (a) a screen for a serious but treatable disease where a follow-up test is cheap; (b) an automatic system that blocks a bank account when it sees fraud.
    Show answer(a) Lower the threshold and watch recall, because a miss is costly and a false alarm costs one more test. (b) Raise the threshold and watch precision (and the false positive rate), because blocking an honest customer is costly. Both answers depend on the stated costs: with different costs the choice changes.

Next: P3.A10 asks whether a model’s scores can be read as probabilities (calibration) and what to do when one class is rare. P3.A4 shows how to split the data so that these metrics are honest, and P3.B1 starts the classic algorithms that you can now score.

Key takeaways

  • A binary classifier makes four kinds of outcome: true positive (TP), false positive (FP), false negative (FN) and true negative (TN). The confusion matrix counts them. Every metric in this lesson is built from these four numbers.
  • Accuracy is (TP + TN) / N. It misleads when one class is rare, because always predicting the majority class already scores high. Compare any accuracy with that baseline.
  • Recall = TP / (TP + FN) answers “of the real positives, how many did we find?”. Precision = TP / (TP + FP) answers “of the flagged cases, how many were real?”. Recall and the false positive rate are rates within a class, so they do not change with class balance. Precision does, because it is a posterior (P1.D6).
  • F1 is the harmonic mean of precision and recall, 2TP / (2TP + FP + FN). It stays low unless both are high and it ignores true negatives. F-beta weights recall beta times as much as precision.
  • Most classifiers output a score, and a threshold turns it into a label. Moving the threshold trades false positives against false negatives. The ROC curve plots recall against the false positive rate for every threshold, and the AUC is the probability that a random positive scores above a random negative (ties count half).
  • The AUC does not depend on the threshold or on the class balance, which is also its weakness: with rare positives a high AUC can hide low precision. The precision-recall curve and average precision (no-skill level equal to the positive rate) show it.
  • For many classes, compute precision and recall per class. Macro averaging counts every class equally, weighted averaging counts each by its size, and micro averaging pools the counts (it equals accuracy for single-label problems). Regression uses MAE, RMSE and R-squared.
  • A metric is chosen from the costs of the mistakes and is not the training loss. Choose the threshold and the model on validation data, report once on the test set, and remember that a metric measured on a few examples is noisy.
Found a mistake? Tell us