Sub topic 4
The meta-learner: a model that learns from models
This chapter assumes you know supervised classification and regression, k-fold cross-validation, and the basics of overfitting. It also assumes you can read scikit-learn code. Leakage, out-of-fold predictions, and the choice of meta-learner each get their own chapter. Here they appear only where they are needed to explain what the meta-learner is.
What the meta-learner is
A stacking ensemble has two levels. Level 0 holds the base learners, which are ordinary models trained on the original features. Level 1 holds the meta-learner, which is also an ordinary model. Its inputs are the predictions of the base learners, and its target is the same y the base learners were trained on.
This changes the learning problem. A base learner asks, "Given these feature values, what is the label?" The meta-learner asks, "Given what these models said, what is the label?" It never has to rediscover structure in the raw data. It only has to learn how much to trust each model, and where.
A simple average gives every base learner the same weight everywhere. A meta-learner can do better in several ways:
- It can weight the stronger model more heavily.
- It can correct a model that is systematically overconfident, such as a random forest, whose probabilities tend to be pulled away from 0 and 1.
- It can use agreement between models as a signal. If three models agree, the combined answer can be more confident than any one of them.
- With a flexible meta-learner, it can learn that one model is reliable in one region of the prediction space and another model is reliable elsewhere.
The meta-feature table
The meta-learner's training set is a table with one row per training example and one column per base model (for multiclass problems, one column per model per class). Each cell is a base model's prediction for that example. The target column is the original y.
With three base models on a binary problem, the meta-learner sees only three numbers per row. That table is small and low-dimensional. This is why the meta-learner should usually be simple: it has few inputs, and those inputs are strongly correlated with each other and with the target.
| Property | Base learner | Meta-learner |
|---|---|---|
| Input | Original features | Base-model predictions |
| Typical input width | Tens to thousands of columns | A handful of columns |
| What it learns | Patterns in the data | How to weight and correct models |
| Typical choice | Rich, flexible models | Simple, regularized model |
A worked example
The following code builds the meta-feature table by hand, trains a logistic regression on it, and inspects what it learned. It then compares the result with each base model and with a plain average.
import numpy as np
from sklearn.base import clone
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
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)
base = {
"rf": RandomForestClassifier(n_estimators=200, random_state=0),
"knn": make_pipeline(StandardScaler(), KNeighborsClassifier()),
"nb": GaussianNB(),
}
# Meta-features for training: out-of-fold probability of class 1 per model.
train_meta = np.column_stack([
cross_val_predict(clone(m), X_train, y_train, cv=5, method="predict_proba")[:, 1]
for m in base.values()
])
# Meta-features for testing: models refit on all training data.
fitted = {name: clone(m).fit(X_train, y_train) for name, m in base.items()}
test_meta = np.column_stack([m.predict_proba(X_test)[:, 1] for m in fitted.values()])
meta = LogisticRegression(max_iter=1000).fit(train_meta, y_train)
for i, name in enumerate(base):
acc = ((test_meta[:, i] > 0.5) == y_test).mean()
print(f"{name} accuracy: {acc:.3f}")
avg_acc = ((test_meta.mean(axis=1) > 0.5) == y_test).mean()
print(f"average accuracy: {avg_acc:.3f}")
print(f"meta accuracy: {meta.score(test_meta, y_test):.3f}")
print("meta coefficients:", dict(zip(base, meta.coef_[0].round(2))))
print("meta intercept:", meta.intercept_.round(2))The coefficients show the learned trust in each model. A larger coefficient means the meta-learner leans on that column more. The numbers will vary with the data and seed, so read your own output instead of expecting fixed values.
Training rows come from cross_val_predict, but test rows come from models refit on the full training set. This asymmetry is deliberate, and a later chapter explains why. For now, notice that the meta-learner never sees a base model's prediction on a row that model was trained on.
What the coefficients mean, and what they don't
With logistic regression as the meta-learner, each coefficient is the weight on one model's probability in the log-odds of the final prediction. The intercept shifts the overall decision threshold. Three cautions apply.
- The weights are not constrained to sum to one, and they can be larger than one. A sum above one means the meta-learner is sharpening the predictions. This is often how it corrects underconfident models.
- Base-model predictions are highly correlated, since every model is trying to predict the same
y. With correlated inputs, individual coefficients become unstable. One model can receive a large positive weight and a near-duplicate a negative weight, and the two cancel in most places. The ensemble can still work, but reading the coefficients as "importance" is unreliable. - A negative weight is not always a bug. It can mean the model is informative in the opposite direction after the others are accounted for. If it comes with unstable results across folds, regularize more or drop one of the models.
For regression, a common safeguard is to constrain the weights to be non-negative, for example LinearRegression(positive=True). The meta-learner then behaves like a learned weighted average, which is harder to overfit.
How flexible should the meta-learner be
A meta-learner can be any model, but flexibility has a cost. The training table has only as many informative columns as you have base models, and the out-of-fold predictions are noisy estimates. A deep gradient-boosted tree on three columns can fit that noise. A linear model with regularization can only learn weights and a threshold, which is usually all the signal there is.
The trade-off looks like this:
- A linear meta-learner is stable, fast, and easy to inspect. It cannot express "trust model A only when model B is uncertain."
- A tree-based meta-learner can capture such interactions. It needs more data, and it is more likely to overfit the meta-feature table.
- Any meta-learner has its own hyperparameters. Tuning them on the same data you use to judge the ensemble creates a second leakage route, covered in the evaluation chapter.
Start with regularized logistic regression for classification and ridge regression for regression. Move to something more flexible only if cross-validated results show a gain that survives a clean evaluation.
Common errors
- Training the meta-learner on in-sample predictions. This is the leakage described above. It produces a meta-learner that trusts overfit models.
- Passing labels when probabilities are available. Hard 0/1 labels discard confidence. The next chapter compares the two options in detail.
- Mismatched columns between training and test. The meta-learner expects the same models in the same order. If you reorder the base models or change
predict_probatopredictbetween the two tables, the weights are applied to the wrong columns, and no error is raised. - Using all probability columns in binary problems. For two classes, the probability of class 0 is just one minus the probability of class 1. Including both gives you perfectly collinear columns. The examples above use only the class-1 column. scikit-learn's
StackingClassifierhandles this for you by dropping one column in the binary case. - Evaluating on the data used to fit the meta-learner. The meta-learner's accuracy on its own training table is optimistic. Use a test set that played no part in any level.
Exercise
A stacking ensemble has three base models and a logistic regression meta-learner. On the meta-learner's training table, the coefficients are 4.1, -3.8, and 0.2, and cross-validated accuracy changes noticeably between runs with different seeds. What is the most likely cause, and what are two reasonable fixes?
Show answer
The first two base models probably produce highly correlated predictions, so the meta-learner assigns them large offsetting weights. The combined effect is small, but the individual weights are unstable. Two fixes: increase the regularization strength of the meta-learner (a smaller C in LogisticRegression), or remove one of the two near-duplicate base models. Replacing one with a model of a different family would add useful diversity.