Sub topic 14
Evaluating an ensemble without fooling yourself
This chapter assumes you know k-fold cross-validation, how out-of-fold predictions feed a meta-learner, and the scikit-learn StackingClassifier from the earlier chapters.
Where the leaks hide
A stacking ensemble has two training stages, so it has more places to leak information than a single model. Three mistakes are common:
- Scoring the meta-learner on the same out-of-fold predictions it was trained on. That score only tells you how well it fits its training data.
- Choosing base models, meta-learner settings or blend weights by looking at the test score. After that the test set is no longer unseen.
- Fitting a scaler or feature selector on all the data before splitting.
The rule is to keep a test set outside every step that learns anything, and to use it once.
Cross-validate the whole stack
StackingClassifier already runs an inner cross-validation to build its meta-features. Do not use that as your estimate. Wrap the whole estimator in an outer cross_val_score. Each outer fold then refits every base model and the meta-learner on that fold's training rows only.
Compare against baselines on the same folds. If the stack does not clearly beat its best member, the extra cost is not justified.
from sklearn.datasets import make_classification
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier, StackingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, 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=100, random_state=0)),
("gb", GradientBoostingClassifier(random_state=0)),
("knn", make_pipeline(StandardScaler(), KNeighborsClassifier())),
]
stack = StackingClassifier(
estimators=base,
final_estimator=LogisticRegression(max_iter=1000),
cv=5,
stack_method="predict_proba",
)
outer = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
candidates = dict(base)
candidates["stack"] = stack
for name, model in candidates.items():
scores = cross_val_score(model, X_train, y_train, cv=outer, scoring="accuracy")
print(f"{name:6s} mean={scores.mean():.3f} std={scores.std():.3f}")
# Only after all decisions are made:
stack.fit(X_train, y_train)
print("final test accuracy:", stack.score(X_test, y_test))Every candidate sees identical outer folds, so the differences are paired and fair. The stack is fitted five more times inside this loop, which is why it is slow.
Reading the numbers
- Compare the gain with the fold standard deviation. A gain of 0.002 with a standard deviation of 0.01 is noise.
- Use a metric that fits the problem, such as log loss or ROC AUC for probability quality, rather than accuracy alone.
- With blending, the holdout score is noisy because the holdout is small. Prefer cross-validation on the training part for comparisons, and keep the test set separate from the blend holdout.
- Do many comparisons and one of them will look good by chance. Each time you pick the winner using the test set, you spend some of its honesty.
Checklist
- Split off the test set first.
- Put all preprocessing inside pipelines.
- Cross-validate the entire stack, not only the meta-learner.
- Beat the best single model on the same folds.
- Report the standard deviation with the mean.
- Score the test set once.
Exercise
A teammate reports 0.95 accuracy for a stack by scoring the meta-learner on the out-of-fold predictions it was trained on. Why is this not a trustworthy estimate, and what should they do instead?
Show answer
The meta-learner was fitted to those exact predictions and labels, so the score measures fit to training data. They should run an outer cross-validation over the whole stack, or score on a test set that was never used for training or model choices, and compare against the best single model on the same folds.