Classification Metrics
The Confusion Matrix lesson introduced accuracy, precision, recall and F1. This lesson goes deeper: how the metrics trade off against each other, how to choose a threshold, and how to average metrics when there are more than two classes.
Precision vs recall: the threshold trade-off
A classifier that outputs probabilities lets you choose the threshold. Raising it makes the model more cautious: precision goes up, recall goes down. Lowering it does the opposite.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_score, recall_score
data = load_breast_cancer()
y = 1 - data.target # make 1 = malignant (the class we want to catch)
X_tr, X_te, y_tr, y_te = train_test_split(data.data, y, test_size=0.3, random_state=0, stratify=y)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).fit(X_tr, y_tr)
proba = model.predict_proba(X_te)[:, 1]
print("threshold precision recall")
for t in [0.1, 0.3, 0.5, 0.7, 0.9]:
pred = (proba >= t).astype(int)
print(f"{t:9} {precision_score(y_te, pred):9.3f} {recall_score(y_te, pred):6.3f}")threshold precision recall
0.1 0.818 0.984
0.3 0.859 0.953
0.5 0.938 0.938
0.7 1.000 0.922
0.9 1.000 0.875
For cancer screening you'd pick a low threshold: a few extra false alarms (lower precision) are acceptable if fewer real tumours are missed (higher recall).
The precision–recall curve
precision_recall_curve computes both metrics for every possible threshold; average_precision_score summarises the curve in one number (like AUC does for ROC):
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_recall_curve, average_precision_score
data = load_breast_cancer()
y = 1 - data.target
X_tr, X_te, y_tr, y_te = train_test_split(data.data, y, test_size=0.3, random_state=0, stratify=y)
proba = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).fit(X_tr, y_tr).predict_proba(X_te)[:, 1]
precision, recall, thresholds = precision_recall_curve(y_te, proba)
plt.plot(recall, precision)
plt.xlabel("Recall")
plt.ylabel("Precision")
plt.title("Precision-recall curve")
plt.show()
# the highest threshold that still reaches 98 % recall
ok = recall[:-1] >= 0.98
best = thresholds[ok].max()
print(f"average precision: {average_precision_score(y_te, proba):.3f}")
print(f"threshold for >= 98% recall: {best:.3f}")average precision: 0.989
threshold for >= 98% recall: 0.101
F-scores
The F1 score is the harmonic mean of precision and recall; it is only high when both are. The more general F-beta score weights recall β times as much as precision:
from sklearn.metrics import f1_score, fbeta_score, precision_score, recall_score
y_true = [1, 1, 1, 1, 0, 0, 0, 0, 0, 0]
y_pred = [1, 1, 0, 0, 1, 0, 0, 0, 0, 0]
p, r = precision_score(y_true, y_pred), recall_score(y_true, y_pred)
print(f"precision={p:.3f} recall={r:.3f}")
print(f"F1 = {f1_score(y_true, y_pred):.3f} (by hand: {2 * p * r / (p + r):.3f})")
print(f"F2 (recall matters more) = {fbeta_score(y_true, y_pred, beta=2):.3f}")
print(f"F0.5 (precision matters more) = {fbeta_score(y_true, y_pred, beta=0.5):.3f}")precision=0.667 recall=0.500
F1 = 0.571 (by hand: 0.571)
F2 (recall matters more) = 0.526
F0.5 (precision matters more) = 0.625
Multi-class averaging
With more than two classes, precision/recall/F1 are computed per class and then averaged:
average= |
How | Use when |
|---|---|---|
"macro" |
plain mean over classes | every class matters equally |
"weighted" |
mean weighted by class size | you care about overall performance |
"micro" |
count all TP/FP/FN globally | equals accuracy for single-label problems |
None |
no averaging: one score per class | to inspect each class |
from sklearn.metrics import f1_score, accuracy_score
y_true = ["cat"] * 8 + ["dog"] * 8 + ["bird"] * 2
y_pred = ["cat"] * 8 + ["dog"] * 7 + ["cat"] + ["dog", "cat"]
print("per class:", dict(zip(["bird", "cat", "dog"], f1_score(y_true, y_pred, average=None).round(3).tolist())))
for avg in ["macro", "weighted", "micro"]:
print(f"{avg:8} F1 = {f1_score(y_true, y_pred, average=avg):.3f}")
print(f"accuracy = {accuracy_score(y_true, y_pred):.3f}")per class: {'bird': 0.0, 'cat': 0.889, 'dog': 0.875}
macro F1 = 0.588
weighted F1 = 0.784
micro F1 = 0.833
accuracy = 0.833
The rare "bird" class is never predicted correctly. Macro F1 punishes that hard; weighted and micro scores barely notice, because birds are only 2 of 18 animals.
Log loss: judging the probabilities
Accuracy only checks the final label. Log loss (cross-entropy) judges the predicted probabilities themselves: being confidently wrong is punished heavily. Lower is better:
from sklearn.metrics import log_loss
y_true = [1, 0, 1, 1]
careful = [0.8, 0.2, 0.7, 0.9]
overconfident = [0.99, 0.01, 0.01, 0.99] # one confident mistake
print(f"careful: {log_loss(y_true, careful):.3f}")
print(f"overconfident: {log_loss(y_true, overconfident):.3f}")careful: 0.227
overconfident: 1.159
At the 0.5 threshold the careful model gets all four labels right and the overconfident one three. But the log loss gap is much bigger than one mistake suggests: assigning probability 0.01 to something that then happened is punished very heavily.
Test yourself
What usually happens to recall when you raise the decision threshold?
- It increases
- It decreases (or stays the same)
- It becomes equal to precision
- It is unaffected
Which averaging gives every class equal weight, regardless of its size?
- micro
- weighted
- macro
- samples
Which F-beta score emphasises recall over precision?
- F0.5
- F1
- F2
- None of them