Handling Imbalanced Datasets (SMOTE, Class Weights)
Address rare positives with resampling, class weights, and proper metric choice.
In plain words
When a thing you want to find is very rare, you judge the model by how well it finds those rare cases, and you can nudge it to care more about them by weighting them or adding more examples.
Think of it like…
Finding needles in a haystack: counting how many pieces of hay you correctly ignored is useless; you care how many needles you found (recall) and how many of the things you flagged were actually needles (precision), and you can either weigh needles more heavily or search with a magnet at a chosen sensitivity.
Where you’ve seen it
A fraud dataset has 100,000 transactions with 1,000 frauds (1%). Always predicting "legit" gives 99% accuracy and 0% recall. Class weights set w_c = n / (k × n_c): for the positive class 100,000 / (2 × 1,000) = 50 and for the negative class 100,000 / (2 × 99,000) = 0.505, so each fraud counts about 99 times as much as a legitimate transaction. A model with 80% recall and a 2% false-positive rate catches 800 frauds but also flags 0.02 × 99,000 = 1,980 legitimate transactions, so precision is 800 / 2,780 = 28.8%; the ROC curve looks excellent while the precision-recall view tells the true operating story. SMOTE creates a synthetic point x_new = x_i + λ (x_nn − x_i) with λ uniform in [0, 1]: for x_i = (2, 3), neighbour (4, 7) and λ = 0.25 it gives (2.5, 4.0). The team applies SMOTE inside an imblearn pipeline so it affects only training folds, compares class weights, SMOTE and undersampling by cross-validated PR-AUC (0.41, 0.40 and 0.36), and chooses weights plus a tuned threshold. Because undersampling negatives from 99:1 to 10:1 shifts the prior, a predicted 0.50 corresponds to odds 1 × (1/99)/(1/10) = 0.101, a true probability of 0.092, so they recalibrate before using scores as risks.
Words you’ll hear
- Class weights
- Per-class multipliers on the loss so rare classes matter more.
- SMOTE
- Synthetic minority oversampling by interpolating between a point and a neighbour.
- PR-AUC / average precision
- Area under the precision-recall curve; baseline equals prevalence.
- Prior shift
- A change in class proportions caused by resampling, which distorts probabilities.
Visual diagram
Theory & deep dive
Metrics, class weights and thresholds first
Start by fixing evaluation: use stratified splits, report precision, recall, F1 and PR-AUC (average precision) rather than accuracy, and compare against the base rate (a PR-AUC of 0.41 is far above the 0.01 baseline). ROC-AUC is insensitive to prevalence and can look excellent when the model is operationally poor: with 1% positives, 80% recall and 2% false-positive rate, precision is only 800 / (800 + 1,980) = 28.8%. Then try class weights (class_weight="balanced" computes n / (k × n_c): 50 for the positive class and 0.505 for the negative class in the example), which require no data manipulation and work with logistic regression, SVMs, trees and boosting (scale_pos_weight in XGBoost). Finally, tune the decision threshold on validation data using costs or constraints (see the threshold lesson), which often matters more than resampling.
Weights change the loss, so predicted probabilities are no longer calibrated to the true base rate; if you need probabilities (expected-cost decisions, risk scores), recalibrate on an untouched validation set (Platt or isotonic) or use the model for ranking and set thresholds empirically. Ensemble methods designed for imbalance (BalancedRandomForest, EasyEnsemble, boosting with focal loss) can also help. Collect more minority data if possible, since no technique replaces real information.
n = 100,000, k = 2, positives 1,000, negatives 99,000. w_pos = 100,000 / (2 × 1,000) = 50. w_neg = 100,000 / (2 × 99,000) = 0.505. A fraud error costs 50 / 0.505 ≈ 99 times a legitimate-transaction error in the loss.
Resampling: SMOTE, undersampling and the leakage traps
Random oversampling duplicates minority rows (risk: overfitting to copies). SMOTE creates synthetic minority points: pick a minority point x_i and one of its k nearest minority neighbours x_nn, then place a new point on the segment between them, x_new = x_i + λ (x_nn − x_i) with λ ∈ [0, 1] (for (2, 3) and (4, 7) with λ = 0.25: (2.5, 4.0)). Variants (Borderline-SMOTE, ADASYN, SMOTE-NC for categoricals) focus on difficult regions. SMOTE works on numeric, well-scaled features, can generate unrealistic points in high dimensions or overlapping classes and doesn't create new information, only plausible interpolations. Random undersampling discards majority rows (fast, but loses data); informed undersampling (Tomek links, NearMiss, cluster centroids) removes overlapping or redundant majority points.
The key rule: resample only the training data inside each cross-validation fold. Oversampling before splitting puts copies or synthetic neighbours of validation points into training, inflating scores. Use imblearn.pipeline.Pipeline (resampling steps run during fit only), and always evaluate on the original, imbalanced validation fold so metrics reflect production prevalence. Resampling shifts class priors: if you undersample negatives from 99:1 to 10:1, a model's predicted probability p′ must be corrected by multiplying the odds by (true prior odds)/(training prior odds) = (1/99)/(1/10) = 0.101: p′ = 0.50 (odds 1) becomes odds 0.101 and probability 0.092. Compare approaches by cross-validated PR-AUC and cost; often class weights plus a tuned threshold match or beat SMOTE with less complexity (PR-AUC 0.41 versus 0.40 versus 0.36 in the example).
Train at 10:1 (negatives:positives) after undersampling; true ratio 99:1. Predicted p′ = 0.50 → odds′ = 1. True odds = 1 × (1/99) ÷ (1/10) = 0.101 → p = 0.101 / 1.101 = 0.092.
How it works, step by step
Step 1 of 41. Set up honest evaluation
Use stratified splits, a majority baseline and metrics such as precision, recall and PR-AUC.
- Prevalence
- = PR-AUC baseline
When to use it & trade-offs
What it is
A dataset is imbalanced when one class (often the one you care about: fraud, churn, disease) is rare. Models trained naively optimise overall loss and can ignore the minority class, and accuracy becomes meaningless (a 1% positive rate gives 99% accuracy for "always negative"). Remedies fall into three groups: metrics and thresholds (evaluate with precision, recall, PR-AUC and tune the decision threshold), algorithm-level changes (class weights, cost-sensitive learning, balanced ensembles) and data-level resampling (random undersampling, oversampling, SMOTE, which synthesises minority points by interpolating between neighbours). Resampling must be applied only to training folds inside a pipeline, never to validation or test data.
Why it matters: Rare events are where many valuable models live, and imbalance changes everything: loss functions, evaluation metrics, probability calibration and the economics of alerts. Teams that oversample before splitting leak duplicates into validation and report fantasy scores; teams that resample and then use predicted probabilities as risks get miscalibrated numbers. Knowing which fix to try first (usually metrics, thresholds and class weights, before synthetic data) saves effort and avoids traps.
When to reach for it
- Fraud, churn, disease and defect detection
- Any problem with a rare positive class
- Alerting systems with limited review capacity
When to avoid or be careful
- Oversampling before the train-validation split
- Reporting accuracy or ROC-AUC alone on rare events
- Using resampled-model probabilities as true risks
Imbalance techniques
Strengths: No data change; works with most models.
Watch out: Distorts probabilities unless recalibrated.
Strengths: Gives the model more minority variety.
Watch out: Synthetic points may be unrealistic; leakage if misapplied.
Strengths: Fast training; simple.
Watch out: Discards information; shifts priors.
Interview signals & numbers to know
When this topic comes up
- “1% of transactions are fraud”
- SMOTE
- class_weight='balanced'
- PR-AUC
- Prior shift correction
Benchmarks & rules of thumb
- 50 vs 0.505
- balanced class weights at 1% prevalence
- 28.8%
- precision at 80% recall and 2% FPR
- 0.50 → 0.092
- probability corrected after undersampling to 10:1
Common mistakes & follow-ups
Common interview mistakes
- Applying SMOTE to the whole dataset and then cross-validating.
- Choosing the model by accuracy.
- Assuming more synthetic data adds information.
Likely interviewer follow-ups
- How would you approach a dataset with 0.5% positives?
- Why do you resample only the training folds?
- Why is PR-AUC better than ROC-AUC under heavy imbalance?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Handling Imbalanced Datasets (SMOTE, Class Weights) with data science interview Q&A and hands-on practice.