Sub topic 13
Dealing with imbalanced classes
This chapter assumes you have followed the earlier chapters. You should have an ImageFolder dataset with train and validation splits, a pretrained ResNet-18 with a new head, and the run_epoch function from the training chapter. You should also know what accuracy and a confusion matrix are.
Why imbalance breaks accuracy
Class imbalance means some classes have far more training images than others. Real image collections are rarely balanced. A defect-detection set might hold 5,000 photos of good parts and 80 of cracked ones.
Imbalance causes two problems:
- Accuracy hides failure. A model that always predicts the majority class scores high accuracy. With 98 good parts for every 2 cracked ones, "always good" is 98% accurate and useless.
- Gradients favor the majority. Most batches contain mostly majority images, so the loss is dominated by them. The model learns to be right about common classes and pays little for being wrong about rare ones.
The fix has two parts. First, measure honestly so you can see the problem. Second, change either the data the model sees or how much each mistake costs.
Step 1: Measure the imbalance
Start by counting. ImageFolder stores a targets list with one class index per image, so counting needs no extra file reads.
from collections import Counter
counts = Counter(train_ds.targets)
for idx, name in enumerate(train_ds.classes):
print(f"{name:>12}: {counts[idx]}")A ratio between the largest and smallest class of about 2:1 is usually harmless. At 10:1 or more you should expect trouble and check per-class results.
Then look at recall for each class on the validation set. Recall for a class is the fraction of its true images that the model found. Overall accuracy cannot show a rare class doing badly, but per-class recall can.
import torch
@torch.no_grad()
def per_class_recall(model, loader, device, num_classes):
model.eval()
hits = torch.zeros(num_classes)
totals = torch.zeros(num_classes)
for images, labels in loader:
preds = model(images.to(device)).argmax(dim=1).cpu()
for c in range(num_classes):
mask = labels == c
totals[c] += mask.sum()
hits[c] += (preds[mask] == c).sum()
return hits / totals.clamp(min=1)
recalls = per_class_recall(model, val_loader, device, num_classes)
for name, r in zip(train_ds.classes, recalls):
print(f"{name:>12}: recall {r:.3f}")If the rare class has recall far below the others, the model is neglecting it.
Step 2: Choose a remedy
Three approaches are common. They can be combined, but try one at a time so you can tell what helped.
| Approach | What changes | Strengths | Risks |
|---|---|---|---|
| Collect more rare images | The data itself | Fixes the root cause | Costs time and labeling effort |
| Weighted sampling | Which images appear in each batch | Rare classes appear often in training | Rare images repeat, which encourages memorizing them |
| Class-weighted loss | How much each mistake costs | No change to the data pipeline | Can destabilize training if weights are extreme |
Option A: Weighted sampling
WeightedRandomSampler draws images with probability proportional to a weight you assign. If each image gets a weight of one divided by its class count, every class is drawn about equally often.
from torch.utils.data import DataLoader, WeightedRandomSampler
class_counts = torch.tensor(
[counts[i] for i in range(num_classes)], dtype=torch.float
)
class_weights = 1.0 / class_counts
sample_weights = class_weights[train_ds.targets]
sampler = WeightedRandomSampler(
weights=sample_weights,
num_samples=len(train_ds),
replacement=True,
)
balanced_loader = DataLoader(
train_ds, batch_size=32, sampler=sampler, num_workers=4
)Three details matter here:
- Do not pass
shuffle=Truetogether with asampler. PyTorch raises an error, because the sampler already controls the order. replacement=Trueis required in practice. Rare images must be drawn more than once, or the batches cannot balance.- Because rare images repeat, augmentation matters more. The random crops and flips in the training transform make each repeat look a little different, which reduces memorization.
Only the training loader uses the sampler. Keep the validation loader unchanged so that it reflects the real class mix.
Option B: Class-weighted loss
Instead of changing which images appear, make mistakes on rare classes cost more. CrossEntropyLoss accepts a weight tensor with one value per class.
total = class_counts.sum()
weights = total / (num_classes * class_counts) # inverse frequency, mean near 1
weights = weights.clamp(max=10.0) # avoid extreme values
criterion = torch.nn.CrossEntropyLoss(weight=weights.to(device))The formula gives a class with half the average frequency a weight of about 2. Clamping the weight keeps a class with very few images from dominating the gradient. With a clamp of 10, a class with 5 images in a dataset of thousands cannot overwhelm everything else.
Use the same weighted criterion for training only. When you report validation loss, use an unweighted CrossEntropyLoss, so the number is comparable across experiments.
Do not combine a balanced sampler with full inverse-frequency weights. The sampler has already evened out the classes, and weighting again over-corrects. The model then over-predicts the rare class and its precision drops.
Step 3: Re-evaluate with the right metrics
Fixing imbalance usually moves a trade-off. More attention to the rare class raises its recall but can lower its precision. Precision for a class is the fraction of images predicted as that class that truly belong to it.
Report both for each class. scikit-learn produces them in one call.
from sklearn.metrics import classification_report
all_preds, all_labels = [], []
model.eval()
with torch.inference_mode():
for images, labels in val_loader:
preds = model(images.to(device)).argmax(dim=1).cpu()
all_preds.extend(preds.tolist())
all_labels.extend(labels.tolist())
print(classification_report(
all_labels, all_preds, target_names=train_ds.classes, digits=3
))The report lists precision, recall, and F1 for each class. F1 is the harmonic mean of precision and recall. It is low when either one is low. The report also gives a macro average, which weights every class equally. When classes are imbalanced, macro-averaged F1 is a more honest single number than accuracy.
Which trade-off is right depends on the cost of each error. In a safety inspection, missing a cracked part (low recall) is worse than flagging a good one (low precision). In a photo-tagging app, the reverse may hold. Decide this before tuning, not after.
Common mistakes
- Rebalancing before splitting. If you oversample by copying files and then split, copies of one image can land in both train and validation. This is data leakage, and validation scores become falsely high. Split first, then balance only the training side, or use a sampler as shown above.
- Judging by accuracy alone. An improvement in rare-class recall can lower accuracy slightly. That is often the right outcome.
- Extreme weights. Weights in the hundreds make the loss noisy. Clamp them or use the square root of the inverse frequency for a milder correction.
- Validation set too small for the rare class. With 5 rare validation images, recall can only be 0, 0.2, 0.4, and so on. One image changes it by 20 points. Make sure each class has enough validation examples to give a stable estimate, and treat small-class numbers as rough.
- Expecting a trick to replace data. Sampling and weighting rearrange what you have. If 30 rare images do not cover the variety of the real class, more labeled images will help more than any loss setting.
Putting it together
A sensible workflow for an imbalanced dataset:
- Count images per class and print the ratio of largest to smallest.
- Train once with the standard setup and compute per-class recall as a baseline.
- If the rare class is weak, add either a weighted sampler or a class-weighted loss, not both.
- Retrain with the same seed and epochs, and compare per-class precision, recall, and macro F1 against the baseline.
- Look at the rare-class errors in the confusion matrix. If they are mislabeled or ambiguous images, fix the data, which the next chapter covers.
Exercise
A validation set has 950 "ok" images and 50 "damaged" images. A model predicts "ok" for every image. What are its accuracy and its recall for "damaged"? Then say which metric you would report and which remedy you would try first if you had no way to collect more damaged images.
Show answer
Accuracy is 950 / 1000 = 95%. Recall for "damaged" is 0 / 50 = 0%, because none of the damaged images is found. Report per-class recall and precision plus macro F1, since accuracy hides the failure. A reasonable first remedy is a WeightedRandomSampler on the training loader (or a clamped class-weighted loss), but not both at once. Keep the validation set unchanged and re-check the damaged-class recall and precision afterward.
Exercise
You build a DataLoader with shuffle=True and a WeightedRandomSampler and get an error. Why, and how do you fix it? Also, why is replacement=True needed?
Show answer
A sampler already decides the order of samples, so DataLoader does not allow shuffle=True together with it. Remove shuffle=True and pass only sampler=sampler. replacement=True is needed because rare-class images must be drawn more than once per epoch for the batches to contain rare and common classes in similar proportions. Without replacement, each image could appear only once and the rare class could not be boosted.