Sub topic 10
Dealing with imbalanced classes
This chapter assumes you have trained a classifier with the Trainer API, as in the earlier chapters. You should know how accuracy, precision, recall, and F1 are defined, and be comfortable with PyTorch tensors and subclassing a Python class. Everything here continues from the DistilBERT setup (checkpoint, tokenizer, compute_metrics).
Why imbalance breaks a fine-tuning run
A dataset is imbalanced when some labels are much rarer than others. Fraud reports, toxic comments, urgent support tickets, and rare intents are typical examples. Often the rare class is the one you care about.
Cross-entropy loss averages over examples. If 95% of examples are one class, a model that always predicts that class gets 95% accuracy and a low loss. Gradient updates are dominated by the majority class, so the rare class is learned late or not at all. The training curves look healthy while the model is useless for the minority class.
A pretrained encoder softens this problem, because it already has useful features. It does not remove it. Plan for imbalance at four points: the split, the metric, the loss or sampling, and the decision threshold.
Build an imbalanced dataset to practice on
IMDB is balanced, so this chapter creates a skewed version. It keeps 300 negative reviews and 3,000 positive ones, a 10:1 ratio. The negative class is the minority.
from datasets import load_dataset, concatenate_datasets
from transformers import AutoTokenizer
checkpoint = "distilbert-base-uncased"
raw = load_dataset("imdb")
train_full = raw["train"].shuffle(seed=42)
neg = train_full.filter(lambda x: x["label"] == 0).select(range(300))
pos = train_full.filter(lambda x: x["label"] == 1).select(range(3000))
skewed = concatenate_datasets([neg, pos]).shuffle(seed=42)
# stratify_by_column keeps the 10:1 ratio in both parts.
split = skewed.train_test_split(test_size=0.15, seed=42, stratify_by_column="label")
train_ds, val_ds = split["train"], split["test"]
# Test set: same skew as the training data, so it reflects the deployment distribution.
test_neg = raw["test"].filter(lambda x: x["label"] == 0).shuffle(seed=1).select(range(300))
test_pos = raw["test"].filter(lambda x: x["label"] == 1).shuffle(seed=1).select(range(3000))
test_ds = concatenate_datasets([test_neg, test_pos]).shuffle(seed=1)
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
def tokenize(batch):
return tokenizer(batch["text"], truncation=True, max_length=256)
train_ds = train_ds.map(tokenize, batched=True)
val_ds = val_ds.map(tokenize, batched=True)
test_ds = test_ds.map(tokenize, batched=True)
print(train_ds.features["label"].names)
print({name: sum(1 for y in train_ds["label"] if y == i)
for i, name in enumerate(train_ds.features["label"].names)})Two details matter here.
- Stratified split. A plain random split of 330 minority examples can give a validation set with very few of them, and the metrics then jump around from run to run.
stratify_by_columnrequires the column to be aClassLabel, which IMDB's label is. - Test distribution. The validation and test sets keep the natural skew. If you rebalanced them, your metrics would describe a world that does not exist in production.
Measure first: accuracy hides the problem
Replace accuracy with metrics that report each class separately. Macro-F1 averages the F1 of each class with equal weight, so the minority class counts as much as the majority. Minority recall tells you how many of the rare items you catch. Minority precision tells you how many of your alarms are real.
import numpy as np
from sklearn.metrics import precision_recall_fscore_support, accuracy_score
def compute_metrics(eval_pred):
logits, labels = eval_pred
preds = np.argmax(logits, axis=-1)
precision, recall, f1, _ = precision_recall_fscore_support(
labels, preds, labels=[0, 1], zero_division=0
)
return {
"accuracy": accuracy_score(labels, preds),
"macro_f1": float(f1.mean()),
"minority_precision": float(precision[0]),
"minority_recall": float(recall[0]),
"minority_f1": float(f1[0]),
}Set zero_division=0 so that early epochs, where the model never predicts the minority class, report 0 instead of warnings and NaN. Train a baseline with these metrics before you apply any fix. Without a baseline you cannot tell whether a fix helped.
On this skewed set, a baseline typically shows accuracy above 0.90 while minority recall is much lower. Your numbers will differ by run, but that gap is the symptom to look for.
Fix 1: class weights in the loss
Class weights multiply each example's loss by a factor that depends on its label. Rare classes get larger factors, so a mistake on a minority example costs more. The common formula is n_samples / (n_classes * count_of_class).
Trainer has no built-in class-weight option, so you subclass it and override compute_loss.
import numpy as np
import torch
from transformers import (
AutoModelForSequenceClassification,
DataCollatorWithPadding,
Trainer,
TrainingArguments,
)
id2label = {0: "NEGATIVE", 1: "POSITIVE"}
label2id = {v: k for k, v in id2label.items()}
counts = np.bincount(train_ds["label"], minlength=2)
weights = counts.sum() / (len(counts) * counts)
class_weights = torch.tensor(weights, dtype=torch.float)
print("class weights:", class_weights)
class WeightedTrainer(Trainer):
def __init__(self, *args, class_weights=None, **kwargs):
super().__init__(*args, **kwargs)
self.class_weights = class_weights
def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
labels = inputs.pop("labels")
outputs = model(**inputs)
logits = outputs.logits
loss_fct = torch.nn.CrossEntropyLoss(weight=self.class_weights.to(logits.device))
loss = loss_fct(logits, labels)
return (loss, outputs) if return_outputs else loss
model = AutoModelForSequenceClassification.from_pretrained(
checkpoint, num_labels=2, id2label=id2label, label2id=label2id
)
args = TrainingArguments(
output_dir="imdb-weighted",
learning_rate=2e-5,
per_device_train_batch_size=16,
per_device_eval_batch_size=32,
num_train_epochs=3,
weight_decay=0.01,
eval_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
metric_for_best_model="macro_f1",
)
trainer = WeightedTrainer(
model=model,
args=args,
train_dataset=train_ds,
eval_dataset=val_ds,
data_collator=DataCollatorWithPadding(tokenizer),
compute_metrics=compute_metrics,
class_weights=class_weights,
)
trainer.train()
print(trainer.evaluate(test_ds))With a 10:1 ratio the weights come out near 5.5 for the minority class and 0.55 for the majority class. The num_items_in_batch argument exists in recent transformers versions, and accepting it with a default keeps the override compatible with older ones.
Note that metric_for_best_model is now macro_f1. If you kept selecting checkpoints by accuracy, the best checkpoint could be one that ignores the minority class.
Fix 2: resampling
Resampling changes the data instead of the loss. Oversampling repeats minority examples. Undersampling drops majority examples. Both apply to the training set only.
| Technique | Strength | Risk |
|---|---|---|
| Class weights | No change to data size or epoch time | Large weights make gradients noisy and training unstable |
| Oversampling | Minority examples are seen more often | Duplicates invite memorization, so overfitting is faster |
| Undersampling | Faster epochs | Throws away majority-class information |
| Threshold tuning | No retraining needed | Needs enough validation data of the rare class |
A simple oversampling step repeats the minority rows until the classes are equal in size.
from datasets import concatenate_datasets
minority = train_ds.filter(lambda x: x["label"] == 0)
majority = train_ds.filter(lambda x: x["label"] == 1)
repeats = len(majority) // len(minority)
oversampled = concatenate_datasets([majority] + [minority] * repeats).shuffle(seed=42)
print(oversampled.num_rows, np.bincount(oversampled["label"]))Do the split first and resample second. If you oversample before splitting, copies of the same review land in both training and validation. Your validation scores then measure memorization, not generalization.
Pick weights or oversampling, not both. Using both counts the correction twice and pushes the model into over-predicting the minority class.
Fix 3: tune the decision threshold
The model outputs two probabilities. argmax is the same as predicting the minority class whenever its probability exceeds 0.5. For a rare class, a different cutoff often gives a better trade-off between precision and recall. You can choose it after training, with no new run.
import numpy as np
import torch
from sklearn.metrics import f1_score
def minority_probs(trainer, dataset):
out = trainer.predict(dataset)
probs = torch.softmax(torch.tensor(out.predictions), dim=-1).numpy()
return probs[:, 0], out.label_ids # probability of class 0 (NEGATIVE)
val_p, val_y = minority_probs(trainer, val_ds)
best_t, best_f1 = 0.5, 0.0
for t in np.arange(0.05, 0.96, 0.05):
pred = np.where(val_p >= t, 0, 1)
score = f1_score(val_y, pred, pos_label=0, zero_division=0)
if score > best_f1:
best_t, best_f1 = float(t), score
print("best threshold:", round(best_t, 2), "minority F1:", round(best_f1, 3))
test_p, test_y = minority_probs(trainer, test_ds)
test_pred = np.where(test_p >= best_t, 0, 1)
print("test minority F1:", round(f1_score(test_y, test_pred, pos_label=0), 3))Choose the threshold on the validation set and report the result on the test set. If you pick it on the test set, the reported score is optimistic. With only about 45 minority examples in validation, the best threshold is noisy. Prefer a coarse grid and treat small differences as ties.
When the cost of a miss is known, for example a missed fraud case costs ten times a false alarm, choose the threshold from those costs instead of from F1.
Common errors
- Reporting accuracy. A 94% accuracy on a 90/10 dataset may mean the minority class is ignored. Always read per-class recall.
- Unstable training with weights. Weights like 50 on a tiny class make single batches dominate. Try the square root of the inverse frequency, or lower the learning rate.
- Missing minority examples per batch. With a 1% class and batch size 16, many batches contain none. Weights help, but gradients stay noisy. Larger batches or gradient accumulation (
gradient_accumulation_steps) smooth this. - Label order confusion. The code above treats class 0 as the minority. If your minority is label 1, change the indices in
compute_metricsand the threshold code. - Tiny validation counts. With fewer than about 30 examples of a class, metric differences between runs are mostly noise. Collect more labeled minority examples before tuning fine details. This usually helps more than any technique here.
Reading what remains
Once the numbers look acceptable, print the minority examples the model still gets wrong. They often show label noise, short or ambiguous texts, or subtypes of the rare class that never appear in training. The next chapter covers this process in more detail. Adding more examples of those subtypes usually beats further tuning of weights.
Exercise
Your validation set has 950 examples of class A and 50 of class B. Your model predicts A for every example. What are its accuracy, class B recall, and macro-F1? Name two ways to correct the training, and one thing you must not change.
Show answer
Accuracy is 950/1000 = 0.95. Class B recall is 0. F1 for class B is 0, and F1 for class A is 2·0.95·1/(0.95+1) ≈ 0.974, so macro-F1 is about 0.487. Two corrections are class weights in the loss (for example inverse-frequency weights through a custom compute_loss) and oversampling the minority class in the training set. You must not resample or reweight the validation or test set, since they have to keep the real label distribution. Choosing a decision threshold on validation data is another valid correction.
Exercise
You oversample the minority class to balance the data, then split the result 90/10 into training and validation. Validation F1 for the minority class reaches 0.99, but it performs poorly in production. What went wrong, and how do you fix the pipeline?
Show answer
Oversampling before splitting put identical copies of the same minority examples in both the training and validation sets, so the model was scored on text it had memorized. Fix it by splitting first (stratified), then oversampling only the training portion, and leaving the validation set with the natural distribution.