Sub topic 12
Balanced ensembles and bagging with resampling
This chapter assumes you know how to fit scikit-learn estimators, how decision trees and random forests work at a high level, and how to read precision, recall and average precision. It also assumes you have seen class weights and random undersampling earlier in this tutorial. Here we combine those ideas. Instead of resampling once and training one model, you resample many times and train many models.
The problem with one undersampled model
Random undersampling fixes imbalance by dropping majority rows until the classes match. With 7,500 training rows and about 5% positives, that leaves roughly 375 positives and 375 negatives. The model trains fast and sees a balanced problem. The cost is that it throws away about 6,750 negatives, so it may never see the part of the majority class that looks most like the rare class.
Random oversampling has the opposite flaw. It keeps every row, but it repeats the minority rows, so a flexible model such as a deep tree memorizes those exact points.
A balanced ensemble avoids both problems. Each member trains on a different balanced subset. A single member sees little of the majority class, but across many members most majority rows get used. Averaging many high-variance models also reduces variance, which is the usual argument for bagging.
How balanced bagging works
Standard bagging draws a bootstrap sample of the whole dataset for each model. Balanced bagging draws the sample class by class. All minority rows, or a bootstrap of them, go into every bag. The majority rows are undersampled to match.
The mechanism is short enough to write by hand. This code uses undersampled bags of decision trees and compares one bag with 25 bags.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.metrics import average_precision_score
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
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
)
def fit_balanced_bags(X, y, n_bags, seed):
rng = np.random.default_rng(seed)
pos = np.flatnonzero(y == 1)
neg = np.flatnonzero(y == 0)
models = []
for _ in range(n_bags):
neg_sample = rng.choice(neg, size=len(pos), replace=False)
idx = np.concatenate([pos, neg_sample])
tree = DecisionTreeClassifier(
min_samples_leaf=3, random_state=int(rng.integers(1_000_000))
)
models.append(tree.fit(X[idx], y[idx]))
return models
def predict_bags(models, X):
return np.mean([m.predict_proba(X)[:, 1] for m in models], axis=0)
for n_bags in (1, 25):
models = fit_balanced_bags(X_train, y_train, n_bags, seed=0)
scores = predict_bags(models, X_test)
print(n_bags, "bags, average precision:", round(average_precision_score(y_test, scores), 3))Expect the 25-bag score to be clearly higher than the single-bag score. The single tree is noisy because it saw only a small slice of the majority class. Averaging smooths the noise and covers more of the majority rows.
Ready-made ensembles in imbalanced-learn
The imbalanced-learn package (imported as imblearn) provides these methods in imblearn.ensemble.
| Class | What each member trains on | Aggregation |
|---|---|---|
| `BalancedBaggingClassifier` | A balanced bootstrap, with any base estimator you choose | Averages probabilities or votes |
| `BalancedRandomForestClassifier` | A balanced bootstrap per tree, plus random feature subsets | Averages tree probabilities |
| `EasyEnsembleClassifier` | A balanced undersample per member, where each member is an AdaBoost model | Averages the AdaBoost outputs |
| `RUSBoostClassifier` | A fresh random undersample at every boosting round | Weighted boosting vote |
The first three are bagging-style. Their members are independent, so they parallelize and mostly reduce variance. RUSBoostClassifier is boosting-style. Its members are sequential, and it mostly reduces bias, so it can fit harder patterns but is more sensitive to label noise.
The next block compares them with stratified cross-validation on the training set only. It continues from the previous block's X_train and y_train.
from imblearn.ensemble import (
BalancedBaggingClassifier,
BalancedRandomForestClassifier,
EasyEnsembleClassifier,
RUSBoostClassifier,
)
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.tree import DecisionTreeClassifier
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
candidates = {
"forest, class_weight": RandomForestClassifier(
n_estimators=200, class_weight="balanced_subsample",
min_samples_leaf=3, n_jobs=-1, random_state=42,
),
"balanced bagging (trees)": BalancedBaggingClassifier(
estimator=DecisionTreeClassifier(min_samples_leaf=3),
n_estimators=50, sampling_strategy="auto", replacement=False,
n_jobs=-1, random_state=42,
),
"balanced random forest": BalancedRandomForestClassifier(
n_estimators=200, sampling_strategy="auto", replacement=True,
n_jobs=-1, random_state=42,
),
"easy ensemble": EasyEnsembleClassifier(
n_estimators=10, random_state=42, n_jobs=-1,
),
"RUSBoost": RUSBoostClassifier(n_estimators=100, random_state=42),
}
for name, est in candidates.items():
s = cross_val_score(est, X_train, y_train, cv=cv, scoring="average_precision")
print(f"{name:28s} {s.mean():.3f} +/- {s.std():.3f}")A few notes on the arguments:
sampling_strategy="auto"undersamples every class except the minority to the minority's size. You can pass a float, such as0.5, to keep the majority at twice the minority count. A fully balanced bag is not always best. A milder ratio keeps more majority information in each member.- The base-learner argument is named
estimatorin current releases andbase_estimatorin older ones. If you get aTypeError, check your installed version. - The defaults for
BalancedRandomForestClassifier(replacement,bootstrap,sampling_strategy) have changed between releases. Set them explicitly, as above, so results do not shift when you upgrade. - Include
RandomForestClassifier(class_weight="balanced_subsample")as a baseline. It is the cheapest option and often competitive. The class weights are recomputed inside each bootstrap sample, which is whybalanced_subsampleis usually preferred overbalancedfor forests.
Choosing between the variants
Use these rules as a starting point, and confirm them with cross-validated average precision on your data.
- Data size. Undersampling-based ensembles cost little when the minority class is small, since each member trains on a few hundred to a few thousand rows. They are attractive when the majority has millions of rows. With a tiny minority (say, 30 positives), every bag is tiny, and the members will be high-variance and strongly correlated through the shared positives.
- Base learner. Bagging helps unstable learners such as deep trees. It does little for stable ones such as logistic regression, where class weights usually give the same result for less work.
- Noise. If labels in the minority class are noisy, boosting methods like
RUSBoostClassifiercan chase the noisy rows. Prefer bagging-style methods. - Cost of positives in each bag. Every bag contains the same minority rows (unless you bootstrap them). Minority outliers therefore influence every member. Setting
replacement=Trueon the minority bootstrap adds some diversity.
Failure modes and gotchas
Inflated probabilities. Each member trains on a 50/50 problem, so its output behaves as if the positive rate were 50%. The averaged score may be around 0.5 for rows where the true risk is 5%. You can see the shift directly. This continues from the previous block.
brf = BalancedRandomForestClassifier(
n_estimators=200, sampling_strategy="auto", replacement=True,
n_jobs=-1, random_state=42,
).fit(X_train, y_train)
scores = brf.predict_proba(X_test)[:, 1]
print("true positive rate in test:", y_test.mean())
print("mean predicted probability:", scores.mean())
print("share predicted positive at 0.5:", (scores >= 0.5).mean())The mean predicted probability will sit well above the true rate, and far more rows will cross 0.5 than are actually positive. The ranking can still be excellent, so average precision is unaffected. What breaks is the interpretation of the numbers as risks, and the default 0.5 threshold, which will give many false positives.
Two fixes are available. If you only need decisions, tune the threshold on out-of-fold predictions as shown in the threshold chapter. If you need real probabilities, wrap the ensemble in CalibratedClassifierCV fitted on data with the natural class ratio. Both fixes need data that was not used to train the members, so keep the calibration split stratified and separate.
Too few bags. With 5 or 10 members, results can change noticeably between random seeds. Increase n_estimators until cross-validated scores stop moving, and report the standard deviation across folds, as the earlier comparison does.
Out-of-bag scores. oob_score options in these classes are computed on rows left out of each member's bag. For undersampling methods, the left-out majority rows are most of the data, and their distribution differs from a balanced test. Treat these scores with caution, and prefer stratified cross-validation with a metric such as average precision.
Comparing against a tuned baseline. A balanced ensemble should beat a plain forest tuned on the same metric before you adopt it. If it does not, the added complexity buys you nothing.
Compute and memory. Bagging fits many models. Use n_jobs=-1, and note that predict_proba on 200 deep trees is slower than on one logistic regression. This matters for latency-sensitive scoring.
Putting it together
A practical workflow looks like this:
- Split with stratification and hold out the test set.
- Run cross-validation on the training set, scoring with average precision. Compare a class-weighted forest, a balanced random forest and balanced bagging with your preferred base learner.
- Tune only a few parameters. The most useful are
n_estimators,min_samples_leafandsampling_strategy. - Pick the threshold from out-of-fold predictions, or calibrate if you need probabilities.
- Evaluate once on the test set.
Exercise
A balanced random forest scores a mean predicted probability of 0.42 on a test set where 4% of rows are positive. Its average precision is high. Is the model broken, and what would you do before using a 0.5 threshold?
Show answer
The model is not broken. Each tree trained on a roughly 50/50 balanced bag, so the averaged scores are shifted upward and are not true risks. Ranking quality, which average precision measures, is unaffected. Before using a threshold, choose it from out-of-fold predictions on the training data (for example, the F1-maximizing threshold or one that meets a precision target). If you need real probabilities, calibrate the ensemble with CalibratedClassifierCV on stratified data that keeps the natural class ratio.
Exercise
You have 40 positives and 200,000 negatives. Why might balanced bagging with undersampling still perform poorly, and which alternative from earlier chapters would you compare it against?
Show answer
Each bag would contain only 40 positives plus 40 negatives, so every member trains on about 80 rows and the members are highly correlated through the shared positives. The ensemble reduces variance from the majority sampling but cannot add information about the minority class. Compare it against a class-weighted linear model or a regularized model trained on all rows, and consider a milder sampling_strategy so each bag keeps more negatives.