Sub topic 12
Balanced ensembles and bagging with resampling
This chapter assumes you know scikit-learn estimators, stratified cross-validation, and why average precision suits a rare positive class. It also assumes you have read the earlier chapters on random undersampling and on keeping resampling inside the training folds.
The idea
Undersampling the majority class throws away data. A single undersampled model is also noisy, because it depends on which majority rows happened to be kept.
A balanced ensemble fixes both problems. It draws many different balanced subsets from the training data and trains one model on each. The final prediction averages the models. Each model sees a balanced problem, and across the ensemble most majority rows get used.
Three ready-made options
The imbalanced-learn library provides these classes in imblearn.ensemble.
| Class | What it does |
|---|---|
| `BalancedBaggingClassifier` | Bagging where each bootstrap sample is rebalanced before fitting. You choose the base estimator. |
| `BalancedRandomForestClassifier` | A random forest where each tree is trained on a balanced bootstrap sample. |
| `EasyEnsembleClassifier` | Boosted learners (AdaBoost by default), each trained on a different undersampled subset. |
Comparing them
The example creates the data again so it runs on its own. It scores each model with average precision on the untouched test set.
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import average_precision_score
from imblearn.ensemble import (
BalancedBaggingClassifier,
BalancedRandomForestClassifier,
EasyEnsembleClassifier,
)
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
)
models = {
"balanced bagging": BalancedBaggingClassifier(
estimator=DecisionTreeClassifier(),
n_estimators=50,
sampling_strategy="auto",
replacement=False,
random_state=42,
),
"balanced random forest": BalancedRandomForestClassifier(
n_estimators=200,
sampling_strategy="all",
replacement=True,
bootstrap=False,
random_state=42,
),
"easy ensemble": EasyEnsembleClassifier(
n_estimators=20, random_state=42
),
}
for name, model in models.items():
model.fit(X_train, y_train)
scores = model.predict_proba(X_test)[:, 1]
print(name, round(average_precision_score(y_test, scores), 3))sampling_strategy="auto" undersamples every class except the minority class down to the minority count. In BalancedRandomForestClassifier, the explicit sampling_strategy, replacement and bootstrap settings avoid default-change warnings in newer imbalanced-learn versions.
The estimator argument is named base_estimator in imbalanced-learn releases before 0.10. Use whichever name your installed version accepts.
Why the ensemble helps
- Lower variance. Averaging many models smooths out the randomness of any single undersample.
- Less information lost. Each model drops most majority rows, but different models drop different rows.
- No synthetic data. Unlike SMOTE, every training row is a real observation.
Common errors
- Resampling before splitting. The ensemble classes resample internally, so pass them the raw training data. Never undersample the data yourself first, and never evaluate on resampled data.
- Tiny minority class. If you have only a few dozen positives, each balanced subset is tiny and each model is weak. More estimators cannot fix this. Consider class weights instead.
- Judging with accuracy. Score with average precision, recall at a chosen precision, or F1 at a tuned threshold.
- Default threshold of 0.5. Balanced training moves the score distribution, so the best threshold often differs from 0.5. Tune it on out-of-fold predictions as in the threshold chapter.
When to choose an ensemble
Pick a balanced ensemble when you have plenty of majority data, because undersampling then costs little. It also fits when training time is acceptable, since you fit many models. The models are also easy to run in parallel with n_jobs. If you need well-calibrated probabilities with no extra step, or you have very little data, class weights on a single model are usually simpler.
Exercise
A teammate trains a BalancedRandomForestClassifier and reports that the model predicts a 40% fraud probability for a transaction. In production, only 2% of transactions are fraud. Why should you not read 40% as the real chance of fraud, and what would you do?
Show answer
Each tree was trained on balanced samples, so the model's scores behave as if fraud were about 50% of the data. They are inflated relative to the true 2% base rate. Use the scores for ranking, or calibrate them (for example with isotonic or sigmoid calibration fitted on held-out, non-resampled data) before treating them as probabilities.