Sub topic 13
Dealing with Imbalanced Classes
This chapter assumes you know PyTorch datasets, model training, and basic evaluation metrics. You also have a training and validation split loaded with ImageFolder.
An imbalanced dataset has unequal numbers of examples in its classes. For example, a wildlife dataset might contain 2,000 bird images but only 150 fox images. A model trained normally may favor the common class because that choice reduces the average loss.
Why accuracy can mislead
Suppose a validation set contains 95 healthy images and 5 diseased images. A classifier that always predicts “healthy” achieves 95% accuracy, but it detects no diseased cases.
Measure performance for each class rather than relying on one overall number.
| Metric | Meaning | Useful question |
|---|---|---|
| Accuracy | Correct predictions divided by all predictions | How often is the model correct overall? |
| Precision | Correct positive predictions divided by all positive predictions | When the model predicts this class, how often is it right? |
| Recall | Correct positive predictions divided by all actual examples | How many examples of this class does it find? |
| F1 score | Balance of precision and recall | Is performance balanced for this class? |
A confusion matrix counts actual classes against predicted classes. Its diagonal contains correct predictions. Off-diagonal cells show which classes the model confuses.
Check the split before changing the model
Keep examples from every class in train, validation, and test sets. A stratified split preserves approximately the same class proportions in each set. If one class has only a few images, inspect the split manually. A class with zero test examples cannot receive a meaningful test score.
Do not create augmented copies before splitting. Near-duplicates can then appear in both training and validation data, causing data leakage, where evaluation images indirectly reveal their training counterparts.
Use the training labels to inspect class counts:
from collections import Counter
counts = Counter(train_ds.targets)
for class_index, count in sorted(counts.items()):
print(train_ds.classes[class_index], count)Weight the loss
One common remedy gives more influence to minority examples. For class \(c\), a simple weight is:
w_c = \frac{N}{K \cdot n_c}Here, \(N\) is the number of training images, \(K\) is the number of classes, and \(n_c\) is the number of images in class \(c\). A small class therefore receives a larger weight.
import torch
import torch.nn as nn
from collections import Counter
counts = Counter(train_ds.targets)
num_classes = len(train_ds.classes)
total = len(train_ds)
weights = torch.tensor(
[total / (num_classes * counts[i]) for i in range(num_classes)],
dtype=torch.float32,
device=device,
)
criterion = nn.CrossEntropyLoss(weight=weights)Compute weights from the training set only. Validation and test labels must not influence training choices.
Other remedies and trade-offs
- A
WeightedRandomSamplerdraws minority examples more often. This can help the model see rare classes, but repeated images may increase overfitting. - Targeted augmentation creates varied versions of minority images. It cannot fix mislabeled or unrepresentative originals.
- Focal loss emphasizes difficult examples. It adds a tuning choice and is not always better than weighted cross-entropy.
- Collecting more minority examples is usually the strongest long-term fix.
Use one change at a time and compare per-class results. Oversampling and heavy loss weighting together may overcorrect the imbalance.
> warning > Never judge a balanced classifier from accuracy alone. Report support, precision, recall, and F1 score for every class, especially when the minority class has an important cost of failure.
Exercise
A validation set has 900 class-A images and 100 class-B images. A model gets 90% accuracy but class-B recall is 0%. What does this suggest, and what should you inspect first?
Show answer
The model may be predicting class A almost always. Inspect the confusion matrix, class counts, split quality, and per-class predictions before changing the architecture.