Sub topic 1
What Class Imbalance Is and Where It Appears
Prerequisites
This chapter assumes you already know the following:
- Basic Python and NumPy.
- Supervised binary classification: features, labels, and a model that predicts one of two classes.
- Train/test splits and cross-validation.
- How to fit and call a scikit-learn estimator.
You do not need any knowledge of resampling, class weights, or specialized metrics. Later chapters introduce those.
What class imbalance means
A classification dataset is imbalanced when the classes appear with very different frequencies. The class with many examples is the majority class. The class with few examples is the minority class. In binary problems the minority class is usually called the positive class, because it is the event you want to detect.
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:1, which is a 5% positive rate.
There is no official threshold for "imbalanced". The practical test is whether the imbalance changes what you should do. Three things usually decide this:
- The ratio. 60/40 is rarely a problem. 95/5 often is. 99.9/0.1 almost always is.
- The absolute count of minority examples. 50 positives out of 5,000 and 5,000 positives out of 500,000 have the same ratio, but they behave differently. With 5,000 positives, a model has plenty of examples to learn from. With 50, it does not.
- The cost of errors. If missing a positive is expensive, even a mild imbalance deserves attention.
Why the minority class is usually the one you care about
Imbalance is rarely a coincidence. It often exists because the thing you want to find is rare. Most transactions are legitimate, most patients screened do not have the disease, and most manufactured parts are not defective. The model is only useful if it finds the rare cases.
This creates a mismatch. Standard training procedures minimize overall error. When one class supplies 95% of the examples, the model is rewarded mostly for getting that class right. The class you care about contributes little to the training signal.
Where imbalance appears
The table lists common domains. Positive rates are typical orders of magnitude, not exact figures.
| Domain | Positive class | Typical positive rate | Cost of a missed positive |
|---|---|---|---|
| Card fraud detection | Fraudulent transaction | 0.1% or lower | Direct financial loss |
| Disease screening | Patient with the condition | 0.1% to 5% | Delayed treatment |
| Manufacturing inspection | Defective part | 0.1% to 2% | Recalls, safety risk |
| Intrusion detection | Malicious connection | Often below 1% | Security breach |
| Customer churn | Customer who leaves | 2% to 20% | Lost revenue |
| Click prediction in ads | Click | 1% to 5% | Lost conversion |
| Rare-event forecasting | Equipment failure | Below 1% | Downtime |
Notice that the cost of a missed positive is different from the cost of a false alarm. In fraud detection, a false alarm costs an analyst a few minutes, while a missed fraud may cost thousands. This asymmetry matters throughout the tutorial, because it decides which remedy fits.
Where imbalance comes from
Knowing the source helps you decide what to do about it.
- Natural rarity. The event is rare in the real world. Fraud is an example. The imbalance in your data reflects the imbalance in production, so it is information, not a defect.
- Sampling and collection effects. Positives may be under-recorded. A defect log might only capture defects someone noticed. This is a label problem as much as an imbalance problem.
- Deliberate sampling. A team may collect all positives and a sample of negatives, or the reverse. The ratio in the dataset then differs from the ratio in production. This matters later for probability calibration.
- Time and filtering. Rules upstream may remove many positives or negatives before the data reaches you.
You should always ask whether the ratio in your training data matches the ratio the model will see in production. If it does not, any metric computed on a re-sampled or filtered dataset may not predict production behavior.
Seeing imbalance in data
Always check the label distribution before you train anything. The following code builds a synthetic dataset with about 5% positives and prints the class counts.
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,
)
counts = np.bincount(y)
print("class counts:", counts)
print("positive rate:", counts[1] / counts.sum())
print("imbalance ratio:", counts[0] / counts[1])The weights argument sets the requested class proportions. The flip_y=0.01 argument randomly flips 1% of the labels, which adds a little noise and moves the final rate slightly away from exactly 5%. The printed positive rate should be close to 0.05, and the ratio close to 19 or 20.
With real data, the same check on a pandas column is df["label"].value_counts(normalize=True). Do this on the raw data, and again on each split you create. A split that accidentally loses most of the positives will give misleading results, and the chapter on stratified splitting covers how to prevent that.
What imbalance does to a model
Imbalance does not make a model fail loudly. It tends to produce a model that looks fine under default measurements and is poor at the task. Several effects combine.
- Few minority examples to learn from. A model sees far fewer positive examples, so the decision boundary around the minority class is poorly determined. The region of feature space where positives live may be represented by only a handful of points.
- A loss dominated by the majority. Most training losses add up errors over all examples. If 95% of examples are negative, 95% of the loss comes from negatives. Reducing the majority's errors helps the loss more than learning the rare class does.
- Biased predicted probabilities. A model trained on 5% positives tends to output low probabilities for everything. With a default cutoff of 0.5, few examples ever cross it, so the model rarely predicts the positive class.
- Overlapping classes make it worse. If the classes overlap in feature space, a model unsure about a region will favor the majority class, because that class is more common there.
- Noisy estimates. With few positives, a metric on the minority class has high variance. Recall measured on 20 test positives can swing by many percentage points between splits.
That last point is easy to overlook. If your test set has 1,000 examples and 2% are positive, you have only 20 positives. One more or fewer detected changes recall by 5 percentage points. Always report the number of minority examples behind a metric.
Imbalance is not always a problem
Not every imbalanced dataset needs a remedy. Some cases to consider before changing anything:
- The model already separates the classes well. If the classes are well separated, a model can detect the rare class without any special treatment. The problem grows as the signal weakens.
- You only need a ranking. If the output is a ranked list that analysts review from the top, ranking quality matters more than any cutoff. Some imbalance methods are unnecessary there.
- You need honest probabilities. Rebalancing the training data changes predicted probabilities. If the downstream use depends on probabilities that reflect true risk, rebalancing can hurt unless you correct it afterwards. The calibration chapter returns to this.
- Collecting more minority data is possible. More real positives usually beats any synthetic method. If you can get them, consider that first.
A good habit is to train a plain baseline first and measure it with suitable metrics. Only then decide whether a remedy is needed, and compare against that baseline.
How the rest of the tutorial fits together
The chapters follow the order in which you meet the problem.
Read the diagram top to bottom. First you learn to detect the problem and measure it properly. Then you learn the remedies that change training, then the ones that change the decision, and finally how to choose among them.
A first look at the consequence
The next chapter explores this in detail, but a short preview shows why the problem is real. The code below splits the data from earlier and trains a classifier that always predicts the majority class.
from sklearn.model_selection import train_test_split
from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score, recall_score
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
baseline = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
pred = baseline.predict(X_test)
print("accuracy:", accuracy_score(y_test, pred))
print("minority recall:", recall_score(y_test, pred))This code continues from the previous example, which defines X and y. The stratify=y argument keeps the class ratio the same in both splits. You should see an accuracy of about 0.95 and a minority recall of 0.0. The model never finds a single positive, and yet its accuracy looks excellent. That gap is the subject of the next chapter.
Common mistakes at this stage
- Skipping the label count. Teams sometimes train for days before noticing that the positive rate is 0.3%.
- Trusting a single ratio. A 1% positive rate in 10 million rows is a different problem from 1% in 2,000 rows.
- Treating imbalance as a bug in the data. If rarity is real, the imbalance is part of the problem. Changing the data's ratio changes what the model learns about base rates.
- Applying a remedy before choosing a metric. Without a metric that reflects your goal, you cannot compare remedies.
- Forgetting that production differs. Check whether the positive rate in production matches the training data, and whether it drifts over time.
Summary
Class imbalance means one class is much rarer than the other. It is common wherever the interesting event is rare, such as fraud, disease, defects, and intrusions. The ratio, the absolute number of minority examples, and the cost of each error type together decide how serious it is. Imbalance does not raise errors by itself. It makes default settings and default metrics misleading, so the first steps are to count your classes and choose an evaluation that reflects your goal.
Exercise
A dataset has 2,000,000 rows with a 0.5% positive rate. A second dataset has 4,000 rows with a 0.5% positive rate. Both have the same imbalance ratio. Which one is likely harder to model, and why? Name one thing you would check before choosing a remedy.
Show answer
The 4,000-row dataset is harder. It has only about 20 positives, so the model has little to learn from and any minority-class metric will be very noisy. The 2,000,000-row dataset has about 10,000 positives, which is usually enough to learn the pattern. Before choosing a remedy, check whether the positive rate in production matches the training data, and train a plain baseline measured with a metric that fits your goal (such as recall or average precision) rather than accuracy.
Exercise
A model trained on a dataset with 3% positives rarely outputs a probability above 0.5 for any example. Give two reasons this happens, and say what it means for predicting with the default cutoff.
Show answer
First, the training loss is dominated by negative examples, so the model learns that a low probability is a good guess for most inputs. Second, positives are rare in the data, so unless the signal is strong, most inputs look more like negatives and receive low scores. With the default cutoff of 0.5, few examples are predicted positive, so recall for the minority class is low even if the model ranks positives above negatives reasonably well. Later chapters show how to adjust the cutoff or the training weights.