Sub topic 7
Random oversampling and undersampling
This chapter covers the two simplest ways to rebalance a training set: duplicating minority rows (random oversampling) and discarding majority rows (random undersampling). It assumes you can fit a scikit-learn classifier, split data into train and test sets, and read precision, recall and average precision. It also assumes you have seen why accuracy misleads on rare classes. The code uses the imbalanced-learn package, installed with pip install imbalanced-learn.
The idea
A classifier trained on 95% negatives and 5% positives sees the rare class so seldom that its loss barely reflects errors on it. Resampling changes the training data so the classes are closer to equal. The model is unchanged.
- Random oversampling draws minority rows at random, with replacement, and adds the copies to the training set until the target ratio is reached.
- Random undersampling removes majority rows at random until the target ratio is reached.
Both methods act on the training set only. The test set keeps its natural class ratio, because it should show how the model behaves on real data.
Trying both on the running example
The first block builds the same kind of dataset used elsewhere in this tutorial and counts the labels after each resampler runs.
from collections import Counter
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from imblearn.over_sampling import RandomOverSampler
from imblearn.under_sampling import RandomUnderSampler
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,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
X_over, y_over = RandomOverSampler(random_state=42).fit_resample(X_train, y_train)
X_under, y_under = RandomUnderSampler(random_state=42).fit_resample(X_train, y_train)
print("original:", Counter(y_train))
print("oversampled:", Counter(y_over))
print("undersampled:", Counter(y_under))Oversampling leaves the majority count unchanged and raises the minority count to match it. Undersampling does the reverse, so the training set shrinks to roughly twice the number of minority rows. Every resampler in imbalanced-learn exposes fit_resample(X, y), which returns the new X and y.
Next, train the same model on each version and score it on the untouched test set.
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, precision_score, recall_score
def evaluate(name, X_fit, y_fit):
clf = LogisticRegression(max_iter=1000).fit(X_fit, y_fit)
pred = clf.predict(X_test)
scores = clf.predict_proba(X_test)[:, 1]
print(
f"{name:<12}"
f"precision={precision_score(y_test, pred, zero_division=0):.3f} "
f"recall={recall_score(y_test, pred):.3f} "
f"AP={average_precision_score(y_test, scores):.3f}"
)
evaluate("original", X_train, y_train)
evaluate("oversampled", X_over, y_over)
evaluate("undersampled", X_under, y_under)Expect a pattern like this, though exact numbers depend on your library versions:
- Recall rises for both resampled models, because the model now predicts the positive class more readily.
- Precision falls, because the model flags more negatives as positive.
- Average precision, which scores the ranking of examples rather than one cutoff, changes much less than precision and recall do.
That last point matters. Resampling mostly moves the decision boundary toward the majority class. It does not always make the model rank examples better. If average precision barely changes, a threshold shift on the original model may give you the same trade-off, as the threshold chapter shows.
Controlling the target ratio
By default, resamplers aim for a 1:1 ratio. Full balance is often more than you need. The sampling_strategy argument controls the target.
| Value | Meaning | Example |
|---|---|---|
| `"auto"` | Balance all classes (default) | Minority raised to the majority count when oversampling |
| float, such as `0.5` | Final minority/majority ratio, binary problems only | 1 positive for every 2 negatives |
| dict, such as `{1: 2000}` | Exact target count per class | Oversampling: 2000 positives. Undersampling: keep 2000 of that class |
| `"minority"`, `"majority"` | Resample only that class | Oversample just the rare class |
A partial ratio is a good first experiment:
ros = RandomOverSampler(sampling_strategy=0.25, random_state=42)
X_part, y_part = ros.fit_resample(X_train, y_train)
print(Counter(y_part))With 0.25, the minority class ends at one quarter of the majority count. This changes the data less than full balance, so it usually overfits less than full oversampling and discards less than full undersampling.
For dictionaries, the meaning depends on the sampler. A dictionary given to an oversampler must ask for at least the current count of each class. A dictionary given to an undersampler must ask for at most the current count. Otherwise imbalanced-learn raises a ValueError.
What each method costs
Oversampling: duplicates and overfitting
Copies add no new information. They only repeat existing rows, so the model gives those rows more weight. Flexible models can then memorize them.
- A deep decision tree can carve out a tiny region around each duplicated positive and score perfectly on the training set.
- A k-nearest-neighbors model sees the copies as a dense cluster of positives and becomes overconfident near them.
- Training takes longer, because the data set grows to about twice the majority count.
You can limit overfitting in three ways:
- Use a partial ratio, as shown above, rather than full balance.
- Regularize the model, for example with a larger
min_samples_leaffor trees or a smallerCfor logistic regression. - Use the
shrinkageparameter ofRandomOverSampler. It performs a smoothed bootstrap, which adds small Gaussian noise to each copy so the copies are no longer identical. It works on numeric features only.
ros_smooth = RandomOverSampler(shrinkage=0.2, random_state=42)
X_smooth, y_smooth = ros_smooth.fit_resample(X_train, y_train)
print(Counter(y_smooth))The shrinkage value scales the noise relative to the feature spread. Larger values give more jitter. This is a step toward the synthetic samples that SMOTE creates in the next chapter.
Undersampling: lost information
Undersampling throws away real data. With 7,500 training rows and about 5% positives, you keep only a few hundred rows and discard thousands of majority examples. The benefits are speed and a smaller memory footprint. The costs are:
- The model sees fewer majority patterns, so it may misjudge regions of feature space where only majority points were dropped.
- The result depends heavily on which rows were drawn. Two random seeds can give noticeably different models.
- With few minority rows in total, the training set may become too small to fit anything stable.
Undersampling suits large datasets where the minority class still has thousands of rows. It fits poorly when the minority class has only dozens.
The variance from random selection can be reduced by averaging many undersampled models. That is the idea behind balanced bagging, covered in the ensembles chapter.
Practical details and edge cases
- Only the training data is resampled. If you resample before splitting, duplicated minority rows can land in both the training and test sets. The test score then rewards memorization and overstates performance. Split first with stratification, then resample the training portion.
- Cross-validation needs care. Resampling the full training set and then running
cross_val_scorehas the same problem. Copies of a row sit in both the fitting and validation folds. The fix is to put the resampler in animblearnpipeline, so it runs inside each fold. The pipeline chapter covers this in detail. - Sample indices. After
fit_resample, the attributesample_indices_on the sampler holds the row positions that were selected from the input. This helps you check which original rows were kept or duplicated. - Non-numeric data. Random resamplers only copy or drop rows, so they work with categorical and text columns, and with inputs that are not NumPy arrays. Only the
shrinkageoption requires numeric features. - Probabilities shift. After training on a balanced set, predicted probabilities no longer match real-world frequencies. A model trained at 50/50 will output higher probabilities for the positive class than the true rate justifies. Use the scores for ranking and thresholding, and check calibration before treating them as probabilities.
- Multi-class problems. The
"auto"strategy balances every class. The float ratio is binary only, so use a dictionary when you have more than two classes.
Oversampling, undersampling, or neither
| Situation | Leaning |
|---|---|
| Large dataset, minority class has thousands of rows | Undersampling is cheap and often enough |
| Small dataset, minority class has dozens to hundreds of rows | Oversampling, ideally with a partial ratio or shrinkage |
| Model is a deep tree or nearest-neighbors | Be wary of plain oversampling because of memorization |
| Training time is a bottleneck | Undersampling |
| You only need a different precision/recall trade-off | Try threshold tuning or class weights first |
Class weights, covered earlier, produce an effect similar to oversampling without making copies. Many estimators accept class_weight, and it costs no extra memory. Resampling remains useful for estimators that have no weighting option, and for cases where you want to cut training time.
A reasonable workflow is to establish a baseline with no rebalancing, then try class weights, then try resampling with a pipeline. Compare all of them on the same stratified cross-validation folds using average precision or another metric that suits the rare class.
Exercise
You oversample the whole dataset to a 1:1 ratio with RandomOverSampler, then split it into train and test sets and report recall of 0.97 on the test set. Why is this number unreliable, and what should you change?
Show answer
Oversampling before the split puts identical copies of the same minority rows in both the training and test sets, so the model is tested on rows it has already memorized. The recall is inflated. Split first with stratification, then resample only the training set, and evaluate on a test set that keeps the original class ratio.
Exercise
A fraud dataset has 2,000,000 transactions and 400 frauds. A colleague suggests random undersampling to 1:1. What is the main risk, and what alternative would you try first?
Show answer
A 1:1 undersample keeps only about 800 rows, so the model loses almost all information about legitimate transactions and the result depends strongly on which 400 were drawn. Try class weights or a partial undersampling ratio (for example keeping tens of thousands of majority rows), or average several undersampled models, and compare with average precision on stratified folds.
Exercise
After fitting a logistic regression on a 1:1 oversampled training set, the predicted positive probabilities on real data are much higher than the true fraud rate. Is this a bug?
Show answer
No. Training on a balanced set changes the prior the model learns, so its probabilities are shifted upward relative to the real class frequencies. The ranking of examples can still be good. Choose a threshold using out-of-fold predictions, and calibrate the probabilities if you need them to be accurate.