Sub topic 1
What Class Imbalance Is and Where It Appears
Prerequisites
This chapter assumes basic Python, NumPy, binary classification, train/test splits, cross-validation, and scikit-learn estimators.
Class Imbalance in Practice
A dataset has class imbalance when one label occurs much more often than another. The common label is the majority class. The less common label is the minority class. In fraud detection, legitimate transactions may outnumber fraud cases by hundreds to one. In disease screening, healthy patients may greatly outnumber patients with the disease.
The minority class is often the important class. A missed fraud case or missed diagnosis can cost more than an unnecessary investigation.
The Accuracy Pitfall
Accuracy is the fraction of all predictions that are correct. With 95% negative examples, a model that always predicts negative achieves about 95% accuracy while detecting no positive examples.
from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score, recall_score
baseline = DummyClassifier(strategy="most_frequent")
baseline.fit(X_train, y_train)
predictions = baseline.predict(X_test)
print(accuracy_score(y_test, predictions))
print(recall_score(y_test, predictions))The second score is more revealing: recall is zero because the model finds none of the rare cases.
Confusion-Matrix Metrics
A confusion matrix counts four outcomes:
- True positive (TP): a positive case predicted as positive.
- False positive (FP): a negative case predicted as positive.
- True negative (TN): a negative case predicted as negative.
- False negative (FN): a positive case predicted as negative.
| Metric | Formula | Meaning |
|---|---|---|
| Precision | TP / (TP + FP) | Of predicted positives, how many were correct |
| Recall | TP / (TP + FN) | Of actual positives, how many were found |
| F1 | 2 × precision × recall / (precision + recall) | Balance between precision and recall |
Use recall when missing a positive is especially costly. Use precision when false alarms are expensive. F1 summarizes both, but it does not replace cost-based reasoning.
Precision-Recall and ROC Curves
A classifier often produces a score or probability before applying a decision threshold. Changing that threshold changes precision and recall.
A precision-recall curve shows this trade-off across thresholds. It is usually more informative for rare positive classes. An ROC curve compares true-positive rate with false-positive rate. ROC curves are useful for general ranking, but can look strong when negatives dominate. For imbalanced classification, inspect average precision and the operating point that matches the application's costs.
Exercise
A model has 98% accuracy but zero recall for the positive class. Is it useful for finding positive cases?
Show answer
No. It never finds a positive case, so accuracy is hiding the failure.