Sub topic 1
What class imbalance is and where it appears
Prerequisites
This chapter assumes you know basic Python and NumPy, and what supervised binary classification is. It also assumes you have used a train/test split and cross-validation, and that you know scikit-learn estimators. Later chapters cover pipelines in more detail.
What class imbalance means
A classification dataset is imbalanced when one class has far fewer examples than the other. The rare class is the minority class. The common class is the majority class. In binary problems the minority class is usually the positive class, the one you want to find.
The imbalance ratio is the number of majority examples divided by the number of minority examples. A dataset with 9,500 negatives and 500 positives has a ratio of 19 to 1, and the minority class makes up 5% of the rows.
There is no fixed cutoff for "imbalanced". Many practitioners start to worry below about 20% minority, and the problem becomes severe below 1%. The cutoff matters less than two questions. How many minority examples do you have in absolute terms? How costly is it to miss one?
Where it appears
Imbalance is the normal state of many real problems, because the events we care about are rare.
| Domain | Positive class | Typical minority share |
|---|---|---|
| Payments | Fraudulent transaction | Well below 1% |
| Medicine | Disease found in a screening test | A few percent or less |
| Manufacturing | Defective part | Often under 5% |
| Security | Intrusion or malware event | Well below 1% |
| Marketing | Customer who responds or churns | Often 1% to 10% |
In each case the rare class is the one with the high cost. A missed fraud or a missed tumour costs far more than a false alarm. This is why imbalance is a problem about both counts and costs.
Seeing imbalance in your data
The first step is to count. Always check the class distribution before you train anything.
import numpy as np
from sklearn.datasets import make_classification
X, y = make_classification(
n_samples=10000,
n_features=20,
n_informative=5,
weights=[0.95, 0.05],
flip_y=0.01,
random_state=42,
)
classes, counts = np.unique(y, return_counts=True)
for c, n in zip(classes, counts):
print(f"class {c}: {n} rows ({n / len(y):.1%})")
print("imbalance ratio:", counts.max() / counts.min())This dataset is synthetic. About 5% of the labels are positive, and flip_y=0.01 flips a small share of labels at random, so the exact counts are not 9,500 and 500. You will use this same data throughout the tutorial.
Why it causes trouble
Most learning algorithms minimise overall error. Each row counts equally, so the majority class dominates the loss. A model can lower its loss by fitting the majority class well and treating the minority class as noise.
Three effects follow.
- Accuracy looks high even when the model finds no positives. The next chapter shows this with numbers.
- The model sees few minority examples, so it has little evidence about what they look like. With only a few dozen positives, the learned pattern may be unstable.
- Random splits can distort the ratio. A small test set may contain very few positives, which makes any metric noisy.
Common errors at this stage
- Skipping the class count and assuming the data is balanced.
- Judging the imbalance by ratio alone. 500 positives out of 100,000 rows gives a poorer learning signal than 50,000 positives out of 5,000,000, even though both are 0.5%.
- Treating the training ratio as fixed. The ratio in production may differ from the ratio in your sample, especially if the data was collected by sampling.
- Rebalancing the data before deciding how to measure success. Choose metrics first, as the following chapters do.
Exercise
A dataset has 20,000 rows and 300 of them are positive. Compute the minority share and the imbalance ratio. Then name one reason the absolute count of 300 positives matters, apart from the share.
Show answer
The minority share is 300 / 20,000 = 1.5%. The majority has 19,700 rows, so the ratio is 19,700 / 300, about 65.7 to 1. The absolute count matters because 300 examples is little evidence for learning the positive pattern, and a test split will hold only a few dozen positives (for example about 75 in a 25% test set), which makes metrics noisy.