Sub topic 9
Choosing evaluation metrics
This chapter assumes you can train a scikit-learn classifier and read a confusion matrix at a basic level. A metric is the number you use to judge a model. It should come from the problem you framed, not from whatever the library prints first.
Why accuracy often misleads
Accuracy is the share of predictions that are correct. It fails when classes are imbalanced. If 1% of transactions are fraud, a model that always predicts "not fraud" scores 99% accuracy and catches nothing.
The confusion matrix counts four outcomes for a binary problem:
- True positive (TP): predicted positive, actually positive.
- False positive (FP): predicted positive, actually negative.
- False negative (FN): predicted negative, actually positive.
- True negative (TN): predicted negative, actually negative.
Precision, recall and F1
- Precision = TP / (TP + FP). Of the cases you flagged, how many were real?
- Recall = TP / (TP + FN). Of the real cases, how many did you find?
- F1 is the harmonic mean of precision and recall. It is low when either one is low.
Pick based on which error costs more. A cancer screening test usually favors recall, because a missed case is worse than an extra follow-up. A spam filter that deletes mail favors precision, because losing a real message is worse than seeing some spam.
Threshold-free metrics
Most classifiers output a probability, and a threshold (often 0.5) turns it into a class. ROC AUC measures how well the model ranks positives above negatives across all thresholds. PR AUC (average precision) does the same for the precision and recall trade-off. On heavily imbalanced data, PR AUC is usually more informative, because ROC AUC can look high even when precision is poor.
Regression metrics
For numeric targets, three metrics are common:
| Metric | Meaning | Note |
|---|---|---|
| MAE | Mean absolute error | Same units as the target. Treats all errors equally. |
| RMSE | Root mean squared error | Same units as the target. Penalizes large errors more. |
| R² | Share of variance explained | Unitless. Can be negative for a bad model. |
Computing metrics in code
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
accuracy_score, precision_score, recall_score, f1_score,
average_precision_score, roc_auc_score, confusion_matrix,
)
from sklearn.model_selection import train_test_split
X, y = make_classification(
n_samples=2000, weights=[0.95, 0.05], random_state=0
)
X_tr, X_te, y_tr, y_te = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0
)
clf = LogisticRegression(max_iter=1000).fit(X_tr, y_tr)
pred = clf.predict(X_te)
proba = clf.predict_proba(X_te)[:, 1]
print("accuracy :", accuracy_score(y_te, pred))
print("precision:", precision_score(y_te, pred))
print("recall :", recall_score(y_te, pred))
print("f1 :", f1_score(y_te, pred))
print("roc auc :", roc_auc_score(y_te, proba))
print("pr auc :", average_precision_score(y_te, proba))
print(confusion_matrix(y_te, pred))Compare accuracy with recall in the output. With 5% positives, accuracy will look strong even when recall is modest.
Common errors
- Reporting accuracy on imbalanced data without a baseline.
- Choosing the metric after seeing results. Fix it during problem framing.
- Passing hard predictions to
roc_auc_scoreinstead of probabilities. - Using the test set to pick a threshold. Choose it on validation data or with cross-validation.
- Using the same metric in
scoring=during tuning that you report at the end. Mismatches give models optimized for the wrong goal.
Exercise
A model detects a rare disease in 2% of patients. It predicts "healthy" for everyone. What are its accuracy and recall, and which metric would you track instead?
Show answer
Accuracy is 98% and recall is 0%, because it finds none of the sick patients. Track recall, together with precision or PR AUC, since missing a sick patient is the costly error.