Sub topic 12
Choosing and regularizing the meta-learner
This chapter assumes you can build an out-of-fold (OOF) stack with StackingClassifier or by hand. It also assumes you know what L1 and L2 regularization do. The earlier chapters covered how meta-features are produced. This one covers the model that consumes them.
Why the meta-learner should usually be simple
The meta-learner trains on a small, unusual table. Each column is a prediction from a base model, so there are usually 3 to 10 columns. Those columns are strongly correlated, because every base model is trying to predict the same target. The OOF values are also noisy, since each came from a model that never saw that row.
A flexible meta-learner such as a deep gradient-boosted ensemble has little to learn here. It can fit the noise in the OOF predictions. It can also learn a fragile rule such as "trust the random forest only when the k-nearest-neighbors output is above 0.63". A regularized linear model avoids both problems. In effect it learns a weighted average of the base models, which is almost all the signal in these columns.
The usual order of preference is:
| Meta-learner | Use when | Main risk |
|---|---|---|
| Logistic regression (L2) | Default for classification | Collinear inputs make coefficients unstable if `C` is large |
| Ridge, optionally with non-negative weights | Default for regression | Needs scaled targets only if you compare alphas across tasks |
| L1 or elastic-net regularized linear model | Many base models, and you want some dropped | Picks arbitrarily among near-duplicate models |
| Shallow tree or small gradient-boosted model | You pass raw features through, or base models have regime-dependent strengths | Overfits the OOF noise, harder to interpret |
| Plain average (no meta-learner) | Very small data or very similar models | Cannot down-weight a weak model |
A plain average is a real baseline, not a strawman. If a fitted meta-learner does not beat the average of your base models in cross-validation, use the average.
Regularization strength
For LogisticRegression, the parameter C is the inverse of regularization strength. A small C pulls the coefficients toward zero and toward each other, so the meta-learner behaves more like an average. A large C lets it chase small differences between correlated models.
You can tune C cheaply because the OOF matrix only needs to be computed once. This example computes it, then compares several values with cross-validation on that matrix.
import numpy as np
from sklearn.base import clone
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, 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=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)
base = [
("rf", RandomForestClassifier(n_estimators=200, random_state=0)),
("gb", GradientBoostingClassifier(random_state=0)),
("knn", make_pipeline(StandardScaler(), KNeighborsClassifier())),
]
oof = np.column_stack([
cross_val_predict(clone(m), X_train, y_train, cv=5, method="predict_proba")[:, 1]
for _, m in base
])
for C in [0.01, 0.1, 1, 10, 100]:
meta = LogisticRegression(C=C, max_iter=1000)
score = cross_val_score(meta, oof, y_train, cv=5).mean()
print(f"C={C:<6} meta-CV accuracy: {score:.3f}")
average = ((oof.mean(axis=1) > 0.5).astype(int) == y_train).mean()
print(f"plain average accuracy on OOF: {average:.3f}")Expect the scores to be close to each other. If they are, the choice of C does not matter much and you should prefer the more regularized option.
Letting scikit-learn choose
You can pass a cross-validated meta-learner as final_estimator. LogisticRegressionCV picks C internally using only the OOF matrix, so the base models are not refit during the search.
from sklearn.ensemble import StackingClassifier
from sklearn.linear_model import LogisticRegressionCV
stack = StackingClassifier(
estimators=base,
final_estimator=LogisticRegressionCV(Cs=[0.01, 0.1, 1, 10], cv=5, max_iter=1000),
cv=5,
stack_method="predict_proba",
)
stack.fit(X_train, y_train)
meta = stack.final_estimator_
print("chosen C:", meta.C_)
print("coefficients (rf, gb, knn):", meta.coef_.round(2))
print("test accuracy:", round(stack.score(X_test, y_test), 3))For binary problems, StackingClassifier with predict_proba passes only the positive-class column from each model, because the two columns sum to 1 and the second adds nothing. That is why there are three coefficients for three models. For multiclass problems, each model contributes one column per class, minus the redundancy.
Reading the coefficients
The coefficients show how much each base model contributes. Large positive values on two correlated models, with a negative value on a third, are a warning sign. The meta-learner is using small differences between near-duplicates, and the weights probably will not generalize. Stronger regularization usually removes this pattern.
Interpretation only works if the inputs are on a comparable scale. Probabilities already are. Raw margins or regression predictions from models with different units are not, so scale them before comparing coefficients.
Constraining the weights in regression
For regression, a useful constraint is to require non-negative weights. A negative weight on a model that predicts the target is rarely meaningful and usually signals collinearity. Ridge supports this with positive=True.
from sklearn.datasets import make_regression
from sklearn.ensemble import RandomForestRegressor, StackingRegressor
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsRegressor
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
Xr, yr = make_regression(n_samples=1500, n_features=15, n_informative=6, noise=20, random_state=0)
Xr_train, Xr_test, yr_train, yr_test = train_test_split(Xr, yr, test_size=0.25, random_state=0)
reg = StackingRegressor(
estimators=[
("rf", RandomForestRegressor(n_estimators=100, random_state=0)),
("knn", make_pipeline(StandardScaler(), KNeighborsRegressor())),
("ridge", make_pipeline(StandardScaler(), Ridge())),
],
final_estimator=Ridge(alpha=1.0, positive=True),
cv=5,
)
reg.fit(Xr_train, yr_train)
print("weights (rf, knn, ridge):", reg.final_estimator_.coef_.round(2))
print("test R^2:", round(reg.score(Xr_test, yr_test), 3))Non-negative weights that sum to roughly 1 make the stack behave like a weighted average. With positive=True the intercept still absorbs any constant bias in the base models.
LogisticRegression has no equivalent non-negativity option. If you need it for classification, a common workaround is to stack on regression-style scores with a constrained least-squares model, or simply to inspect the coefficients and drop models that get negative weights.
Choosing: a short decision path
Common mistakes
- Using a high-capacity meta-learner by default. A random forest on four probability columns mostly relearns the average and adds variance.
- Tuning on the test set. Selecting
Cor the meta-learner type by looking at test accuracy turns the test set into a validation set. - Fitting the meta-learner on in-sample predictions. This is the leakage problem from earlier chapters. The meta-learner will give nearly all the weight to whichever model overfits the training data most.
- Comparing coefficients without checking scale or collinearity. A coefficient of 2.1 on one model and 0.4 on another does not mean the first is five times more useful.
- Skipping the average baseline. Without it you cannot tell whether the meta-learner earns its extra complexity.
Exercise
You stack four base models whose OOF probabilities are highly correlated. A logistic-regression meta-learner with C=100 gives coefficients of +4.8, -3.9, +5.1 and -4.5, and its cross-validated accuracy is 0.002 above the plain average. What does this suggest, and what do you change?
Show answer
The meta-learner is exploiting small differences between near-duplicate models. Large coefficients of opposite sign on correlated inputs are unstable and unlikely to generalize, and the tiny gain over the average does not justify them. Lower C (for example 0.01 to 0.1) or use LogisticRegressionCV so the regularization is chosen from the OOF data, then compare again with the plain average. If the gain stays negligible, use the average, or drop some of the near-duplicate base models.