Sub topic 3
Choosing base learners
This chapter assumes you know supervised learning basics, k-fold cross-validation, and the idea of a meta-learner that trains on base-model predictions. The previous chapter explained why diversity matters. This one covers how to pick a set of base learners in practice and how to check that your choices help.
What a base learner has to do
A base learner is any model whose predictions feed the meta-learner. A good one meets two conditions:
- It is individually competent. A model near chance level adds noise to the meta-features. The meta-learner can learn to ignore it, but only by spending some of your limited training signal.
- It makes different mistakes from the other base learners. If two models are wrong on the same rows, the second adds almost nothing.
You rarely get both from a single pick. Strong models tend to resemble each other, and very different models are often weaker. The goal is a small set that balances the two.
Pick from different model families
Models from the same family tend to err in similar ways, because they share assumptions about the data. Models from different families err differently. A starting menu:
| Family | Example | Strength | Needs scaling | Cost |
|---|---|---|---|---|
| Linear | `LogisticRegression` | Smooth, global trends; hard to overfit | Yes | Low |
| Bagged trees | `RandomForestClassifier` | Interactions, noisy features | No | Medium |
| Boosted trees | `GradientBoostingClassifier` | Strong tabular accuracy | No | Medium to high |
| Distance-based | `KNeighborsClassifier` | Local structure | Yes | Cheap to fit, slower to predict |
| Probabilistic | `GaussianNB` | Very different bias; fast | No | Low |
Two practical consequences follow.
First, wrap models that need scaling in a pipeline, as in the chapter's earlier StandardScaler plus k-nearest-neighbors example. Inside a pipeline, the scaler is refit within every cross-validation fold, so no fold's statistics leak into another.
Second, several random forests with different seeds do not make a diverse set. Neither do a random forest and an extra-trees model, which are close relatives. Two gradient boosting libraries with similar settings also overlap heavily. Varying hyperparameters inside one family gives much less diversity than switching families.
Measure diversity instead of guessing
You can check how much two models overlap by comparing their out-of-fold predictions. Low correlation between two models, combined with similar individual scores, suggests the pair is worth combining.
The code below computes out-of-fold probabilities for five candidates, prints each one's log loss, and prints their correlation matrix. It runs as written.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import ExtraTreesClassifier, GradientBoostingClassifier, RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss
from sklearn.model_selection import cross_val_predict, train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = make_classification(n_samples=2000, n_features=20, n_informative=8, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)
candidates = {
"logreg": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
"rf": RandomForestClassifier(n_estimators=200, random_state=0),
"et": ExtraTreesClassifier(n_estimators=200, random_state=0),
"gb": GradientBoostingClassifier(random_state=0),
"knn": make_pipeline(StandardScaler(), KNeighborsClassifier()),
"nb": GaussianNB(),
}
oof = {}
for name, model in candidates.items():
probs = cross_val_predict(model, X_train, y_train, cv=5, method="predict_proba")[:, 1]
oof[name] = probs
print(f"{name:7s} log loss: {log_loss(y_train, probs):.3f}")
names = list(oof)
corr = np.corrcoef(np.column_stack([oof[n] for n in names]), rowvar=False)
print("\n " + " ".join(f"{n:>6s}" for n in names))
for n, row in zip(names, corr):
print(f"{n:7s} " + " ".join(f"{v:6.2f}" for v in row))Expect rf and et to show a correlation close to 1, and nb or logreg to correlate less with the tree models. The exact numbers depend on your data. Only the pattern matters.
Correlation of probabilities is a rough proxy. A pair with a correlation of 0.95 can still help if the disagreements fall on the hard rows. Treat the matrix as a way to spot obvious duplicates, not as a precise score.
Select a subset greedily
With a candidate pool, you can add models one at a time. At each step, add the model that most improves the meta-learner's cross-validated score, and stop when nothing improves it. This continues from the previous snippet.
from sklearn.model_selection import cross_val_score
selected, best = [], -np.inf
while True:
scores = {}
for n in names:
if n in selected:
continue
cols = np.column_stack([oof[k] for k in selected + [n]])
scores[n] = cross_val_score(
LogisticRegression(max_iter=1000), cols, y_train,
cv=5, scoring="neg_log_loss",
).mean()
if not scores:
break
pick = max(scores, key=scores.get)
if scores[pick] <= best + 1e-4:
break
selected.append(pick)
best = scores[pick]
print(f"added {pick:7s} meta log loss: {-best:.4f}")
print("selected:", selected)Two limits apply. The out-of-fold predictions were produced by models that saw the same training rows, so the meta-scores are slightly optimistic, and the more candidates you try, the more optimism you collect. Also, the selection must use only training data. If you choose base learners by looking at test-set scores, the test set is no longer an honest estimate. Chapter on evaluation covers this in detail.
Tune base learners for the ensemble
Base learners do not need to be tuned to their individual best. Some guidance:
- Moderate tuning is enough. The meta-learner corrects biases, so a base model that is slightly off can still contribute. Spending hours on one base model's hyperparameters usually helps less than adding a different family.
- Mild overfitting is acceptable. Deep trees or a small
n_neighborsgive low-bias, high-variance models. The meta-learner averages across models, so some of that variance cancels. Do not take this far, because out-of-fold predictions from a heavily overfit model are noisy. - Make model types differ on purpose. Give a boosted model shallow trees and a random forest deep ones, or give a k-nearest-neighbors model a different feature scaling. These choices push errors apart.
- Feature views can add diversity. Training a base learner on a subset of features, or on engineered features such as log transforms, changes what it can see. This works well when the subsets are meaningful, such as one model on text-derived features and another on numeric columns.
Watch the cost
Stacking with cv=5 fits every base learner five times for the out-of-fold step, then once more on the full training set. Six base learners means 36 fits. Prediction cost grows with each model too, and k-nearest-neighbors is the slowest to predict because it searches stored training rows.
A common working size is 3 to 6 base learners. Past that, gains are usually small, because new candidates tend to resemble models already in the set.
Common mistakes
- Using only tree ensembles. Random forest, extra trees, and boosted trees together give three correlated models. Include at least one non-tree model.
- Forgetting scaling for linear and distance models. Without scaling, k-nearest-neighbors is dominated by whichever feature has the largest range.
- Including a base learner with its own leakage. If a base model uses target encoding fit outside the cross-validation loop, its out-of-fold predictions are contaminated. Keep preprocessing inside the pipeline.
- Choosing models by test score. Select on out-of-fold training predictions and touch the test set once.
- Ignoring calibration. Probabilities from
GaussianNBand from random forests have different shapes. A logistic-regression meta-learner can partly fix this, but if you mix very differently calibrated outputs, check the result rather than assuming it works.
Exercise
You have a random forest, an extra-trees model, and a gradient boosting model, and their out-of-fold probabilities correlate above 0.95. Adding a scaled logistic regression only brings the ensemble from 0.904 to 0.906 accuracy. Which change would you try first to increase diversity, and how would you decide whether to keep the new model?
Show answer
Replace one of the near-duplicate tree models, for example extra trees, with a model from a different family such as k-nearest-neighbors in a scaling pipeline or naive Bayes. Compute its out-of-fold predictions on the training data and check that it is individually competent and less correlated with the others. Keep it only if the meta-learner's cross-validated score on the training data improves by more than noise, for example in the greedy selection loop. Do not use the test set to decide.