Class Imbalance
ML Engineer path · lesson 69 of 80Two cancer-screening models, both with 90% accuracy — one catches 10 of 100 cancers, the other catches 90. Flip which class counts as positive and watch the same model's F1 move from 0.17 to 0.95.
Key insight
Reason 2 is why this is not a data-volume problem. The majority-class heuristic sits in a broad, flat basin of the loss surface: perturb it slightly and accuracy drops, so gradient descent has no local signal telling it that a far better solution exists somewhere else entirely.
Three levers for imbalance
Sort each technique by what it changes.
Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.
Resample the data
Drop items hereChange the loss
Drop items hereChange the metric
Drop items hereTest your knowledge
Why does gradient descent struggle to escape the majority-class heuristic?
The short version
A smoke alarm that never goes off. In a building that has never had a fire, it is right every single night, and its accuracy is magnificent. The number you wanted was never accuracy.
In more depth
Class Imbalance
With 900 NORMAL scans and 100 CANCER scans, a model that always answers NORMAL scores 90% accuracy and catches nothing.
Three reasons it's hard
It happens in regression too: health-care bills are highly skewed, and a 100% error on a $250 bill is acceptable; a 100% error on a $10k bill is not.
Where it comes from
Metrics — Table 4-7
1,000 scans: 100 CANCER, 900 NORMAL.
| Accuracy | Precision | Recall | F1 | |
|---|---|---|---|---|
| Model A (catches 10/100) | 0.9 | 0.5 | 0.1 | 0.17 |
| Model B (catches 90/100) | 0.9 | 0.5 | 0.9 | 0.64 |
F1, precision and recall are asymmetric. With CANCER positive, model A's F1 is 0.17; with NORMAL positive, it is 0.95. In scikit-learn's f1_score, pos_label defaults to 1.
Under heavy imbalance ROC flatters a model: FPR = FP/(FP+TN), and the enormous TN count means a flood of false positives barely moves the curve. Davis and Goadrich (2006) argued for the Precision-Recall Curve, whose precision term has no true-negative cushion.
Data-level: resampling
Both SMOTE and Tomek links have only been proven effective in low-dimensional data.
"When you resample your training data, never evaluate your model on resampled data."
Algorithm-level: change the loss
Interview Questions
References & Further Reading
Love this visualization?
Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.
100% free • No credit card required