Sub topic 6
Why naive stacking leaks
This chapter assumes you know supervised learning, k-fold cross-validation, and the difference between training error and test error. It also assumes you can read basic scikit-learn code. You should also know what a meta-learner is: a second-level model that takes the predictions of base models as its input features.
The naive recipe
The obvious way to build a stacking ensemble has three steps:
- Fit each base model on the training set.
- Call
predictorpredict_probaon that same training set to get meta-features. - Fit the meta-learner on those meta-features and the training labels.
This runs without errors and often produces a good-looking training score. It is still wrong, because the meta-learner learns from predictions that do not resemble the ones it will see later.
What goes wrong
A base model has seen the label of every training row during fitting. When it predicts on a training row, it is partly recalling an answer it was given. This is target leakage: information about the label reaches the feature through the fitting process.
The size of the leak depends on the model:
- A fully grown decision tree or a random forest can reproduce most training labels almost exactly. Its training-set probabilities are close to 0 or 1.
- A k-nearest-neighbors model counts each training row as its own neighbor, so its training predictions are optimistic too.
- A heavily regularized linear model memorizes very little, so its training predictions are close to its honest ones.
The meta-learner cannot see these differences. It only sees that the random forest column matches the labels almost perfectly, so it gives that column a very large weight. At test time the forest is no longer reciting memorized answers. Its predictions are noisier and less confident than the meta-learner expects, and the ensemble ends up trusting its most overfit member most.
This is a distribution shift between the meta-features used for training and those used for prediction. The meta-learner is trained on in-sample predictions and applied to out-of-sample ones.
Seeing the leak in code
The script below builds both versions of the meta-features from the same data and base models. It then compares the meta-learner weights and the test accuracy. The data has 10 percent label noise (flip_y=0.1). Noise makes memorization useless on new data, so the leak shows up more clearly.
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.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, flip_y=0.1, 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())),
]
# Base models refit on all training data. Both versions use these at test time.
fitted = [clone(model).fit(X_train, y_train) for _, model in base]
test_meta = np.column_stack([m.predict_proba(X_test)[:, 1] for m in fitted])
# Naive meta-features: predict the rows the models were fit on.
naive_meta_X = np.column_stack(
[m.predict_proba(X_train)[:, 1] for m in fitted]
)
naive = LogisticRegression(max_iter=1000).fit(naive_meta_X, y_train)
# Out-of-fold meta-features: every row is predicted by a model that never saw it.
oof_meta_X = np.column_stack([
cross_val_predict(clone(model), X_train, y_train, cv=5, method="predict_proba")[:, 1]
for _, model in base
])
oof = LogisticRegression(max_iter=1000).fit(oof_meta_X, y_train)
names = [name for name, _ in base]
print("columns:", names)
print("naive coefficients:", naive.coef_.round(2))
print("oof coefficients: ", oof.coef_.round(2))
print("rf train accuracy: ", fitted[0].score(X_train, y_train))
print("naive test accuracy:", naive.score(test_meta, y_test))
print("oof test accuracy: ", oof.score(test_meta, y_test))Exact numbers depend on your library versions. The pattern to look for is this:
- The random forest's training accuracy is close to 1.0, far above its real accuracy.
- The naive meta-learner puts a much larger coefficient on the
rfcolumn than the out-of-fold meta-learner does. - The out-of-fold meta-learner usually matches or beats the naive one on the test set.
Three ways the leak shows up
Inflated training scores. If you score the meta-learner on naive_meta_X, you get a number that reflects memorization. It tells you nothing about generalization.
Misleading weights. The meta-learner prefers whichever base model overfits most. In a regression stack, you may see a near-1 coefficient on one model and near-0 on the rest. That is a warning sign.
Unstable behavior across datasets. The same code may look fine on a small, clean problem and fail on a noisy one. Predictable behavior needs a method that removes the cause, not one that happens to work.
The fix: honest meta-features
The cure is to produce each meta-feature value with a model that did not see that row's label. There are two standard ways to do this, and the next chapters build both:
- Out-of-fold predictions. Split the training data into k folds. For each fold, fit the base model on the other k-1 folds and predict the held-out fold. After k rounds, every training row has one honest prediction. The next chapter covers this in detail.
- A holdout set. Fit the base models on one part of the training data and generate meta-features on a separate part they never saw. Blending uses this approach.
In both cases the meta-features come from the same kind of process that will produce them at prediction time: a model scoring rows it was not fit on.
A subtle point about the test-time models
Out-of-fold stacking creates a small mismatch of its own. The meta-learner was trained on predictions from models fit on 80 percent of the training data when cv=5. At test time, the base models are refit on 100 percent. The test-time predictions are slightly better than the ones the meta-learner learned from.
This mismatch is mild and usually harmless. Its direction is conservative: the meta-learner has seen slightly worse base predictions than it will receive. This is why scikit-learn's StackingClassifier refits the base estimators on the full training set after it builds the meta-features. Compare this with naive stacking, where the mismatch is large and runs in the dangerous direction.
Other places leakage enters
Out-of-fold predictions fix the main leak, but you can reintroduce leakage in other ways:
- Preprocessing fit on all the data. If you fit a scaler or imputer on the full dataset before splitting, test-set statistics leak into every model. Put preprocessing inside each base model's pipeline, as the
StandardScaleris in the code above. - Tuning on the test set. If you pick base models or meta-learner settings by looking at test scores, the test set stops being a fair estimate. Tune with cross-validation on the training data only.
- Different folds per base model. Out-of-fold columns from different fold splits are still honest, but reusing one fixed split makes the columns easier to compare and debug. Use a
KFoldorStratifiedKFoldobject with a fixedrandom_statefor all base models if you build the stack by hand. - Grouped or repeated rows. If rows from the same user, patient, or session appear in several folds, a model sees near-copies of the held-out row during fitting. The out-of-fold predictions are then still too optimistic. Use
GroupKFoldin that case.
Exercise
A teammate builds a stack by fitting a random forest and a logistic regression on the training set, calling predict_proba on the same training set, and fitting a second logistic regression on those probabilities. The meta-learner gives the forest a coefficient of 9 and the linear model a coefficient of 0.4. Explain why the weights look like this and how you would change the pipeline.
Show answer
The forest memorizes training labels, so its in-sample probabilities are close to the true labels. The linear model cannot memorize, so its in-sample predictions are only moderately accurate. The meta-learner sees the forest column as nearly perfect and weights it heavily, even though the forest is far less accurate on new rows. Replace the in-sample predictions with out-of-fold predictions from cross_val_predict(..., method="predict_proba"), fit the meta-learner on those, and refit the base models on the full training set for test-time predictions. Alternatively, use a separate holdout set to produce the meta-features.
Exercise
You use 5-fold out-of-fold predictions to train the meta-learner. Why is it still acceptable that the base models are refit on 100 percent of the training data for test-time predictions?
Show answer
The meta-learner trained on predictions from models fit on 80 percent of the data, so the full-data models are slightly stronger than the ones it learned from. The mismatch is small and conservative, because it errs toward underestimating base model quality. Naive stacking is different: its meta-features are inflated by memorization, so the mismatch is large and in the harmful direction.