Three orthogonal strategies, often combined
Most real-world classification problems have skewed class distributions: 99% normal transactions, 1% fraud. Train naively and the model learns "always predict normal" — perfect accuracy, zero utility. Three tools, in increasing aggressiveness:
- Weighted sampling — change which samples the DataLoader picks. Oversample rare classes; the model sees them more often.
- Class weights in the loss — keep sampling proportional but make rare-class mistakes count more.
nn.CrossEntropyLoss(weight=...). - Focal loss — for extreme imbalance (1:1000+), modify the loss to down-weight easy examples. Originally from RetinaNet.
These compose freely. Start with class weights (easiest, fewest hyperparameters); add weighted sampling if class weights aren't enough; reach for focal loss for truly extreme cases.
The trap to avoid
If you oversample rare classes AND apply class weights, you double-weight them. Pick one or carefully tune both. Same logic applies to focal loss — its α parameter is itself a class weight.