Sub topic 7
Random oversampling and undersampling
This chapter assumes you know scikit-learn estimators, stratified splits, and the metrics from earlier chapters: precision, recall, and average precision. It also assumes the imbalanced-learn package is installed (pip install imbalanced-learn).
The idea
Class weights change how much each error costs. Resampling changes the data itself so the classes look more balanced to the model.
- Random oversampling copies minority rows, chosen at random with replacement, until the classes reach a target ratio.
- Random undersampling deletes majority rows, chosen at random, until the classes reach a target ratio.
Both are simple and work with any estimator, including those that do not accept class weights.
Trying both
The example below builds an imbalanced dataset, resamples only the training split, and compares both methods against no resampling. Each model is scored on the untouched test split.
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, recall_score, precision_score
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
)
samplers = {
"none": None,
"oversample": RandomOverSampler(random_state=42),
"undersample": RandomUnderSampler(random_state=42),
}
for name, sampler in samplers.items():
if sampler is None:
X_res, y_res = X_train, y_train
else:
X_res, y_res = sampler.fit_resample(X_train, y_train)
model = LogisticRegression(max_iter=1000).fit(X_res, y_res)
pred = model.predict(X_test)
scores = model.predict_proba(X_test)[:, 1]
print(
f"{name:12s} train size={len(y_res):5d} "
f"precision={precision_score(y_test, pred):.3f} "
f"recall={recall_score(y_test, pred):.3f} "
f"AP={average_precision_score(y_test, scores):.3f}"
)You should see recall rise and precision fall for both resampled models compared with no resampling. The exact numbers depend on your library versions. Average precision usually changes much less, because resampling mostly shifts where the default 0.5 cutoff falls rather than how well the model ranks cases.
Trade-offs
| Method | Benefit | Risk |
|---|---|---|
| Oversampling | Keeps all majority information | Exact duplicates encourage overfitting. Training takes longer. |
| Undersampling | Fast training, small data | Throws away real majority examples. Higher variance. |
Oversampling can overfit because the model sees the same minority points many times. Tree models with deep splits can memorize them. Undersampling matters most when the majority class is large, for example millions of rows, because discarding most of it costs little information.
You do not need a perfect 1:1 ratio. The sampling_strategy argument sets the target. A float is the desired minority-to-majority ratio after resampling:
from imblearn.under_sampling import RandomUnderSampler
# Keep minority/majority at 0.25, so the majority is cut to 4x the minority.
sampler = RandomUnderSampler(sampling_strategy=0.25, random_state=42)
X_res, y_res = sampler.fit_resample(X_train, y_train)
print(y_res.mean())A partial rebalance often gives a better precision and recall balance than a full one.
Side effects to expect
- Shifted probabilities. After resampling, the model sees a minority rate of 50% or 25% instead of 5%. Its predicted probabilities then overstate the real risk. Do not read them as true probabilities without calibration.
- Evaluate on the original distribution. Keep the test set at its natural class ratio. Otherwise precision looks better than it will be in production.
- Set a seed. Both samplers are random. Use
random_stateso results can be reproduced.
Exercise
You undersample the majority class to a 1:1 ratio and train a model. On the untouched test set, recall improves but precision drops sharply. Give one reason this happens and one change you could try.
Show answer
The model now sees the minority class at 50% prevalence, so it flags many more cases as positive. On the real test set, where positives are rare, many of those flags are false positives, which lowers precision. Options include using a partial ratio such as sampling_strategy=0.25, raising the decision threshold, or switching to oversampling so less majority data is lost.