Sub topic 3
Choosing base learners
This chapter assumes you know k-fold cross-validation, the bias-variance trade-off, and basic scikit-learn. Earlier chapters showed that combining models helps when their errors differ. This chapter covers how to pick the models that go into the first level of a stack.
What a good base learner looks like
A base learner is a model whose predictions become inputs to the meta-learner. Each one should meet three conditions:
- It is good on its own. A model near chance level adds noise. Check each candidate's cross-validated score first.
- It makes different mistakes. Two models that err on the same rows give the meta-learner nothing new.
- It is affordable. Stacking with
cv=5fits each base model six times (five folds plus one final refit), so slow models multiply your training cost.
The second condition matters most. Adding a fourth random forest with another seed usually helps less than adding one k-nearest-neighbors model.
Mixing model families
Models differ in what they can represent, so models from different families tend to disagree in useful ways.
| Family | Typical strength | Notes |
|---|---|---|
| Linear (logistic regression) | Smooth, additive effects | Needs scaled inputs. Cheap. |
| Random forest | Interactions, noisy features | Low variance, hard to overfit. |
| Gradient boosting | Strong accuracy on tabular data | Slower. Can overfit without tuning. |
| k-nearest neighbors | Local structure | Needs scaling. Slow at prediction time. |
| Naive Bayes | Very different bias | Probabilities are often poorly calibrated. |
A practical starting set is one linear model, one bagged-tree model, one boosted-tree model, and one distance-based model. You can also vary the input. For example, one model can use all features and another can use a subset or a transformed version.
Measuring diversity
Compute out-of-fold (OOF) predictions for each candidate and look at how strongly they correlate. OOF predictions come from models that never saw the row they predict, so they show real errors. The code below needs no stacking class.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_predict, train_test_split
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),
"gb": GradientBoostingClassifier(random_state=0),
"knn": make_pipeline(StandardScaler(), KNeighborsClassifier()),
}
oof = {}
for name, model in candidates.items():
p = cross_val_predict(model, X_train, y_train, cv=5, method="predict_proba")[:, 1]
oof[name] = p
print(f"{name}: OOF accuracy {((p > 0.5) == y_train).mean():.3f}")
names = list(oof)
corr = np.corrcoef(np.column_stack([oof[n] for n in names]), rowvar=False)
print(names)
print(np.round(corr, 2))Read the correlation matrix alongside the accuracies. Two models with correlation above about 0.95 are near duplicates, so keep the cheaper one. A weaker model with low correlation to the rest can still earn its place. A strong model that mirrors another one usually cannot.
Keep the set small
More base learners mean more meta-features, and the meta-learner can overfit to them, especially on small datasets. Three to six varied models is usually enough. Add one at a time and keep it only if the stack's cross-validated score improves by more than its noise.
Exercise
Your candidate set is logistic regression, a random forest, and a second random forest with a different seed. The two forests have an OOF correlation of 0.99. What would you do, and why?
Show answer
Drop one forest. It is nearly a duplicate, so it adds fit cost and an extra meta-feature without new information. Replace it with a model from another family, such as gradient boosting or k-nearest neighbors, and check whether the OOF correlation with the others is lower.