Imbalanced classes
When one class is rare, accuracy lies. Metrics and fixes that respect the minority.
Lesson 12 of 6612 minIntermediate
You will learn to
- Measure class imbalance
- Pick metrics that respect the minority class
- Compare class weights, resampling and threshold moves
Before this lesson
Intuition
Imagine a smoke detector that never rings. In a building where fires are very rare, it is "correct" almost every day. Nobody would call it good. A classifier trained on data where one class is rare faces the same trap: predicting the common class all the time gives a high accuracy and a useless model.
Class imbalance means the classes have very different sizes. It is normal in fraud, fault detection, rare diseases and churn. It is not a defect of the data; it is how the world is. The problems start when you use the wrong yardstick, or when the model has too few minority rows to learn from.
There are three levels of response, from cheapest to most costly:
- Measure honestly. Use metrics that look at the minority class.
- Move the decision threshold. Decide how much a missed case costs compared with a false alarm.
- Change the training. Give minority rows more weight, resample, or collect more of them.
Picture it
The minority share is a thin sliver. This is why accuracy, which counts every row equally, hides what happens to it.
The math
Let the classes have and rows. The imbalance ratio is
and the accuracy of the always-majority model is .
With a confusion matrix (true positives TP, false positives FP, false negatives FN, true negatives TN), three metrics that respect the minority:
Balanced accuracy is the mean of the recall on each class: .
Class weights rescale the loss. A common choice gives class the weight
where is the number of rows, the number of classes and the rows in class . Rare classes get larger weights, so each mistake on them costs more.
Worked example
We have 1,000 rows: 950 negatives, 50 positives. The imbalance ratio is 19 to 1, which the profile reports as a warning (see below). Always predicting negative gives 95% accuracy and recall 0.
A real model produces this confusion matrix at the default threshold of 0.5:
| Predicted positive | Predicted negative | |
|---|---|---|
| Actual positive (50) | TP = 30 | FN = 20 |
| Actual negative (950) | FP = 40 | TN = 910 |
- Accuracy = (30 + 910) / 1000 = 0.94, lower than the do-nothing model.
- Precision = 30 / 70 = 0.43, recall = 30 / 50 = 0.60, F1 = 0.50.
- Balanced accuracy = (0.60 + 910/950) / 2 = 0.78.
By accuracy this model looks worse than doing nothing. By F1 and recall it is clearly useful. This is the point of the lesson: the metric decides the verdict.
Moving the threshold. If missing a positive is much more costly than a false alarm, lower the threshold. Suppose that at a lower threshold the model catches 40 of the 50 positives, with 100 false alarms (TP = 40, FP = 100, FN = 10, TN = 850). Recall rises to 0.80, precision falls to 0.29, F1 is 0.42 and accuracy is 0.89. Whether that is better depends on costs: if each missed case costs ten times a false alarm, it is. These numbers are computed from the matrices above; the matrices themselves are illustrative.
Class weights. With 950 and 50 rows, the weights are 1000 / (2 x 950) = 0.53 for the majority and 1000 / (2 x 50) = 10 for the minority. Each minority row then counts about 19 times as much, so the total weight of the two classes is equal.
How mlflow does it
- Imbalance signal. The data profile compares the largest and smallest class of the target. A ratio of 3 to 1 or more raises a class imbalance warning; 10 to 1 or more raises it as an error. The Class balance card on the Quality tab shows the ratio, and the warning names the actual counts and suggests F1, balanced accuracy or ROC AUC. A class with fewer than 2 rows raises a rare class error, because it cannot appear on both sides of a split.
- Stratified split. For classification, the hold-out split and the default fold strategy (Stratified k-fold) keep the class shares the same in each part.
- Class weights. Some algorithms expose a
class_weighthyperparameter (for examplebalanced, which gives rare classes more importance, andNone, which counts every row equally). The hyperparameter help in the app explains each option. - Threshold. The Threshold sweep plot on a run shows how precision and recall move as the threshold changes, so you can pick a value from your own costs.
- No resampling step yet. The list of transformations in Pipeline Studio has no oversampling or undersampling step at the moment, so resampling needs to be done on the data you upload, which requires care (see below).
Common mistakes
- Judging by accuracy. It rewards the majority class. Use recall, precision, F1, balanced accuracy, or the precision-recall curve, and look at the confusion matrix.
- Resampling before splitting. Duplicating or synthesising rows before the split puts copies of the same row on both sides. Resample inside the training part only.
- Treating 0.5 as sacred. The default threshold assumes equal costs. Choose it from the costs of each kind of error.
- Balancing the test set. The test set should reflect the real class mix, otherwise precision will be misleading. Balance training, not evaluation.
- Ignoring tiny minorities. With 15 positives in a test set, every metric is noisy. Report uncertainty, prefer cross-validation, or gather more minority rows. More real data is usually the best fix.
Try it in mlflow
Check the imbalance signal
- Open Data and pick a dataset with a categorical target.
- Click Explore and open the Quality tab.
- Find the Class balance card and read the majority to minority ratio.
- Open the Overview tab and look for a class imbalance warning on the target.