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

TechniqueDescriptionRisk
Random oversamplingDuplicate minority samplesOverfitting
Random undersamplingRemove majority samplesLoss of information
Data augmentationApply transformations (rotation, flip, shift, zoom, shear)Requires careful tuning
SMOTESynthetically generate minority samples by interpolating between nearest neighboursOnly for structured/tabular data

SMOTE (Synthetic Minority Over-sampling Technique)

  1. Select a minority class instance
  2. Find its -nearest neighbours (from minority class)
  3. 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.