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 spam | predicted not spam | |
|---|---|---|
| actually spam | TP = 14 | FN = 6 |
| actually not spam | FP = 10 | TN = 170 |
Rows are the truth and columns the prediction, as in P2.4. The row totals are the class sizes ( spam, 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 , 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:
where 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 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 . 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? . It is also called sensitivity or the true positive rate (TPR).
- Precision: of the 24 emails it flagged, how many were really spam? . 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? .
- False positive rate (FPR): of the 180 non-spam emails, how many were flagged? , which is .
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 , 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 and a false positive rate of , 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 finds of the 100 sick people (, ).
- An FPR of flags of the 9900 healthy people (, ).
- Precision is . Most alarms are false.
If half the people were sick, the same recall and FPR would give a precision of . If the FPR drops to with 1% sick, precision rises to . The recall and FPR describe the test, and they do not change with the mix of people. Precision is , 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:
For the spam filter, .
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 and its recall is . The ordinary mean is , which sounds acceptable for a filter that finds 5% of the spam. The harmonic mean is . 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. treats recall as times as important as precision:
For the spam filter (recall-heavy, because gets weight 4) and (precision-heavy). gives .
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 . The usual default is , but it is a choice, not part of the model.
Moving 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 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 goes from 1 down to 0. Try these:
- Set the threshold to 0.5 with 1:1. The counts are TP 90, FN 10, FP 10, TN 90: recall and FPR , the numbers of the medical test above.
- 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.
- Open the precision-recall tab and compare the curve at 1:1 and at 99:1.
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:
- : the threshold is so high that nothing is called positive. : so low that everything is.
- , 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 to is a classifier that ignores its input. If it calls each example positive with probability , then recall and FPR both equal .
- 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):
| score | positives | negatives |
|---|---|---|
| 0.9 | 2 | 1 |
| 0.7 | 1 | 1 |
| 0.4 | 1 | 2 |
Lower the threshold step by step. At the model flags 2 positives and 1 negative, so recall and FPR . At : 3 positives and 2 negatives, which is . At everything is flagged: . The ROC points are
The AUC is the area under the curve, found with the trapezoid rule of P1.C9. The three trapezoids have areas , and , and
A segment such as 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 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 and together . The positive at 0.7 beats two negatives and ties with one: . The positive at 0.4 ties with two negatives: . The total is , and , 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 ranks positives and negatives like a coin flip; 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 , where and 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 instead of looking at all 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 are exactly what they were at 1:1, but at threshold 0.5 the precision has fallen to . How can both be true? FPR measures false alarms against the number of negatives. With 9900 negatives, an FPR of is 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 at 1:1, at 4:1, at 9:1 and at 99:1, against no-skill levels of , , and . A model with an AP of 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:
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 (the three steps are at ), while the trapezoid area from scikit-learn’s curve is .
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, for the spam filter. It stays low when the model ignores the rare class, and “always not spam” scores . The Matthews correlation coefficient uses all four counts. Its numerator is and its denominator is the square root of the product of the four totals (two row totals and two column totals). It is here. It ranges from to and is 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 classes the confusion matrix is . Here is the one from P2.4 (rows are the true class): 150 images, of which 133 are correct, so the accuracy is .
| called cat | called dog | called bird | |
|---|---|---|---|
| true cat | 48 | 2 | 0 |
| true dog | 5 | 40 | 5 |
| true bird | 1 | 4 | 45 |
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, (the 5 true dogs called cats and the 5 called birds are misses), and precision is the diagonal entry over its column, .
| class | precision | recall | F1 |
|---|---|---|---|
| cat | 0.889 | 0.960 | 0.923 |
| dog | 0.870 | 0.800 | 0.833 |
| bird | 0.900 | 0.900 | 0.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 () and the micro value is the accuracy, . 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 against a micro value (the accuracy) of , 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 . Use the best line for the three points of P3.A1 (fitted in P3.A2): the errors are .
- Mean absolute error: . In the units of , and each error counts in proportion to its size.
- Mean squared error: . It punishes large errors more, and it is the training loss of P3.A2. RMSE is back in the units of .
- R-squared: . It compares the model with the baseline that predicts the mean for every example: means no better than that baseline, and it is negative for a model that is worse (a constant 5 gives ). 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 per miss and per false alarm, the cost to minimize is . 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 (1 miss and 35 false alarms, a cost of 45) instead of (a cost of 110). If a false alarm costs ten times a miss, it is (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 of the positive class, and correct decisions cost nothing, predicting positive is the cheaper choice when , which gives the threshold . With a miss ten times as costly, . 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 near (P1.D8). A recall of measured on only 20 positives has a standard error of , so a rough 95% interval is about . 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: ; is their sum; real positives.
With positive rate , recall and false positive rate , Bayes’ theorem gives the precision
For scores and a threshold : predict positive when . ROC curve: the points . With scores of positives and of negatives,
Average precision: over the distinct thresholds, with . Macro average: ; weighted: ; micro: the metric of the summed counts. Regression: , , .
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.6083The 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 against for always saying “not spam”, precision , recall , specificity , FPR , , , , and the mean against the harmonic mean for the filter that flags one email.
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 both ways, AP , and on the random data AUC in all three cases, with AP at a positive rate of and at .
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 , micro ), then the unbalanced matrix (macro , weighted , micro ). Change the matrix to see which average reacts.
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 , MSE , RMSE and , then for predicting the mean and for predicting the constant 5.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Check your understanding
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?
Model A is right on all 1980 honest transactions, so its accuracy is . Model B gets right, which is . The accuracy is higher for A, yet its recall is . Model B does not have the higher accuracy, and the two are not equal. Precision of Model A is , undefined, not .
A classifier has precision and recall . What is its F1 score?
. The ordinary mean would hide the very low recall, which is the reason F1 uses the harmonic mean. The product is not a mean. A high precision does not make F1 high when recall is low.
A model has an AUC of . What does this say?
The AUC is the probability that a random positive outscores a random negative, so it measures ranking over all thresholds. It is not an accuracy at any one threshold, and it does not fix a precision. A model that found of the positives with no false alarms would have a ROC curve that reaches recall at an FPR of , which does not follow from an AUC of .
A model has an AUC of on a data set where of the examples are positive. Which statement can still be true?
The AUC uses rates within each class, so a small FPR on a huge negative class can still mean more false alarms than hits. The AUC does not set a precision, and it is computed correctly at any balance; it answers a ranking question. The no-skill level of the precision-recall curve is the positive rate, .
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?
Macro averaging gives the two small classes two thirds of the weight, so their poor scores pull the number down. Micro averaging, accuracy and the weighted average are all dominated by the 1000-example class, so they stay high and hide the failure.
Exercises
- A test set has 40 positives and 960 negatives. The model gives and . Find , , accuracy, precision, recall, FPR and F1, and the accuracy of always predicting negative.
Show answer
and . Accuracy is , precision , recall , FPR and . Always negative scores , higher than the model’s accuracy, so the model needs a metric other than accuracy. - A test has recall and a false positive rate of . Its precision if of the people tested are positive?
Show answer
Per 1000 people: positive, so ; negative, so . Precision is . Three of four alarms are false, though the test looks good by recall and FPR. - Positives score and negatives score . Find the AUC by comparing pairs and describe the ROC curve.
Show answer
Positive beats all 3 negatives, beats 2 (0.4 and 0.2), beats 1 (0.2): of pairs, so AUC . Going down the thresholds, the ROC curve steps up, right, up, right, up, right, each step long, from to . - A 3-class matrix has rows , and (true class in rows). Find the accuracy and the macro-averaged recall.
Show answer
Accuracy is . The recalls are , and , so the macro recall is . The small classes pull the macro value far below the accuracy. - For targets and predictions find MAE, RMSE and .
Show answer
The errors are . MAE , MSE and RMSE . The mean of the targets is , so and . - 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.