Sub topic 13
Handling class and label imbalance
This chapter assumes you can read a confusion matrix, know precision, recall and F1 for a binary problem, and have used scikit-learn's LogisticRegression. It builds on the micro, macro and weighted averages from the previous chapter.
Why imbalance hurts
Imbalance means some classes (multiclass) or labels (multilabel) appear far less often than others. A model trained to minimize average loss can ignore a rare class and still look good. Accuracy hides this. If 80% of rows belong to one class, predicting that class every time scores 0.8.
In multilabel data the problem is usually worse. With 50 labels, each label is typically positive in a small fraction of rows. Every per-label binary problem is then mostly negative, and a threshold of 0.5 rarely fires.
Diagnose first
Look at counts before changing anything.
- Multiclass: count rows per class and read per-class recall from the confusion matrix.
- Multilabel: compute each label's positive rate, and compare micro F1 with macro F1.
A macro F1 far below micro F1 or weighted F1 means rare classes are being sacrificed. Micro and weighted averages are dominated by frequent classes, so they can look healthy while rare classes fail.
Reweight the loss
The least invasive fix is to make errors on rare classes cost more. In scikit-learn, class_weight="balanced" sets each class weight to n_samples / (n_classes * count_of_class).
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score
X, y = make_classification(
n_samples=3000, n_features=20, n_informative=6, n_classes=3,
weights=[0.80, 0.15, 0.05], random_state=0,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, stratify=y, random_state=0
)
for cw in (None, "balanced"):
clf = LogisticRegression(max_iter=1000, class_weight=cw).fit(X_train, y_train)
pred = clf.predict(X_test)
print("class_weight =", cw)
print(" per-class F1:", f1_score(y_test, pred, average=None).round(3))
print(" macro F1: ", round(f1_score(y_test, pred, average="macro"), 3))Expect rare-class recall to rise with "balanced", usually at the cost of some precision on those classes. That trade is the point, so judge it with the metric you care about.
For multilabel models trained with a per-label sigmoid, the equivalent is a per-label positive weight. PyTorch's BCEWithLogitsLoss takes a pos_weight vector. A common choice is the ratio of negatives to positives for each label.
import numpy as np
Y = np.array([[1, 0, 0], [0, 0, 0], [1, 1, 0], [0, 0, 0], [0, 0, 1], [0, 0, 0]])
pos = Y.sum(axis=0)
pos_weight = (len(Y) - pos) / pos
print("positives per label:", pos)
print("pos_weight:", pos_weight.round(2))Other options
- Oversample or undersample the training set only. Never resample before splitting, or duplicated rows leak into the test set.
- Move the threshold instead of changing the data. A lower threshold for a rare label raises its recall without retraining. This is covered in the previous chapter on per-label thresholds.
- Collect or augment data for the rare classes when you can. It is often the most effective option.
In multilabel data, oversampling a row that carries a rare label also duplicates its common labels. This can worsen imbalance elsewhere, so check the per-label counts after resampling.
Common errors
- Reporting accuracy or micro F1 alone and missing a failing rare class.
- Resampling before the train/test split.
- Applying
class_weightand also tuning thresholds without re-checking the metrics. Both shift the precision and recall balance. - Using a random split that leaves a rare class absent from the validation fold. Use stratified splits.
Exercise
A multilabel model reports micro F1 of 0.82 and macro F1 of 0.41. What does the gap suggest, and what is your first check?
Show answer
Frequent labels are performing well and dominate micro F1, while rare labels perform badly and pull macro F1 down. Check each label's positive rate and per-label precision and recall, then consider per-label thresholds or pos_weight for the weak labels.