Sub topic 13
Handling class and label imbalance
This chapter assumes you can fit a scikit-learn classifier, read a confusion matrix, and compute precision, recall and F1 for a binary problem. It also assumes you know the micro, macro and weighted averages from the earlier chapters on evaluation.
What imbalance looks like in each setting
In a multiclass problem, imbalance means the class counts are far apart. A dataset with 85% class A, 12% class B and 3% class C is imbalanced. A model that always predicts A scores 85% accuracy and never finds B or C.
In a multilabel problem, imbalance has two layers:
- Per-label imbalance. Most labels are rare, so each binary column of the target matrix is mostly zeros. A label with 2% prevalence gives each of its binary classifiers a 98:2 problem.
- Label frequency spread. Some labels appear in thousands of rows and others in a handful. Micro averages are dominated by the frequent labels, and macro averages weight every label equally.
Multilabel imbalance is usually worse than multiclass imbalance. In a multiclass problem the classes compete through softmax, so a rare class loses probability mass to a common one. In a multilabel problem each sigmoid output sees mostly negatives, so it drifts toward predicting "absent".
Diagnose before you fix
Check the counts first. For multiclass targets use np.bincount(y). For a multi-hot matrix use Y.sum(axis=0) for label counts and Y.sum(axis=1) for labels per row.
Then evaluate with metrics that expose the problem:
- Accuracy hides it. Use per-class recall and macro F1.
- In multilabel problems, subset accuracy can be low even for a good model. Report per-label F1 alongside micro and macro F1.
- If macro F1 is far below micro F1 (or weighted F1), the rare classes or labels are doing badly.
Levers for mitigation
| Lever | What it changes | Main risk |
|---|---|---|
| Class weights | Loss per example, so rare classes cost more when missed | Probabilities are no longer calibrated |
| Resampling (over or under) | The training set composition | Overfitting to duplicates, or discarding information |
| Threshold tuning | The decision rule after training | Needs held-out data to choose thresholds |
| Better metrics | How you judge the model | Does not change the model |
The usual order is to measure first, then try class weights, then tune thresholds. Resampling comes last because it is the easiest to get wrong.
Class weights in a multiclass model
Class weights multiply each example's loss by a factor tied to its class. With class_weight="balanced", scikit-learn uses n_samples / (n_classes * count_of_class). A class with a tenth of the examples gets about ten times the weight.
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, recall_score
X, y = make_classification(
n_samples=4000, n_features=10, n_informative=5, n_redundant=0,
n_classes=3, n_clusters_per_class=1, weights=[0.85, 0.12, 0.03],
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)
y_pred = clf.predict(X_test)
print("class_weight =", cw)
print(" macro F1: ", round(f1_score(y_test, y_pred, average="macro"), 3))
print(" per-class recall:", recall_score(y_test, y_pred, average=None).round(3))Expect recall on the two rare classes to rise with "balanced", and precision on those classes to fall. The common class loses some recall because the boundary moves toward it. Whether that trade is good depends on the cost of each kind of error, so check precision as well as recall.
Class weights in a multilabel model
A multilabel model built by binary relevance trains one binary classifier per label. Passing class_weight to the base estimator applies it separately inside each of those binary problems. The weight is computed per label from that label's own positive and negative counts.
The next example thins out one label so it is rare. It prints the negative-to-positive ratio for each label, which is the value a neural network would use as pos_weight in a weighted binary cross-entropy loss.
import numpy as np
from sklearn.datasets import make_multilabel_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.multiclass import OneVsRestClassifier
from sklearn.metrics import f1_score
X, Y = make_multilabel_classification(
n_samples=3000, n_features=20, n_classes=6, n_labels=2, random_state=0
)
rng = np.random.default_rng(0)
# Keep only about 15% of the positives of the last label, to make it rare.
Y[:, 5] = Y[:, 5] * (rng.random(len(Y)) < 0.15)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, random_state=0)
pos = Y_train.sum(axis=0)
print("prevalence:", Y_train.mean(axis=0).round(3))
print("neg/pos ratio:", ((len(Y_train) - pos) / pos).round(1))
for cw in (None, "balanced"):
model = OneVsRestClassifier(
LogisticRegression(max_iter=1000, class_weight=cw)
).fit(X_train, Y_train)
Y_pred = model.predict(X_test)
print("class_weight =", cw)
print(" per-label F1:", f1_score(Y_test, Y_pred, average=None, zero_division=0).round(3))
print(" micro F1:", round(f1_score(Y_test, Y_pred, average="micro", zero_division=0), 3))
print(" macro F1:", round(f1_score(Y_test, Y_pred, average="macro", zero_division=0), 3))Look at the last entry of the per-label F1 list. An unweighted model often scores close to zero on a label this rare, because its probability rarely reaches 0.5. Weighting usually lifts that label, and macro F1 moves more than micro F1 because macro counts the rare label as much as any other.
Resampling without leaking
Oversampling duplicates or synthesizes minority examples. Undersampling drops majority examples. Both change the training set only. The validation and test sets must keep the real class distribution, or your metrics will describe a world that does not exist.
Multilabel resampling is harder. Duplicating a row that carries a rare label also duplicates every other label on that row, which can inflate common labels. Methods that choose rows by label rarity exist, but they distort label co-occurrence. Treat resampling in multilabel problems as an experiment to validate, not a default.
Weights, thresholds and probabilities
Class weights shift the model's scores toward the rare class. This can raise recall, but the output probabilities no longer match real frequencies. If a downstream system needs trustworthy probabilities, the weighted model needs recalibration.
The alternative is to train without weights and move the decision threshold afterwards. For a multilabel model, choose one threshold per label on a validation set. For a multiclass model, you can scale each class's probability by a factor before taking argmax. This keeps the model's ranking intact and makes the trade between precision and recall explicit.
Validation for rare labels
A random split can leave a rare label with no positives in the validation set, and its F1 is then undefined. Use stratified splits for multiclass targets. For multilabel targets, use an iterative-stratified splitter, which tries to keep every label's proportion similar across folds. Also check the positive count per label in each fold before trusting per-label scores. A label with five test positives gives an F1 that moves a lot from a single prediction.
Common errors
- Reporting accuracy or micro F1 only, so rare-class failure stays hidden.
- Tuning class weights on the test set. Use cross-validation or a separate validation set.
- Setting
zero_divisionsilently and not noticing labels with no predicted positives. - Comparing a weighted model's probabilities to an unweighted model's without recalibrating.
Exercise
A multilabel model has micro F1 of 0.78 and macro F1 of 0.41. What does this gap suggest, and what are two steps you would try first?
Show answer
Micro F1 pools all label decisions, so frequent labels dominate it. Macro F1 averages per-label scores equally, so the low value means several rare labels perform badly. First, print per-label F1 and positive counts to find the weak labels. Then try class weights in the base estimator, or tune a separate threshold for each weak label on validation data. Resampling comes later, inside cross-validation folds only.
Exercise
You oversample the minority class of a dataset, then run 5-fold cross-validation on the enlarged data. The F1 for the minority class is 0.97, but it drops to 0.40 in production. What went wrong?
Show answer
Oversampling before splitting put duplicates of the same example into both the training and validation folds. The model was scored on examples it had effectively already seen. Resampling must happen inside each fold, on the training part only, and the validation part must keep the real class distribution.