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.
- 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: correct out of 1,000.
- Compute its accuracy. Accuracy is percent. This looks excellent, yet the model is useless for finding fraud.
- 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: .
- Compute its accuracy. percent. Accuracy went down, so a naive score ranks Model B below the trivial model.
- Compute the rare-class measures. Recall is the share of frauds caught: percent. Precision is the share of flagged cases that are fraud: percent. Check: the trivial model has recall 0, so it fails the task that matters.
- 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.
- 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: , 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
A two-class dataset is imbalanced when one class, the rare class, has a much smaller share of the examples than the other. If is the number of rare-class examples and the number of common-class examples, the prior share of the rare class is , and is small.
Step 1 in symbols: the trivial model's accuracy
For the example, , , and . A model that always predicts negative has accuracy and recall . 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 is small.
Step 2 in symbols: precision and recall
With true positives , false positives , false negatives , and true negatives :
For Model B, , , , so precision is and recall is .
Step 3 in symbols: the weighted loss
Let be the label and the predicted Probability that . The Cross-Entropy Loss of a single example is . Give each class its own weight, and average over the examples:
A common choice is for each class , which makes both classes contribute the same total weight. For the example, and . The walkthrough used and , which is the ratio and gives both classes the same total weight, . 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 rows. The positive share is . 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 into an answer by comparing it with a threshold : flag the case if . The default assumes that both kinds of error cost the same. When misses are costlier, lowering raises recall and lowers precision. The threshold is then chosen on held-out data, from the precision and recall trade-off.
Worked examples
A dataset has 10 examples, and only one is positive.
- A model that always predicts negative gets 9 of the 10 right.
- Accuracy is percent.
- Its recall is , since the one positive is missed.
- Interpretation: a 90 percent accuracy comes from the imbalance alone. The number says nothing about whether the rare case was found.
Use the counts from the walkthrough. Model A predicts negative for all 1,000 cases, with , , , . Model B has , , , .
- Model A accuracy: .
- Model B accuracy: .
- Model A recall: . Model A precision is undefined, because it flags nothing.
- Model B recall: .
- Model B precision: .
- 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.
A training batch has two examples. Example 1 is fraud, with label 1, and the model predicts . Example 2 is genuine, with label 0, and the model predicts for fraud, so it gives to genuine. Use weights and .
- Loss for example 1: . Weighted by 99, this is .
- Loss for example 2: . Weighted by 1, this is .
- Compare: the fraud error costs about times the genuine error.
- 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.
- Try it: suppose the model's fraud prediction for example 1 improves to , and the weight stays 99. What is the weighted loss for example 1?
Answer: , and . 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.
| Method | What it changes | Cost |
|---|---|---|
| Class weights in the loss | How much each error counts | Can make training noisy when weights are very large |
| Oversampling the rare class | How many copies the model sees | Risk of memorising copies |
| Undersampling the common class | How many common examples remain | Loses information |
| Moving the threshold | How scores become answers | Needs 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.