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:

  1. Measure honestly. Use metrics that look at the minority class.
  2. Move the decision threshold. Decide how much a missed case costs compared with a false alarm.
  3. Change the training. Give minority rows more weight, resample, or collect more of them.

Picture it

1,000 rows: 950 majority, 50 minority (19 to 1)Train: 665 + 35Test: 285 + 15Always predicting the majority class: 95% accuracy, 0 minority rows found
A 1,000-row target with 50 minority rows. A stratified 70/30 split keeps the same share in both parts. A model that always says 'majority' still scores 95% accuracy.

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 nmajn_{\text{maj}} and nminn_{\text{min}} rows. The imbalance ratio is

ρ=nmajnmin\rho = \frac{n_{\text{maj}}}{n_{\text{min}}}

and the accuracy of the always-majority model is nmaj/(nmaj+nmin)n_{\text{maj}}/(n_{\text{maj}}+n_{\text{min}}).

With a confusion matrix (true positives TP, false positives FP, false negatives FN, true negatives TN), three metrics that respect the minority:

precision=TPTP+FP,recall=TPTP+FN,F1=2 precision⋅recallprecision+recall\text{precision} = \frac{TP}{TP+FP}, \qquad \text{recall} = \frac{TP}{TP+FN}, \qquad F_1 = \frac{2\,\text{precision}\cdot\text{recall}}{\text{precision}+\text{recall}}

Balanced accuracy is the mean of the recall on each class: 12(TPTP+FN+TNTN+FP)\tfrac{1}{2}\left(\tfrac{TP}{TP+FN} + \tfrac{TN}{TN+FP}\right).

Class weights rescale the loss. A common choice gives class cc the weight

wc=nK ncw_c = \frac{n}{K\, n_c}

where nn is the number of rows, KK the number of classes and ncn_c the rows in class cc. 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 positivePredicted negative
Actual positive (50)TP = 30FN = 20
Actual negative (950)FP = 40TN = 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_weight hyperparameter (for example balanced, which gives rare classes more importance, and None, 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

  1. Open Data and pick a dataset with a categorical target.
  2. Click Explore and open the Quality tab.
  3. Find the Class balance card and read the majority to minority ratio.
  4. Open the Overview tab and look for a class imbalance warning on the target.
Open in mlflow

Read in the docs

Check your understanding

  1. 1. A dataset has 950 negatives and 50 positives. A model that always predicts negative has what accuracy?
  2. 2. Which change does NOT alter the model, only how its scores are turned into decisions?
  3. 3. Where must oversampling be done in a validation workflow?