Lesson 4.11 · 8 min read · about 50 min to master at a very slow pace
Class Imbalance
When the interesting class is rare, a model can score high accuracy while catching nothing. Baselines, the right metrics, threshold moves, oversampling and stratified sampling, and the oversampling traps.
The accuracy trap
When the interesting class is rare (fraud, a rare disease, equipment failure), a classifier minimising overall error can learn to ignore it. With 0.5% fraud, predicting "not fraud" for everyone scores 99.5% accuracy and catches zero fraud.
Remedies
- Use the right metrics: sensitivity, specificity, precision, ROC/AUC, a confusion matrix; and compare with the majority-class baseline.
- Move the threshold using the costs of each error (4.9).
- Oversample the rare class (or undersample the common one) in the training data, so the model pays attention to it.
- Use class weights: count each rare-class error as more expensive in the loss.
A stratified oversampling procedure
- Split the data into set A (the class of interest) and set B (everything else).
- Training set: randomly take 50% of A, plus an equal number of cases from B. This makes training balanced.
- Validation set: the remaining 50% of A, plus enough of B to restore the original class ratio.
Result: a somewhat worse overall error rate, but typically a much better error rate on the cases that matter. Validation stays representative of the real world.
Oversampling traps
- Never oversample before splitting. Copies of the same record land in both training and validation, inflating scores (leakage).
- Evaluate on data with the original class ratio, otherwise precision and accuracy are meaningless for deployment.
- After oversampling, predicted probabilities are no longer calibrated to the real prevalence; adjust before using them for cost-based thresholds.
How it's asked
"We balanced the data by duplicating the rare class, then cross-validated. Comment." Duplicates of the same case end up in training and validation folds, so the model is tested on near-copies of its training data. Oversample only within each training fold.
Cheatsheet
Oversampling rule
Imbalance toolkit
Check your understanding
Score 75% or more to master this lesson and earn XP. Answer first, then check.