Sub topic 5
Precision: How Trustworthy Are Positive Predictions
This chapter assumes you can read a confusion matrix (TP, FP, TN, FN), write basic Python, and know why a model is scored on held-out test data. Precision answers one question: when the model says "positive", how often is it right?
The definition
Precision is the share of positive predictions that are truly positive.
precision = TP / (TP + FP)The denominator, TP + FP, is every sample the model labeled positive. It is the "predicted positive" column of the confusion matrix. Precision never looks at the "predicted negative" column.
Here are the ten labels and predictions from the previous chapters.
y_true = [1, 0, 1, 1, 0, 0, 0, 0, 0, 1]
y_pred = [1, 0, 0, 1, 0, 1, 0, 0, 0, 1]
tp = sum(t == 1 and p == 1 for t, p in zip(y_true, y_pred))
fp = sum(t == 0 and p == 1 for t, p in zip(y_true, y_pred))
precision = tp / (tp + fp)
print(tp, fp, precision) # 3 1 0.75The model made four positive predictions and three were correct, so precision is 3 / 4 = 0.75.
Reading precision as a probability
Precision estimates the probability that a sample is positive, given that the model predicted positive. A precision of 0.75 means that if you pick one flagged item at random, there is about a 75% chance it is a real positive. This makes precision the right number for a person who acts on each positive prediction, such as an analyst reviewing alerts.
The complement, 1 - precision, is the false discovery rate. It is the share of flagged items that are wasted effort.
What precision ignores
Precision does not use FN or TN. A model can score a perfect precision by predicting positive only when it is extremely sure.
y_true = [1, 0, 1, 1, 0, 0, 0, 0, 0, 1]
y_pred = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0] # only one positive prediction
tp = sum(t == 1 and p == 1 for t, p in zip(y_true, y_pred))
fp = sum(t == 0 and p == 1 for t, p in zip(y_true, y_pred))
fn = sum(t == 1 and p == 0 for t, p in zip(y_true, y_pred))
print(tp / (tp + fp)) # 1.0
print(tp / (tp + fn)) # 0.25Precision is 1.0, yet the model missed three of the four real positives. This is why precision is always reported next to recall. Either number alone can be gamed by a model that is very timid or very eager.
Precision depends on how rare positives are
Precision, unlike recall, depends on the class balance of the data it is measured on. Recall (the true positive rate) and the false positive rate are properties of the model's behavior on each class. Precision mixes the two classes, so it shifts when the share of positives changes.
The next function holds the classifier fixed, with 90% recall and a 5% false positive rate. It varies only the prevalence, the fraction of samples that are positive.
def precision_at(prevalence, n=10000, tpr=0.9, fpr=0.05):
positives = n * prevalence
negatives = n - positives
tp = positives * tpr
fp = negatives * fpr
return tp / (tp + fp)
for prevalence in (0.5, 0.1, 0.01):
print(prevalence, round(precision_at(prevalence), 3))
# 0.5 0.947
# 0.1 0.667
# 0.01 0.154The model did not change, but precision fell from 0.947 to 0.154. At 1% prevalence there are 9,900 negatives, and 5% of them is 495 false positives. These swamp the 90 true positives.
This effect is the reason precision is the more informative metric on imbalanced problems. Accuracy hides it. With 1% fraud and a 5% false positive rate, accuracy stays above 94%, while 85% of fraud alerts are false alarms.
Computing precision with scikit-learn
precision_score takes the true labels first and the predictions second.
from sklearn.metrics import confusion_matrix, precision_score
y_true = [1, 0, 1, 1, 0, 0, 0, 0, 0, 1]
y_pred = [1, 0, 0, 1, 0, 1, 0, 0, 0, 1]
tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()
print(tn, fp, fn, tp) # 5 1 1 3
print(tp / (tp + fp)) # 0.75
print(precision_score(y_true, y_pred)) # 0.75Two details matter here.
confusion_matrix(...).ravel()returns the cells in the order TN, FP, FN, TP for binary labels 0 and 1. Unpacking them in a different order silently gives wrong numbers.- By default
precision_scoretreats label1as the positive class. If your positive class is a string such as"spam", or if it is0, passpos_label.
from sklearn.metrics import precision_score
y_true = ["ham", "spam", "spam", "ham", "spam"]
y_pred = ["ham", "spam", "ham", "spam", "spam"]
print(precision_score(y_true, y_pred, pos_label="spam")) # 0.6666666666666666Here the model predicted "spam" three times and was right twice.
The argument-order trap
If you swap the two arguments, scikit-learn treats your predictions as the truth. The call still runs, and it returns recall instead of precision.
from sklearn.metrics import precision_score, recall_score
y_true = [1, 0, 1, 1, 0, 0, 0, 0, 0, 1]
y_pred = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
print(precision_score(y_true, y_pred)) # 1.0
print(precision_score(y_pred, y_true)) # 0.25 (this is really recall)
print(recall_score(y_true, y_pred)) # 0.25On the earlier ten-sample example, precision and recall are both 0.75, so a swap would go unnoticed. When you check your code, use an example where the two values differ.
The zero-division case
If the model never predicts positive, TP + FP is 0 and the formula becomes 0 / 0. Precision is undefined. This happens in practice with a very conservative model, a high threshold, or a tiny batch.
Scikit-learn returns 0.0 and emits an UndefinedMetricWarning by default. The zero_division parameter makes the choice explicit.
from sklearn.metrics import precision_score
y_true = [1, 0, 1, 0]
y_pred = [0, 0, 0, 0] # no positive predictions
print(precision_score(y_true, y_pred, zero_division=0)) # 0.0
print(precision_score(y_true, y_pred, zero_division=1)) # 1.0Neither value is "correct". Setting 0 is the pessimistic convention. Setting 1 follows the argument that a model that made no claims made no wrong claims. Pick one, state it, and note that the metric was undefined. If you average precision over many folds or groups, a silent default can shift the average.
How the threshold moves precision
Most classifiers output a score, and a threshold turns the score into a label. Raising the threshold tends to raise precision, because only the most confident samples remain positive predictions. It also lowers recall.
The relationship is not strictly monotonic. Removing one positive prediction can lower precision if that prediction was a true positive.
y_true = [1, 1, 0, 1, 0, 0]
scores = [0.9, 0.8, 0.7, 0.6, 0.3, 0.2]
for threshold in (0.5, 0.65, 0.75):
y_pred = [int(s >= threshold) for s in scores]
tp = sum(t == 1 and p == 1 for t, p in zip(y_true, y_pred))
fp = sum(t == 0 and p == 1 for t, p in zip(y_true, y_pred))
print(threshold, round(tp / (tp + fp), 2))
# 0.5 0.75
# 0.65 0.67
# 0.75 1.0Going from 0.5 to 0.65 removes the true positive scored 0.6 and keeps the false positive scored 0.7, so precision drops. At 0.75 the false positive is gone and precision reaches 1.0. A later chapter covers the full precision-recall trade-off. For now, remember that precision at a given threshold is noisy when few samples sit above it.
When to favor precision
Favor precision when a false positive is more costly than a missed positive. The question to ask is what happens each time the model raises a flag.
| Situation | Cost of a false positive | Why precision matters |
|---|---|---|
| Spam filter that deletes mail | A legitimate email is lost | Users lose trust quickly |
| Automatic account suspension | A real customer is locked out | Support cost and churn |
| Fraud alerts sent to a small review team | Reviewer time is wasted | Capacity is limited |
| Recommending a product for a paid promotion | Money spent on a wrong target | Direct cost per positive |
Precision is a weaker guide when missing a positive is the larger harm, as in screening for a serious disease. There, recall comes first. The next chapters on error costs and F1 return to this choice.
Common errors
- Reporting precision alone. A model with one correct positive prediction has precision 1.0. Always pair it with recall.
- Reporting a ratio without its denominator. "100% precision" from 1 of 1 predictions means little. Report TP and FP counts, or the number of positive predictions.
- Computing precision on training data. A model can look precise on samples it has memorized. Use a held-out test set.
- Comparing across different class balance. See the prevalence example above.
- Using the wrong positive class. For multi-class or string labels, set
pos_labelor anaverageoption deliberately. - Ignoring the undefined case. Set
zero_divisionand state what you chose.
Exercise
A model flags 40 transactions as fraud. Reviewers confirm 30 of them are fraud. Of the 1,000 transactions in the test set, 50 were actually fraud. What is the precision, and what does it say about the 20 frauds the model did not flag?
Show answer
Precision is TP / (TP + FP) = 30 / 40 = 0.75. The 20 missed frauds (50 real frauds minus 30 caught) are false negatives, and precision does not use them at all. Their effect shows up in recall, which is 30 / 50 = 0.6.
Exercise
A classifier has 80% recall and a 2% false positive rate. Using the formula in this chapter, what is its precision on 10,000 samples when 5% are positive? Round to two decimals.
Show answer
Positives = 500 and negatives = 9,500. TP = 500 0.8 = 400 and FP = 9,500 0.02 = 190. Precision = 400 / (400 + 190) = 400 / 590, which is about 0.68. At lower prevalence the same model would have lower precision.
Exercise
You call precisionscore(ypred, y_true) by mistake, with the arguments swapped. Which metric do you actually get, and why can this go unnoticed on some datasets?
Show answer
You get recall. The predictions are treated as the true labels, so the "predicted positives" in the denominator become the real positives. If precision and recall happen to be equal, as in the ten-sample example where both are 0.75, the swap produces the same number and no error is visible.