Search

Search papers and lessons

Class Imbalance

Level 3 · 12 min read

Class imbalance is when one answer is far rarer than the other in training data, so a classifier can score well on accuracy while missing nearly every rare case.

On this page

  • Colour = topic mix
  • Discrete math
  • Probability
  • Calculus
  • Learning basics
  • Losses & regularization
  • Inference
  • ReadReady to readNot yet

TL;DR

A classifier learns from examples labelled with one of two answers. Class imbalance means one answer is far more common than the other, for example 1 positive case in 100. A model trained on such data can reach high accuracy by mostly predicting the common answer, and still miss almost every rare case. Methods for handling it either change how errors are counted during training, change how many examples of each class the model sees, or change the threshold used to turn a score into an answer. The right choice depends on what a missed rare case costs.

Builds on: Precision and Recall, Resampling, Cross-Entropy Loss · Leads to: Focal Loss

This lesson is about a machine learning method. It is not advice for any particular decision.

Where it's used

Card fraud detection. Most card transactions are genuine, and fraud is a small fraction of them. A bank's training data might have one fraudulent transaction in a thousand. A model that never flags fraud is right 99.9 percent of the time, so accuracy alone says nothing about whether it catches fraud. Teams therefore measure precision and recall on the rare class.

Manufacturing defect detection. A factory inspects parts with cameras, and most parts pass. If defects are rare, the training set has few examples of the defect class, and the model may learn only the look of good parts. The cost of a missed defect can be much higher than the cost of a false alarm, so the threshold is set with that cost in mind.

Screening and rare events in research. Studies of rare events, such as a particular failure in a machine or a rare genetic variant in a large dataset, face the same problem. The positive class may have a few hundred examples among millions of rows. Analysts usually report the counts of each class and per-class metrics, not one accuracy figure.

How it works

Take a tiny fraud dataset of 1,000 transactions. Ten are fraud (positive) and 990 are genuine (negative). Use four counts to describe what any classifier, such as Logistic Regression, does on this data: fraud cases flagged as fraud (true positives), genuine cases flagged as fraud (false positives), fraud cases missed (false negatives), and genuine cases cleared (true negatives). These four counts make up the Confusion Matrix.

  1. Start with the trivial model. It predicts "genuine" for every transaction. It catches 0 of the 10 frauds and correctly clears all 990 genuine cases. Check: 0+990=9900 + 990 = 990 correct out of 1,000.
  2. Compute its accuracy. Accuracy is 990/1000=99990 / 1000 = 99 percent. This looks excellent, yet the model is useless for finding fraud.
  3. Try a model that flags more. Model B flags 48 transactions as fraud. Of those, 8 really are fraud and 40 are genuine. It misses 2 frauds and clears 950 genuine cases. Check: 8+40+2+950=10008 + 40 + 2 + 950 = 1000.
  4. Compute its accuracy. (8+950)/1000=95.8(8 + 950) / 1000 = 95.8 percent. Accuracy went down, so a naive score ranks Model B below the trivial model.
  5. Compute the rare-class measures. Recall is the share of frauds caught: 8/10=808 / 10 = 80 percent. Precision is the share of flagged cases that are fraud: 8/48≈16.78 / 48 \approx 16.7 percent. Check: the trivial model has recall 0, so it fails the task that matters.
  6. Look at the training signal. During training, a loss adds up the error on every example, and gradient descent lowers that total. The 990 genuine cases can outnumber the frauds about 99 to 1, so their small errors can add up to more than the errors on the frauds. The model is then pushed mainly toward the easy majority answer.
  7. Weight the errors. Give each fraud example a weight of 99 and each genuine example a weight of 1. Now one fraud error counts as much as 99 genuine errors, which balances the total pull of the two classes. Check: 10×99=99010 \times 99 = 990, the same total weight as the 990 genuine cases.
flowchart LR
  A["Imbalanced training data: 10 fraud, 990 genuine"] --> B{"Handle the imbalance"}
  B --> C["Weight errors by class"]
  B --> D["Resample the classes"]
  B --> E["Move the decision threshold"]
  C --> F["Evaluate with precision and recall"]
  D --> F
  E --> F

The math

Definition: Class imbalance

A two-class dataset is imbalanced when one class, the rare class, has a much smaller share of the examples than the other. If n+n_+ is the number of rare-class examples and n−n_- the number of common-class examples, the prior share of the rare class is π=n+/(n++n−)\pi = n_+ / (n_+ + n_-), and π\pi is small.

Step 1 in symbols: the trivial model's accuracy

For the example, n+=10n_+ = 10, n−=990n_- = 990, and π=10/1000=0.01\pi = 10 / 1000 = 0.01. A model that always predicts negative has accuracy 1−π=0.991 - \pi = 0.99 and recall 00. In general, accuracy of a constant prediction equals the share of the majority class, so accuracy cannot separate a good model from a useless one when π\pi is small.

Step 2 in symbols: precision and recall

With true positives TPTP, false positives FPFP, false negatives FNFN, and true negatives TNTN:

precision=TPTP+FP,recall=TPTP+FN.\text{precision} = \frac{TP}{TP + FP}, \qquad \text{recall} = \frac{TP}{TP + FN}.

For Model B, TP=8TP = 8, FP=40FP = 40, FN=2FN = 2, so precision is 8/48≈0.1678/48 \approx 0.167 and recall is 8/10=0.808/10 = 0.80.

Step 3 in symbols: the weighted loss

Let yi∈{0,1}y_i \in \{0, 1\} be the label and pip_i the predicted Probability that yi=1y_i = 1. The Cross-Entropy Loss of a single example is −[yiln⁡pi+(1−yi)ln⁡(1−pi)]-\left[ y_i \ln p_i + (1 - y_i) \ln(1 - p_i) \right]. Give each class its own weight, and average over the NN examples:

L=−1N∑i=1N[w+ yiln⁡pi+w− (1−yi)ln⁡(1−pi)].L = -\frac{1}{N} \sum_{i=1}^{N} \Big[ w_{+}\, y_i \ln p_i + w_{-}\,(1 - y_i) \ln(1 - p_i) \Big].

A common choice is wc=N/(2nc)w_c = N / (2 n_c) for each class cc, which makes both classes contribute the same total weight. For the example, w+=1000/20=50w_{+} = 1000 / 20 = 50 and w−=1000/1980≈0.505w_{-} = 1000 / 1980 \approx 0.505. The walkthrough used w+=99w_{+} = 99 and w−=1w_{-} = 1, which is the ratio n−/n+n_- / n_+ and gives both classes the same total weight, 990990. Either choice balances the two sums.

Step 4 in symbols: resampling changes the class balance

If the positive examples are copied until there are 990 of them, the new training set has 990+990=1980990 + 990 = 1980 rows. The positive share is 990/1980=0.5990 / 1980 = 0.5. Copying does not add new information, so the copies must be handled carefully to avoid memorising the same few examples.

Step 5 in symbols: the threshold

A classifier turns its score pp into an answer by comparing it with a threshold tt: flag the case if p>tp \gt t. The default t=0.5t = 0.5 assumes that both kinds of error cost the same. When misses are costlier, lowering tt raises recall and lowers precision. The threshold is then chosen on held-out data, from the precision and recall trade-off.

Worked examples

Example
Tiny: ten cases, one positive

A dataset has 10 examples, and only one is positive.

  1. A model that always predicts negative gets 9 of the 10 right.
  2. Accuracy is 9/10=909 / 10 = 90 percent.
  3. Its recall is 0/1=00 / 1 = 0, since the one positive is missed.
  4. Interpretation: a 90 percent accuracy comes from the imbalance alone. The number says nothing about whether the rare case was found.
Example
Standard: the fraud dataset, two models

Use the counts from the walkthrough. Model A predicts negative for all 1,000 cases, with TP=0TP = 0, FP=0FP = 0, FN=10FN = 10, TN=990TN = 990. Model B has TP=8TP = 8, FP=40FP = 40, FN=2FN = 2, TN=950TN = 950.

  1. Model A accuracy: (0+990)/1000=0.990(0 + 990) / 1000 = 0.990.
  2. Model B accuracy: (8+950)/1000=0.958(8 + 950) / 1000 = 0.958.
  3. Model A recall: 0/(0+10)=00 / (0 + 10) = 0. Model A precision is undefined, because it flags nothing.
  4. Model B recall: 8/(8+2)=0.808 / (8 + 2) = 0.80.
  5. Model B precision: 8/(8+40)≈0.1678 / (8 + 40) \approx 0.167.
  6. Interpretation: Model B has lower accuracy and far more practical value. It finds 8 of 10 frauds, at the cost of 40 false alarms. Only the rare-class measures show this.
Example
Realistic: one batch with weighted errors

A training batch has two examples. Example 1 is fraud, with label 1, and the model predicts p=0.2p = 0.2. Example 2 is genuine, with label 0, and the model predicts p=0.2p = 0.2 for fraud, so it gives 1−p=0.81 - p = 0.8 to genuine. Use weights w+=99w_{+} = 99 and w−=1w_{-} = 1.

  1. Loss for example 1: −ln⁡(0.2)≈1.609-\ln(0.2) \approx 1.609. Weighted by 99, this is 99×1.609≈159.399 \times 1.609 \approx 159.3.
  2. Loss for example 2: −ln⁡(0.8)≈0.223-\ln(0.8) \approx 0.223. Weighted by 1, this is 0.2230.223.
  3. Compare: the fraud error costs about 159.3/0.223≈714159.3 / 0.223 \approx 714 times the genuine error.
  4. Interpretation: the weighting makes the model strongly prefer raising its fraud probability. Without weights, the two losses would differ only by a factor of 1.609 over 0.223, about 7 to 1.
  5. Try it: suppose the model's fraud prediction for example 1 improves to p=0.9p = 0.9, and the weight stays 99. What is the weighted loss for example 1?

Answer: −ln⁡(0.9)≈0.105-\ln(0.9) \approx 0.105, and 99×0.105≈10.499 \times 0.105 \approx 10.4. The loss fell from about 159.3 to about 10.4 because the model now gives the true class a high probability.

Common mistakes and tradeoffs

It is tempting to think that high accuracy means a good classifier. In fact, when one class is rare, a model that ignores it can have very high accuracy. Use precision, recall and the confusion matrix on the rare class instead.

It is tempting to think that copying rare examples always helps. In fact, copies add no new information, and a model can memorise them and do worse on new data. Resampling is most useful when the rare class has some variety to learn from.

It is tempting to think that discarding common-class examples is safe. In fact, it throws away information about what genuine cases look like, and the model may then flag too many of them. Undersampling is a reasonable choice when the common class is very large and redundant.

It is tempting to think that the default threshold of 0.5 is correct. In fact, the threshold encodes a belief about the cost of each error. When a miss is much costlier than a false alarm, a lower threshold is usually right.

When to act on imbalance. Act when the rare class matters for the decision and the model's per-class results are poor. Check the counts and the rare-class measures before training anything.

When not to bother. If the classes are roughly balanced, or if the model's probabilities are already good and the cost of errors is similar, no special handling may be needed.

MethodWhat it changesCost
Class weights in the lossHow much each error countsCan make training noisy when weights are very large
Oversampling the rare classHow many copies the model seesRisk of memorising copies
Undersampling the common classHow many common examples remainLoses information
Moving the thresholdHow scores become answersNeeds held-out data to choose

A specialised loss, Focal Loss, reduces the weight of easy examples so that rare, hard examples dominate the gradient.

History

Early work on classification mostly assumed balanced costs and balanced classes. As classifiers were used in medical screening, credit scoring and fraud detection through the 1990s and 2000s, researchers noticed that accuracy hid poor performance on rare cases, and that the rare class was often the one that mattered.

In 2002 Chawla and colleagues introduced SMOTE, a method that creates new synthetic minority examples by interpolating between existing ones instead of copying them. It became a standard tool, although its synthetic points can be unrealistic in high dimensions.

In 2017 the focal-loss paper, Focal Loss for Dense Object Detection, proposed scaling the cross-entropy loss by a factor that shrinks for well-classified examples. It showed that a single-stage detector could match two-stage detectors on an imbalanced object-detection task, because easy background examples no longer overwhelmed training.

Recap

  • Accuracy can look high on imbalanced data even when the rare class is never found.
  • Precision and recall on the rare class, read from the confusion matrix, show what a model actually does.
  • Class weights change how much each error counts, so the loss stops being dominated by the common class.
  • Resampling changes the class balance by copying or dropping examples, with trade-offs in memory and information.
  • Moving the threshold trades precision for recall and should be chosen from the cost of each error.
  • Read next: Focal Loss, a loss designed for this problem.

Check yourself

QuestionRecall: why does a model that always predicts the common class get high accuracy but zero recall on the rare class?Show answer
Because the common class makes up most of the examples, a constant prediction of that class is right on most cases, so accuracy is high. The rare class is never predicted, so no rare case is found, and recall on that class is zero.
QuestionComputation: a dataset has 200 positives and 1,800 negatives. A model flags 150 cases, of which 120 are positive. What are the precision and the recall? Give numbers.Show answer
Precision is 120/150=0.80120 / 150 = 0.80. Recall is 120/200=0.60120 / 200 = 0.60. Answer: precision 80 percent, recall 60 percent.
QuestionWhy: a team trains a classifier on imbalanced data and reports that it is 98 percent accurate. Why might the team still have a poor model?Show answer
The 98 percent may come mainly from the common class. If the rare class is only 2 percent of the data, a model that rarely predicts it can be accurate overall while missing most rare cases. The team should check precision and recall on the rare class.
QuestionApplied: a screening tool for a rare defect misses a defect at a much higher cost than a false alarm. Should the team raise or lower the decision threshold, and why?Show answer
Lower it. A lower threshold flags more cases, which raises recall (fewer misses) at the cost of more false alarms and lower precision. Because a miss is costlier than a false alarm, that trade is the right one, and the exact threshold should be picked on held-out data.

Sources