Sub topic 10
Dealing with Imbalanced Classes
Assume you know Python, PyTorch tensors, train/validation/test splits, and the Hugging Face Trainer API. This chapter focuses on classification data where some labels appear much more often than others.
Why accuracy can mislead
A dataset is class-imbalanced when its labels have very different frequencies. For example, a support-ticket classifier might contain 9,000 normal tickets and 1,000 urgent tickets.
A model that always predicts “normal” gets 90% accuracy. However, it never finds an urgent ticket. Accuracy hides this failure because it gives the majority class most of the influence.
Use metrics that report performance for each class:
- Precision is the fraction of predicted positives that are correct.
- Recall is the fraction of actual positives that the model finds.
- F1 is the harmonic mean of precision and recall.
- Macro-F1 computes F1 for each class and then gives every class equal weight.
- Weighted-F1 weights each class by its number of examples.
Macro-F1 is often the better primary metric when minority classes matter. Weighted-F1 describes average performance across the examples, but it can still hide poor minority-class behavior.
| Metric | How classes contribute | Useful when |
|---|---|---|
| Accuracy | Majority classes dominate | Class frequencies are similar |
| Macro-F1 | Every class contributes equally | Minority classes matter |
| Weighted-F1 | Classes contribute by frequency | You need an overall example-weighted score |
Weighting the training loss
During training, the model minimizes a loss. For classification, this is usually cross-entropy. Class weighting multiplies the loss for an example by a value associated with its true class.
A common starting formula is:
weight(class) = number of examples / (number of classes × examples in that class)
Rare classes receive larger weights. A mistake on a rare example therefore affects the model update more strongly.
The following custom Trainer uses these weights. It assumes that train_ds, val_ds, model, tokenizer, and args were created in the earlier training steps.
import numpy as np
import torch
from transformers import Trainer
labels = np.asarray(train_ds["label"])
num_classes = model.config.num_labels
counts = np.bincount(labels, minlength=num_classes)
class_weights = len(labels) / (
num_classes * np.maximum(counts, 1)
)
class_weights = torch.tensor(class_weights, dtype=torch.float32)
class WeightedTrainer(Trainer):
def compute_loss(
self, model, inputs, return_outputs=False, num_items_in_batch=None
):
labels = inputs.pop("labels")
outputs = model(**inputs)
weights = class_weights.to(outputs.logits.device)
loss = torch.nn.functional.cross_entropy(
outputs.logits,
labels,
weight=weights,
)
return (loss, outputs) if return_outputs else loss
trainer = WeightedTrainer(
model=model,
args=args,
train_dataset=train_ds,
eval_dataset=val_ds,
data_collator=DataCollatorWithPadding(tokenizer),
compute_metrics=compute_metrics,
)
trainer.train()
print(trainer.evaluate())The weight vector must follow the model’s label IDs. If label 0 means urgent and label 1 means normal, the first weight must belong to urgent.
Other strategies and trade-offs
Class weighting is usually the safest first experiment, but it is not the only option.
- Oversampling repeats minority examples. It can improve recall, but repeated text may cause overfitting.
- Undersampling removes majority examples. It reduces training cost, but discards information.
- Data augmentation creates additional examples. Generated text must preserve the label.
- Threshold tuning changes the decision threshold after training. This can improve recall without retraining, especially for binary classification.
Do not rebalance the validation or test set just to obtain a better-looking score. If production data is imbalanced, evaluation should reflect that distribution. You can also report a confusion matrix and precision, recall, and F1 for every label.
Compare a baseline and a weighted run using the same split and random seed. If macro-F1 rises but minority precision collapses, the model may be predicting the rare class too often. Inspect examples and adjust weights or the decision threshold rather than assuming that a higher single metric means a better model.
Exercise
A test set has 950 examples of class 0 and 50 examples of class 1. A model reaches 95% accuracy but has recall 0.00 for class 1. Which additional metric should be emphasized, and what does the recall reveal?
Show answer
Emphasize macro-F1 and report per-class precision and recall. Class-1 recall of 0.00 means the model found none of the 50 minority examples, even though its accuracy looks high.