Handling Class Imbalance
Related: 7. Evaluating ML Models | 6. Loss Functions and Backpropagation | 2. Supervised Learning | Artificial Intelligence
The Problem
When one class vastly outnumbers another (e.g., 998 negatives vs 2 positives), classifiers become biased toward the majority class. A model predicting “always negative” achieves 99.8% accuracy but is useless.
The standard cross-entropy loss (see 6. Loss Functions and Backpropagation) is dominated by the majority class gradients.
Algorithm-Level Solutions
Weighted Cross-Entropy
Assign higher weights to minority classes in the loss function:
Weighted BCE:
class_weights = {0: 1.0, 1: 5.0} # higher weight for minority
model.fit(..., class_weight=class_weights)Focal Loss
Reduces the influence of easy (majority) samples and focuses training on hard (minority) samples. Adds a modulating factor to cross-entropy.
Data-Level Solutions
| Technique | Description | Risk |
|---|---|---|
| Random oversampling | Duplicate minority samples | Overfitting |
| Random undersampling | Remove majority samples | Loss of information |
| Data augmentation | Apply transformations (rotation, flip, shift, zoom, shear) | Requires careful tuning |
| SMOTE | Synthetically generate minority samples by interpolating between nearest neighbours | Only for structured/tabular data |
SMOTE (Synthetic Minority Over-sampling Technique)
- Select a minority class instance
- Find its -nearest neighbours (from minority class)
- Create a synthetic sample by interpolating:
where is random.
Critical rule: Perform oversampling/augmentation only on training data, never on the test set.
Performance Metrics for Imbalanced Data
Use precision, recall, and F1-score (see 7. Evaluating ML Models) rather than accuracy alone.