Learning outcomes

By the end of this lesson, you will be able to:

Central question If failures occur in only 2% of cases, why can a model with 98% Accuracy be completely useless? How can rare-event detection improve without distorting final evaluation?

1. What does class imbalance mean?

In classification, classes may occur at very different frequencies. If the positive class—a fraudulent transaction, rare defect, or equipment failure—makes up only a small fraction of observations, the data are described as imbalanced. This is not automatically a data error: it may accurately reflect the target environment.

Positive-class prevalence is the number of positive observations divided by the total. If 200 of 10,000 transactions are fraudulent, prevalence is 200 / 10,000 = 0.02, or 2%. There are 9,800 negative observations, giving a class ratio of 1:49.

Positive-class prevalenceπ = N₊ / (N₊ + N₋)π is the fraction of positive observations; N₊ is the number of positive observations; N₋ is the number of negative observations. The formula shows what fraction of the target population consists of the events we want to detect.

Do not confuse a rare event with poor labelling. Do not force a dataset to 50:50 merely because that seems convenient for training. First establish whether prevalence represents the target environment, how the positive class is defined, and whether event frequency changes over time.

Class imbalance — a substantial difference in the number of observations belonging to different classes.
Class prevalence in a dataset of 10,000 eventsThe positive class is 2%; the negative class is 98%. The bar represents counts, not class importance.Negative 98%Positive 2%200 / 10,000
The positive class is 2%; the negative class is 98%. The bar represents counts, not class importance.

2. The high-Accuracy trap

Consider 10,000 transactions: 200 positive and 9,800 negative. A trivial classifier always predicts “negative”. It correctly classifies all 9,800 negatives and misses all 200 positives. Accuracy is 98%, but positive-class Recall is zero.

This is a majority-class baseline: a model that always predicts the most frequent class. It is a useful control: a complex model should beat it on metrics that matter to the task, not merely on an overall percentage.

The counts are TP = 0, FN = 200, FP = 0, TN = 9,800. Accuracy = (TP + TN) / N = 98%; Recall = TP / (TP + FN) = 0%. Precision is mathematically undefined when there are no positive predictions; some libraries conventionally return 0 with a warning.

Majority-class baseline — a simple model that always predicts the most frequent class.

3. How prevalence affects Precision

Recall and FPR are rates calculated within each true class. Precision asks a different question: what fraction of positive predictions are correct? It therefore depends not only on model separation but also on the frequency of the positive class in the incoming population.

At 2% prevalence in 10,000 observations, there are 200 positives and 9,800 negatives. Let TPR = 0.80 and FPR = 0.02. Then TP = 160, FN = 40, FP = 196, TN = 9,604. Precision = 160 / (160 + 196) ≈ 44.9%, while Recall = 80%. Despite an FPR of only 2%, more than half of alerts are false.

Precision in terms of prevalence, TPR, and FPRPrecision = (TPR × π) / (TPR × π + FPR × (1 − π))TPR is the fraction of positive cases detected; FPR is the fraction of negative cases incorrectly flagged as positive; π is prevalence. With TPR and FPR fixed, reducing π generally reduces Precision.

If prevalence falls to 0.2% while TPR and FPR remain unchanged, Precision falls further. The same ROC characteristics do not guarantee the same practical alert value in different populations. Re-check the base rate and operating threshold when moving a model to a new environment.

Confusion counts for one modelAt TPR 80% and FPR 2%, we get 160 TP and 196 FP: a low FPR does not mean high Precision.TP = 160True positivesFP = 196False positivesFN = 40False negativesTN = 9,604True negativesRecall = 80% · Precision ≈ 44.9%
At TPR 80% and FPR 2%, we get 160 TP and 196 FP: a low FPR does not mean high Precision.

4. Methods for handling imbalance

Class weighting increases the contribution of rare-class errors to the loss function. A simple approach assigns weights inversely proportional to class frequency. This makes optimization pay more attention to rare examples, but creates no new information and may increase false alerts. Probabilities from a weighted model may need separate calibration.

Oversampling increases minority examples: simple duplication can overfit individual observations. Undersampling reduces majority examples and speeds training, but may discard useful information. These methods change training data, not target reality.

SMOTE (Synthetic Minority Over-sampling Technique) creates synthetic points by interpolating between neighbouring minority examples. Generated points may be unrealistic with categorical features, complex class geometry, outliers, or strong feature dependence. No method guarantees improvement: compare it with a baseline on identical splits.

Weighted loss functionL = w₊ · L₊ + w₋ · L₋L₊ and L₋ are average losses on positive and negative examples; w₊ and w₋ are class weights. Increasing w₊ gives rare-class errors more influence but does not guarantee improvement.

5. Stratification and leakage prevention

A stratified split preserves approximately the same class proportion in train, validation, and test. This matters when positives are scarce: a random split may leave too few events—or none—in one partition.

Stratification does not replace a correct split strategy. If rows belong to the same customer, device, or patient, use group splitting. If the task predicts the future, use a time-based split. Do not sacrifice group independence or chronology to preserve class proportions.

Split first, then apply oversampling, undersampling, or SMOTE only to training data. If rare examples are copied before splitting, identical or related examples may appear in both train and test. That is leakage and inflates the estimate. In cross-validation, resampling must be repeated inside each training fold.

In cross-validation, resampling must be repeated inside each training fold.

A safe data-preparation orderSplit first, then resample training data only; validation and test retain natural prevalence.Split firstTrain / validation / testResample train onlyTraining partitionKeep validation and testNatural prevalence
Split first, then resample training data only; validation and test retain natural prevalence.

6. Evaluating rare-event models

Start with the confusion matrix and absolute TP, FP, TN, and FN counts. Percentages without denominators hide scale: an FPR of 2% means 20 false alerts per 1,000 negative observations, but at millions of observations it can create a large workload.

For rare events, consider Recall, Precision, F1 or Fβ, PR-AUC / Average Precision, and operational metrics such as alerts per day, fraction reviewed, cost of a missed event, and review cost. ROC-AUC remains useful for ranking but does not directly describe alert Precision at a particular prevalence.

Choose the threshold on validation data, considering workload and error costs. If probabilities matter, check calibration separately. Once the protocol is fixed, use test for final independent evaluation. Record prevalence and monitor it in deployment.

7. Worked example and common mistakes

A monitoring service processes 10,000 events: 200 real failures and 9,800 normal states. The model produces TP = 160, FN = 40, FP = 196, TN = 9,604. Recall = 80%, Precision ≈ 44.9%, and Accuracy = 97.64%.

The majority baseline has 98% Accuracy but 0% Recall. The failure detector has slightly lower Accuracy yet finds 160 of 200 failures. However, 196 false alerts must be compared with team capacity: if every alert needs manual review, the threshold may be too costly.

Common mistakes include balancing the full dataset before splitting; evaluating on an artificially balanced test set; allowing copies of rare examples into train and test; treating SMOTE as universal; selecting a threshold on test; reporting Accuracy alone; omitting prevalence; and ignoring group or temporal dependencies.

Practical exercise

For 10,000 events, there are 200 positive and 9,800 negative observations. The model produces TP = 160, FN = 40, FP = 196, and TN = 9,604.

  1. Calculate prevalence, Accuracy, Precision, and Recall.
  2. Compare the model with an always-negative rule. What Accuracy and Recall does the baseline achieve?
  3. Explain why an FPR of 2% does not mean Precision is 98%.
  4. Suggest two ways to change training and name one risk of each.
  5. At what stage may SMOTE be applied, and why must it not run before splitting?

Expected result: Prevalence = 2%; Accuracy = 97.64%; Precision ≈ 44.9%; Recall = 80%. Majority baseline: Accuracy = 98%, Recall = 0%. SMOTE is applied only inside training and each training fold; validation/test retain the natural distribution.

Conclusion:Class imbalance changes how classifier quality should be interpreted, but it does not make the data wrong. Accuracy can hide failure on a rare class; Precision depends on prevalence; resampling and SMOTE require strict leakage prevention. Reliable evaluation combines a confusion matrix, positive-class metrics, PR analysis, operational constraints, and testing on the natural distribution.

Sources and further reading

  1. He, H. & Garcia, E. A. (2009). Learning from Imbalanced Data. IEEE Transactions on Knowledge and Data Engineering, 21(9), 1263–1284.. A review of learning and evaluation methods for imbalanced data.
  2. Saito, T. & Rehmsmeier, M. (2015). The Precision-Recall Plot Is More Informative than the ROC Plot When Evaluating Binary Classifiers on Imbalanced Datasets. PLOS ONE, 10(3).. Why PR analysis is especially useful with a rare positive class.
  3. Chawla, N. V. et al. (2002). SMOTE: Synthetic Minority Over-sampling Technique. Journal of Artificial Intelligence Research, 16, 321–357.. The original paper on synthetic oversampling.

Key terms

Class prevalenceClass prevalenceThe fraction of observations belonging to a class in the target population; positive prevalence is denoted by π.
Class imbalanceClass imbalanceA substantial difference in the number of observations belonging to different classes.
Class weightingClass weightingAssigning different weights to classes in the training loss function.
Oversampling / undersamplingResamplingIncreasing minority examples or reducing majority examples inside training data.
SMOTESynthetic Minority Over-sampling TechniqueCreating synthetic minority examples by interpolating between neighbouring observations.

Knowledge check

Choose one answer for each question. Feedback appears after you select Check answer.

Question 1

How is positive-class prevalence calculated?

Question 2

A dataset contains 2% positives. A model always predicts negative. What does it achieve?

Question 3

Why can Precision fall when prevalence falls but TPR and FPR stay fixed?

Question 4

Where may SMOTE be applied?

Question 5

What does stratified splitting do?

Question 6

Which statement about SMOTE is correct?

Question 7

What is a suitable rare-event evaluation report?