Sub topic 5
Precision: how trustworthy a positive prediction is
This chapter assumes you can read a binary confusion matrix (you know the four cells TP, FP, FN and TN) and can follow short Python snippets that use scikit-learn. Everything here builds on those four counts.
The question precision answers
When the model says "positive", how often is it right? That is precision. It looks only at the cases the model flagged and asks what share of them were real positives.
precision = TP / (TP + FP)The denominator, TP + FP, is every case the model predicted as positive. In a matrix with actual labels in rows and predicted labels in columns, that is the whole positive-prediction column. Precision is therefore a column-wise measure. Recall, which you meet in the next chapter, is its row-wise counterpart.
Other fields use other names for the same quantity. Information retrieval and most machine learning libraries say "precision". Medicine and diagnostics often say positive predictive value (PPV). Both names mean TP / (TP + FP).
A worked example
Use the same ten labels as before. Rows are actual labels and columns are predicted labels.
from sklearn.metrics import confusion_matrix, precision_score
y_true = [1, 0, 1, 1, 0, 0, 1, 0, 0, 0]
y_pred = [1, 0, 0, 1, 0, 1, 1, 1, 0, 0]
cm = confusion_matrix(y_true, y_pred, labels=[0, 1])
print(cm)
# [[4 2]
# [1 3]]
tn, fp, fn, tp = cm.ravel()
print(tp / (tp + fp)) # 0.6
print(precision_score(y_true, y_pred)) # 0.6
# The same number read straight from the positive-prediction column.
positive_column = cm[:, 1] # [2 3]: FP on top, TP below
print(positive_column[1] / positive_column.sum()) # 0.6The model made five positive predictions (2 + 3). Three were correct. Precision is 3/5 = 0.6, so about 40% of the alerts this model raises are false alarms.
Notice what precision ignores. The cell FN (1) and the cell TN (4) never appear in the formula. A model could miss half of all real positives and still have perfect precision, as long as the few cases it does flag are correct.
What a precision value means in practice
Precision measures the cost of acting on a positive prediction. A low value means that cost is wasted often. Whether that matters depends on what happens after the model says "positive".
| Situation | What a false positive costs | How much precision matters |
|---|---|---|
| Spam filter moving mail to a junk folder | A real message is hidden | High. Users lose trust quickly |
| Fraud alert that freezes a card | A customer is blocked from paying | High |
| First-pass screening for a disease | An extra, cheap follow-up test | Lower. Missing a case costs more |
| Recommending a video | A few seconds of attention | Low |
A useful habit is to say precision out loud as a sentence: "Of everything we flagged, this share was correct." If that sentence describes what your stakeholders care about, precision is the right headline metric. If they care more about "of everything real, how much did we catch", look at recall instead.
Precision depends on how common the positive class is
Precision is not a fixed property of a model. It also depends on how often the positive class occurs in the data you test on. The reason is that FP grows with the number of negatives, while TP grows with the number of positives.
Take one classifier that finds 80% of positives (true positive rate 0.8) and wrongly flags 10% of negatives (false positive rate 0.1). Apply it to two datasets.
tpr = 0.80
fpr = 0.10
def precision_for(positives, negatives):
tp = tpr * positives
fp = fpr * negatives
return tp / (tp + fp)
print(precision_for(100, 100)) # about 0.889, balanced data
print(precision_for(100, 1000)) # about 0.444, 10 negatives per positive
print(precision_for(100, 10000)) # about 0.074, 100 negatives per positiveThe classifier did not change. Its recall and its false positive rate stayed the same. Yet precision fell from about 0.89 to about 0.07, because negatives became far more common and a 10% false alarm rate now produces many more false alarms than there are real hits.
This is also why a high-looking recall and a low false positive rate can coexist with a precision you would not want to ship. Always compute precision on data with a realistic positive rate.
Precision moves with the decision threshold
Most classifiers output a score, and a threshold turns the score into a label. Raising the threshold makes the model more selective. Here are three thresholds applied to the same scores.
from sklearn.metrics import confusion_matrix, precision_score
y_true = [1, 0, 1, 1, 0, 0, 1, 0, 0, 0]
scores = [0.9, 0.2, 0.4, 0.8, 0.1, 0.7, 0.6, 0.55, 0.3, 0.35]
for threshold in (0.35, 0.5, 0.65):
y_pred = [1 if s >= threshold else 0 for s in scores]
print(threshold)
print(confusion_matrix(y_true, y_pred, labels=[0, 1]))
print(precision_score(y_true, y_pred))| Threshold | TP | FP | FN | Precision |
|---|---|---|---|---|
| 0.35 | 4 | 3 | 0 | 4/7, about 0.571 |
| 0.50 | 3 | 2 | 1 | 3/5 = 0.6 |
| 0.65 | 2 | 1 | 2 | 2/3, about 0.667 |
Precision rose as the threshold rose, because the borderline positive predictions were removed and most of those were false alarms. The price is visible in the FN column: missed positives went from 0 to 2.
This pattern is common but not guaranteed. Precision usually trends upward as the threshold rises, yet it can dip locally. Removing one true positive from a small set of predictions can lower precision even as the threshold rises. With few predictions, precision is a jumpy function of the threshold. Do not draw a smooth curve through five points and trust it.
Edge case: no positive predictions
If the model predicts no positives at all, then TP + FP = 0 and precision is 0/0, which is undefined. This happens with models that always predict the majority class, such as the 95/5 example earlier in the tutorial.
scikit-learn does not crash. It returns a value you choose with the zero_division argument.
from sklearn.metrics import precision_score
y_true = [0, 1, 0, 1]
y_pred = [0, 0, 0, 0] # the model never predicts the positive class
print(precision_score(y_true, y_pred, zero_division=0)) # 0.0
print(precision_score(y_true, y_pred, zero_division=1)) # 1.0If you leave zero_division at its default of "warn", you get 0.0 plus a warning. Setting it explicitly is better, because the choice affects how averages and reports look. Neither 0 nor 1 is "correct". The honest reading is that precision is undefined when the model made no positive claims. Report it together with recall, which will be 0 in this case and exposes the real problem.
A related small-sample problem: precision based on very few positive predictions is noisy. A model with 1 true positive and 0 false positives has precision 1.0, but that number comes from a single case. Report the counts alongside the ratio when the denominator is small.
Precision in a multiclass matrix
In a matrix with more than two classes, each class has its own precision. For class k, divide the diagonal cell by the sum of its predicted column.
from sklearn.metrics import confusion_matrix, precision_score
labels = ["bird", "cat", "dog"]
y_true = ["cat", "cat", "cat", "dog", "dog", "dog", "bird", "bird", "bird", "bird"]
y_pred = ["cat", "cat", "dog", "dog", "dog", "dog", "bird", "cat", "bird", "bird"]
cm = confusion_matrix(y_true, y_pred, labels=labels)
print(cm)
# [[3 1 0]
# [0 2 1]
# [0 0 3]]
print(cm.diagonal() / cm.sum(axis=0))
# [1. 0.66666667 0.75 ]
print(precision_score(y_true, y_pred, labels=labels, average=None))
# [1. 0.66666667 0.75 ]Read down each column. Every time the model said "bird" it was right (3 of 3). When it said "cat", one of three predictions was actually a bird, so precision is 2/3. When it said "dog", one of four was actually a cat, so precision is 3/4. The off-diagonal entries in a column tell you what the false positives for that class really were.
Common mistakes
- Dividing by the wrong total. Precision divides by predicted positives (a column), not by actual positives (a row). If you divide TP by TP + FN you have computed recall.
- Reading the matrix with the axes swapped. Check which axis holds actual labels before choosing the column. If your tool puts predictions on the rows, precision is read along a row.
- Reporting precision alone. A model can reach precision 1.0 by predicting positive rarely. Always pair it with recall, or with F1, which is covered later in this tutorial.
- Comparing precision across datasets with different positive rates, as shown above.
- Treating an undefined value as zero without saying so.
Exercise
A fraud model flags 200 transactions in a test set. Of those, 150 are real fraud. The test set contains 300 real fraud cases in total. What is the precision, and which of the numbers given is not needed to compute it?
Show answer
Precision = TP / (TP + FP) = 150 / 200 = 0.75. The 300 real fraud cases is not needed. It is the denominator of recall (150 / 300 = 0.5), not precision.
Exercise
A classifier has a true positive rate of 0.9 and a false positive rate of 0.05. It is tested on 50 real positives and 1000 real negatives. Compute TP, FP and precision. Then say what happens to precision if the test set had only 100 negatives, with everything else unchanged.
Show answer
TP = 0.9 × 50 = 45 and FP = 0.05 × 1000 = 50, so precision = 45 / 95, about 0.474. With 100 negatives, FP = 5 and precision = 45 / 50 = 0.9. The model is the same, but precision rises because there are fewer negatives to produce false alarms.
Exercise
In the three-class matrix [[3, 1, 0], [0, 2, 1], [0, 0, 3]] (rows actual, columns predicted, order bird, cat, dog), what is the precision of "cat", and which class are the false positives for "cat" coming from?
Show answer
The cat column is [1, 2, 0], so precision = 2 / 3, about 0.667. The one false positive is a bird that was predicted as a cat.