Handling Imbalanced Data: SMOTE, Oversampling, Undersampling, and Class Weights
Learn how to handle imbalanced datasets where one class dominates (e.g., 99% negative, 1% positive), using SMOTE, oversampling, undersampling, class weights, and the right metrics like F1 and AUC-PR.
Handling Imbalanced Data: SMOTE, Oversampling, Undersampling, and Class Weights
When one class heavily dominates your dataset (e.g., 99% "not fraud" and 1% "fraud"), standard ML models and metrics often fail. A model that always predicts the majority class can achieve 99% accuracy while being useless for the minority class. This guide covers detection, strategies, and best practices for imbalanced classification.
---
What Is Class Imbalance?
Class imbalance means the target variable has highly unequal distribution across classes. For binary classification:
| Scenario | Example | Challenge |
|---|---|---|
| 99% negative, 1% positive | Fraud detection | Model tends to predict "not fraud" for everything |
| 95% negative, 5% positive | Disease screening | Minority class is often the one you care about |
| 90% stay, 10% churn | Customer churn | Need to identify the small churn group |
---
Why Imbalance Is a Problem
- Models optimize for the majority — minimizing loss often means predicting the majority class most of the time
- Accuracy is misleading — 99% accuracy with 1% positive class means you might catch zero positives
- Minority class gets insufficient representation — the model sees few examples to learn from
- Default thresholds fail — 0.5 may be wrong; you often need to tune the decision threshold
Real-World Examples
| Domain | Majority | Minority | Why It Matters |
|---|---|---|---|
| Fraud detection | Legitimate transactions | Fraudulent | Missing fraud is costly |
| Disease screening | Healthy | Diseased | Missing disease is dangerous |
| Churn prediction | Retained customers | Churned | Identifying churners enables retention |
| Spam detection | Legitimate email | Spam | Both classes matter, but spam is often rarer |
| Defect detection | Good products | Defective | Catching defects saves money |
How to Detect Imbalance
- Class distribution — Plot or count target value counts
- Imbalance ratio — Majority count / Minority count (e.g., 99:1)
- Per-class sample size — If minority has fewer than ~100 samples, standard methods may struggle
| Imbalance Ratio | Severity | Typical Approach |
|---|---|---|
| 2:1 to 5:1 | Mild | Class weights or threshold tuning |
| 10:1 to 100:1 | Moderate | Oversampling, undersampling, or SMOTE |
| 100:1 or higher | Severe | Combine techniques, consider anomaly detection |
Strategies for Imbalanced Data
1. Random Oversampling
What it does: Duplicates minority class samples so the dataset becomes balanced.
| Pros | Cons |
|---|---|
| Simple, no data loss | Can overfit to repeated samples |
| Preserves all majority data | Increases training time and memory |
| Easy to implement | Synthetic duplicates add no new information |
---
2. Random Undersampling
What it does: Randomly removes majority class samples to balance the dataset.
| Pros | Cons |
|---|---|
| Fast, reduces data size | Throws away potentially useful data |
| Reduces training time | May lose important majority-class patterns |
| Simple to implement | Risky if majority class has rare but important subgroups |
---
3. SMOTE (Synthetic Minority Oversampling Technique)
What it does: Creates synthetic minority samples by interpolating between existing minority samples. For each minority sample, it finds K nearest neighbors in the minority class and generates new points along the line segments between them.
| Pros | Cons |
|---|---|
| Creates new examples, not duplicates | Can create noisy samples near outliers |
| Often performs better than random oversampling | May overgeneralize in high dimensions |
| Doesn't discard data | Requires careful tuning of K (neighbors) |
| Works well in practice | Can amplify noise if minority is noisy |
---
4. ADASYN (Adaptive Synthetic Sampling)
What it does: Like SMOTE, but focuses more on generating synthetic samples near the decision boundary where the majority class dominates. Harder-to-learn minority samples get more synthetic neighbors.
| Pros | Cons |
|---|---|
| Adapts to local density | More complex than SMOTE |
| Focuses on borderline samples | Can be slower |
| May improve over SMOTE when boundary is fuzzy | Less widely implemented |
---
5. Class Weights
What it does: Tells the algorithm to penalize misclassifying the minority class more than the majority. For example, weight minority class 99 and majority 1 so that missing a minority sample counts 99× more in the loss.
| Pros | Cons |
|---|---|
| No data modification — uses original distribution | Not all algorithms support it |
| No overfitting to duplicated samples | May need tuning of weight values |
| Simple to enable in most frameworks | Can make optimization harder |
| Works with tree-based and linear models | — |
class_weight='balanced' or similar. Often the first thing to try.
---
6. Cost-Sensitive Learning
What it does: Assigns different costs to different types of errors (e.g., false negative costs 10× false positive). Optimization minimizes total cost.
Use when: You have explicit business costs for different error types. Complements class weights.
---
7. Threshold Tuning
What it does: Instead of using 0.5 as the decision threshold, find the threshold that optimizes your metric (e.g., F1, recall at target precision).
| Default (0.5) | Lower threshold (e.g., 0.3) | Higher threshold (e.g., 0.7) |
|---|---|---|
| May miss many positives | More positives predicted → higher recall, lower precision | Fewer positives → higher precision, lower recall |
---
8. Combining Techniques
Common combinations:
- SMOTE + Undersampling — Oversample minority, lightly undersample majority for balance
- Class weights + Threshold tuning — Use weights during training, tune threshold for deployment
- Stratified sampling + Class weights — Stratified folds for fair evaluation, weights for training
Which Metrics to Use
Do NOT use accuracy for imbalanced data. A model predicting the majority class everywhere can have 99% accuracy.
| Metric | When to Use |
|---|---|
| F1 Score | Balance between precision and recall; single number for comparison |
| Precision-Recall AUC (AUC-PR) | Better than ROC-AUC for imbalanced data; focuses on positive class |
| Recall | When missing a positive is very costly (fraud, disease) |
| Precision | When false positives are costly (spam marking real email) |
| Balanced Accuracy | (Sensitivity + Specificity) / 2 — treats classes equally |
| Confusion Matrix | Always inspect — see actual TP, FP, FN, TN |
Comparison Table of Strategies
| Strategy | Data Modification | Best For | Risk |
|---|---|---|---|
| Random oversampling | Yes — duplicates | Quick fix, moderate imbalance | Overfitting to duplicates |
| Random undersampling | Yes — removes | Large majority, redundant data | Information loss |
| SMOTE | Yes — synthetic | Moderate imbalance, 50+ minority | Noisy synthetic samples |
| ADASYN | Yes — synthetic | Boundary-focused | Less standard support |
| Class weights | No | First try, algorithm support | Weight tuning |
| Threshold tuning | No | After training | Requires validation |
| Cost-sensitive | No | Known error costs | Cost specification |
How to Use in the Platform
- Go to ML → Train
- Select your dataset and target column
- Check Class distribution in the data summary — look for imbalance
- In model configuration:
balanced) if available
- Or choose SMOTE / Oversampling in preprocessing options
- For evaluation, select F1 or AUC-PR as the primary metric, not accuracy
- After training, use Threshold tuning or ROC/PR curve to pick the best decision threshold
Common Pitfalls
| Pitfall | Problem | Fix |
|---|---|---|
| Oversampling before train/test split | Synthetic samples can leak into both sets | Split first, then apply SMOTE/oversampling only to training fold |
| Not using stratified cross-validation | Some folds may have zero minority samples | Always use stratified k-fold for imbalanced classification |
| Using accuracy as the metric | Misleading 99% accuracy | Use F1, AUC-PR, or balanced accuracy |
| Ignoring the business cost of errors | Optimizing wrong metric | Align metric with real-world cost of FN vs FP |
| Over-oversampling | Too many synthetic samples | Aim for moderate balance (e.g., 1:3 or 1:1), not necessarily 50:50 |
Quick Reference
| Imbalance Level | First Try | If Needed |
|---|---|---|
| Mild (5:1) | Class weights, threshold tuning | — |
| Moderate (20:1) | SMOTE or class weights | Combine with stratified CV |
| Severe (100:1) | SMOTE + undersampling, class weights | Consider anomaly detection |
---
What's Next?
- [ML Overview](ml-overview) — Full ML workflow
- [Model Evaluation Metrics](model-evaluation-metrics) — Precision, recall, F1, AUC-PR in depth
- [Cross-Validation Guide](cross-validation-guide) — Use stratified CV for imbalanced data
- [ML Common Pitfalls](ml-common-pitfalls) — Data leakage, wrong metrics, and more
Related Articles
Machine Learning Overview: Workflow and Getting Started
A beginner-friendly recap of ML, classification vs regression vs clustering, the ML workflow (select, configure, train, evaluate, predict), and a 5-minute quick-start guide.
Model Evaluation Metrics: Accuracy, Precision, Recall, F1, AUC, RMSE, and More
Understand all major ML evaluation metrics for classification and regression, learn when to use each one, and avoid common metric selection mistakes.
Cross-Validation: Reliable Model Evaluation Techniques
Learn how to evaluate ML models reliably using k-fold, stratified, leave-one-out, and time series cross-validation to avoid overfitting and get honest performance estimates.
ML Common Pitfalls: Data Leakage, Overfitting, and Mistakes to Avoid
Avoid the top 15 ML pitfalls including data leakage, wrong metrics, overfitting, training/serving skew, and model drift. Learn how to detect each pitfall and fix it with practical examples.
Was this helpful?