Sub topic 14
Evaluating an ensemble without fooling yourself
This chapter assumes you can run k-fold cross-validation, know why a test set is kept untouched, and have built a StackingClassifier as in the previous chapters. It covers how to measure whether a stack or blend is better than its parts, and the ways that measurement goes wrong.
Why ensembles are easy to over-credit
An ensemble has more moving parts than a single model. It has several base models, a meta-learner, a cross-validation scheme inside the fit, and often a choice of which members to keep. Every one of those choices can be tuned against a score. Each time you look at a score and change something, a little information from the data you scored on flows into the model. The final number then looks better than the model's real performance on new data.
Stacking adds a second problem. The meta-learner's inputs are predictions, and predictions are only trustworthy if the model that made them did not see the row it predicted. You handled that for training with out-of-fold (OOF) predictions. Evaluation needs the same care at a higher level.
The three data roles
Keep three roles separate:
- Training data fits the base models and the meta-learner. Inside it, the stack creates its own OOF predictions.
- Validation data is used to compare designs: which base models, which meta-learner, how many folds. It can be a set of outer cross-validation folds taken from the training data.
- Test data is used once, at the end, to report the number you will quote.
The key point is in the box "Fit whole stack on fold training part". The outer loop must refit the entire pipeline, including the inner OOF step, for each fold. If you only cross-validate the meta-learner on OOF features that were computed beforehand, you leak.
The subtle leak: cross-validating only the meta-learner
Suppose you compute OOF predictions for all of the training data once, then run cross-validation on the meta-learner using those columns. It looks reasonable, but it is optimistic. The OOF prediction for row A came from a base model trained on rows that include row B. When row B sits in a meta-learner validation fold, the meta-features of row A (in the meta-learner's training part) already carry information about row B's label. The effect is usually small for a simple meta-learner and larger when the base models memorize, such as deep trees or 1-nearest-neighbor. It also grows when you tune many options against that score.
The fix costs compute but not complexity: wrap the whole StackingClassifier in the outer cross-validation. This is nested cross-validation. The outer loop estimates performance and the inner cv=5 inside the stack builds meta-features.
A fair comparison
Report the stack next to its strongest single member, scored on identical folds with a proper scoring rule. The code below does this.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier, StackingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss
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, stratify=y, 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",
)
models = dict(base)
models["stack"] = stack
# Same outer folds for every model, so fold scores are paired.
outer = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = {}
for name, model in models.items():
scores[name] = cross_val_score(model, X_train, y_train, cv=outer, scoring="neg_log_loss")
print(f"{name:5s} log loss {-scores[name].mean():.3f} +/- {scores[name].std():.3f}")
best = max((n for n, _ in base), key=lambda n: scores[n].mean())
gain = scores["stack"] - scores[best] # positive means the stack has lower log loss
print(f"best single model: {best}")
print(f"per-fold gain: {np.round(gain, 3)}")
print(f"mean gain {gain.mean():.3f}, spread {gain.std():.3f}")
# The test set is touched once, after the design is fixed.
stack.fit(X_train, y_train)
print("test log loss:", log_loss(y_test, stack.predict_proba(X_test)))Read the output in this order:
- Compare the stack to the best single model, not the average of the members. Beating the average is easy and says little.
- Look at the per-fold gain. If the stack wins in all five folds, the gain is likely real. If the gain is smaller than its spread, or changes sign across folds, you cannot claim an improvement. Folds share training data, so their scores are correlated and the spread understates the true uncertainty. Treat it as a rough guide.
- Only then look at the test score. If it disagrees with the outer CV by more than the spread, find out why before reporting.
Choosing the metric
Stacking passes probabilities to the meta-learner, so probability quality matters. Accuracy ignores it. A stack can improve log loss or ROC AUC noticeably while accuracy barely moves, and with a small test set accuracy can move by chance in either direction. Use log loss or the Brier score for probability quality, ROC AUC for ranking, and a threshold metric (F1, recall at a precision target) only if the decision rule is fixed in advance. For regression stacks, compare RMSE or MAE, and use the same loss the meta-learner is trained on where possible.
Common mistakes
| Mistake | Why it inflates the score | Fix |
|---|---|---|
| Choosing members or hyperparameters by test score | The test set becomes a validation set | Choose with outer CV, test once |
| Fitting scaling, imputation, or feature selection on all data before splitting | Statistics from validation rows enter training | Put preprocessing inside pipelines |
| Cross-validating only the meta-learner on precomputed OOF features | Meta-features carry information about validation labels | Cross-validate the whole stack |
| Comparing the stack with the average base model | A weak baseline makes any gain look large | Compare with the best member and a tuned single model |
| Giving the stack more tuning effort than the baselines | The gain comes from effort, not from stacking | Spend the same search budget on both |
| Reporting the best of many ensemble variants | Selection bias from many tries | Count the variants tried, and confirm the winner on fresh data |
| Random folds on grouped or time-ordered data | Near-duplicate or future rows sit in both sides | Use `GroupKFold` or time-based splits |
Blending needs the same discipline
With blending the holdout set trains the meta-learner, so it cannot also be your honest estimate. You need a third set, or an outer CV loop around the whole blend. Because the holdout is small, its score is noisy. Differences of a few thousandths between two blends are often noise, and picking the best of ten blends on the holdout makes the holdout score optimistic.
When the gain is not worth reporting
Decide a threshold before you look. A reasonable rule is that the stack must beat the best single model by more than the fold-to-fold spread, on a metric that matches the use, and the improvement must justify the extra cost. Stacking multiplies training time by roughly the number of folds, adds prediction latency for every base model, and adds more things to monitor in production. A gain of 0.002 log loss rarely pays for that.
Exercise
A teammate computes OOF predictions for all 10,000 training rows once, then runs 5-fold cross-validation on a logistic-regression meta-learner using those columns and reports 0.91 ROC AUC for the stack. Why might this be optimistic, and what should they do instead?
Show answer
The OOF prediction for each row came from base models trained on other rows, including rows that later fall in the meta-learner's validation fold. Those meta-features therefore carry information about validation labels, and the effect grows if base models memorize or if many options are tuned against this score. They should wrap the whole StackingClassifier in outer cross-validation (for example crossvalscore with a StratifiedKFold) so each outer fold refits the base models and the inner OOF step on its own training part. They should then compare per-fold scores with the best single model and score a locked test set once at the end.
Exercise
In the comparison code, the stack's per-fold gain in negative log loss is [0.004, -0.003, 0.006, -0.001, 0.002], with mean 0.0016 and spread about 0.0034. Should you report that the stack improves on the best single model?
Show answer
No. The mean gain is smaller than the spread and the sign changes across folds, so the data do not show a reliable improvement. Folds share training data, so the real uncertainty is even larger than the spread suggests. Keep the simpler single model unless more data, a better metric, or a repeated cross-validation run shows a consistent gain.