Sub topic 2
Precision: How Trustworthy Is a Positive Prediction?
Assume you know basic supervised classification, fractions, and short Python snippets. This chapter uses binary classification, where class 1 is the positive class.
Precision: How Trustworthy a Positive Prediction Is
Precision is the fraction of positive predictions that are correct:
\[ \text{precision}=\frac{TP}{TP+FP} \]
Here, TP means true positives, and FP means false positives. Precision answers: “When the model predicts positive, how often is it right?”
| Actual outcome | Predicted positive | Predicted negative |
|---|---|---|
| Positive | TP | FN |
| Negative | FP | TN |
from sklearn.metrics import 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]
print(precision_score(y_true, y_pred)) # 0.6The model made five positive predictions. Three were correct, so its precision is \(3/5=0.6\).
Recall: How Many Real Positives Were Found
Recall, also called sensitivity, is the fraction of actual positives that the model finds:
\[ \text{recall}=\frac{TP}{TP+FN} \]
FN means false negatives: real positives that the model missed. In the example, there are four actual positives and three were found, so recall is \(3/4=0.75\).
flowchart TD
A[Positive prediction] --> B[True positive: correct]
A --> C[False positive: incorrect]
D[Actual positive] --> B
D --> E[False negative: missed]Why Accuracy Misleads on Imbalanced Data
Accuracy is the share of all predictions that are correct:
\[ \text{accuracy}=\frac{TP+TN}{TP+TN+FP+FN} \]
With imbalanced data, one class is much more common than the other. Suppose 95 records are negative and only 5 are positive. A model that always predicts negative gets 95% accuracy, but its recall for the positive class is zero. It finds none of the cases that matter.
Use precision and recall when the positive class is rare or when different error types have different costs.
F1: Combining Precision and Recall
The F1 score is the harmonic mean of precision and recall:
\[ F1=2\frac{\text{precision}\times\text{recall}} {\text{precision}+\text{recall}} \]
It is high only when both measures are high. F1 is useful when you need a single score but want to penalize a model that sacrifices either trustworthy alerts or coverage.
Exercise
A model has TP = 8, FP = 2, and FN = 4. What are its precision, recall, and F1 score?
Show answer
Precision = 8/10 = 0.80. Recall = 8/12 ≈ 0.67. F1 ≈ 0.73.