Sub topic 12
Choosing and regularizing the meta-learner
This chapter assumes you can build a StackingClassifier, you know why the meta-learner trains on out-of-fold predictions, and you are comfortable with L2 regularization and cross-validation in scikit-learn.
Why the meta-learner should be simple
The meta-learner sees only a few columns, usually one per base model. Those columns are highly correlated, because every base model is trying to predict the same target. A flexible meta-learner can overfit the small differences between them. A simple one learns how much to trust each base model, and that is usually all you need.
The out-of-fold predictions are also slightly noisier than the predictions the base models make at test time. Those models are refit on all the training data, so they are a little stronger. A model that fits the meta-features too closely will not carry over cleanly.
Sensible defaults
| Task | Default meta-learner | Why |
|---|---|---|
| Classification | `LogisticRegression` with L2 | Calibrated output, few parameters |
| Regression | `Ridge` or `RidgeCV` | Handles correlated inputs |
| Weights must be non-negative | `LinearRegression(positive=True)` or `Ridge(positive=True)` | Gives a weighted average of the base models |
Non-negative weights are worth considering when your base models are all decent. A negative weight on one model often means the meta-learner is fitting noise rather than the signal.
Regularization strength
The inverse regularization strength C in LogisticRegression controls how far the weights can move. A small C pulls the weights toward equal, small values. A large C lets one strong model dominate. Select it by cross-validation on the training set, not on the test set.
from sklearn.datasets import make_classification
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier, StackingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score, 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=1500, 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)
base = [
("rf", RandomForestClassifier(n_estimators=100, random_state=0)),
("gb", GradientBoostingClassifier(random_state=0)),
("knn", make_pipeline(StandardScaler(), KNeighborsClassifier())),
]
best_C, best_score = None, -1.0
for C in [0.01, 0.1, 1.0, 10.0]:
stack = StackingClassifier(
estimators=base,
final_estimator=LogisticRegression(C=C, max_iter=1000),
cv=5,
stack_method="predict_proba",
)
score = cross_val_score(stack, X_train, y_train, cv=3).mean()
print(f"C={C}: cv accuracy {score:.3f}")
if score > best_score:
best_C, best_score = C, score
final = StackingClassifier(
estimators=base,
final_estimator=LogisticRegression(C=best_C, max_iter=1000),
cv=5,
stack_method="predict_proba",
).fit(X_train, y_train)
print("chosen C:", best_C, "test accuracy:", final.score(X_test, y_test))For a binary problem, scikit-learn keeps only the class-1 probability from each model. The meta-learner here therefore sees three columns. With k classes it would see k - 1 columns per model.
Look at final.final_estimator_.coef_ to see how much weight each base model gets. If one weight dominates, the ensemble is close to that single model, and the others add cost without much benefit.
When a nonlinear meta-learner is justified
A small gradient boosting model or random forest can help in two cases:
- You pass the raw features through alongside the predictions (
passthrough=True), and the meta-learner needs to learn where each base model is reliable. - You have a large training set, so the meta-learner has enough rows to learn interactions.
If you use one, keep it shallow and strongly constrained, and compare it against the logistic regression on the same cross-validation splits.
Exercise
A stacked ensemble with a gradient boosting meta-learner scores 0.97 in cross-validation. A logistic regression meta-learner on the same base models and splits scores 0.96. What would you check before choosing the boosting model?
Show answer
Check whether the 0.01 gain is larger than the fold-to-fold variation, using the standard deviation across folds. Then compare the cost and the risk of overfitting. The boosting meta-learner has many more parameters but only a few correlated columns to learn from. If the gain is within the noise, keep the logistic regression. It is cheaper, easier to inspect through its coefficients, and less likely to overfit.