Sub topic 3
F1 score: combining precision and recall
Assume you know confusion matrices, precision, recall, basic Python, and train/test splits. This chapter connects these measures and shows how to report them safely.
F1 score
The F1 score combines precision and recall into one number. It is their harmonic mean:
\[ F1 = \frac{2 \times precision \times recall}{precision + recall} \]
The harmonic mean gives a low score when either input is low. With precision and recall both equal to 0.75:
\[ F1 = \frac{2 \times 0.75 \times 0.75}{0.75 + 0.75} = 0.75 \]
F1 is useful when false positives and false negatives both matter. It does not include true negatives, so it may be unsuitable when correctly identifying negative cases is important.
Moving the threshold: precision versus recall
A classifier often produces a score between 0 and 1. A decision threshold converts that score into a class. For example, scores at least 0.5 become positive predictions.
Raising the threshold usually produces fewer positive predictions. Precision can rise because the remaining positives are more trustworthy, while recall can fall because some real positives are missed. Lowering the threshold usually has the opposite effect.
Choose the threshold using validation data and the cost of each error. Do not choose it by looking at the test labels.
Computing metrics with scikit-learn
from sklearn.metrics import (
accuracy_score, f1_score, precision_score, recall_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]
print(accuracy_score(y_true, y_pred)) # 0.8
print(precision_score(y_true, y_pred)) # 0.75
print(recall_score(y_true, y_pred)) # 0.75
print(f1_score(y_true, y_pred)) # 0.75Check these results against manual calculations. This can reveal reversed labels or an incorrect positive-class choice.
Multiclass averaging
For multiclass classification, calculate metrics per class, treating each class as the positive class.
- Macro average gives every class equal weight. It exposes poor performance on rare classes.
- Weighted average weights each class by its number of true examples. It reflects overall data distribution but can hide rare-class failures.
- Micro average combines all classes' decisions before calculating the metric. Frequent classes dominate it.
State the averaging method whenever you report a multiclass score.
Common pitfalls when reporting metrics
- Do not report only accuracy on imbalanced data.
- Do not tune a threshold on the test set.
- Check whether the positive label is encoded as intended.
- Handle cases with no predicted positives. Precision may be undefined; configure an explicit zero-division policy.
- Report class support, meaning the number of true examples per class.
- Use a separate validation set or cross-validation when selecting models or thresholds.
Exercise
A model has precision 0.8 and recall 0.5. What is its F1 score?
Show answer
F1 = 2 × 0.8 × 0.5 ÷ (0.8 + 0.5) ≈ 0.62.