Sub topic 11
Stacking with scikit-learn
This chapter assumes you know k-fold cross-validation, why a meta-learner needs out-of-fold predictions, and basic scikit-learn usage. Here you will see how StackingClassifier does that work for you.
What the class does
StackingClassifier (and StackingRegressor for regression) implements the stacking procedure in one fit call:
- For each base model, it computes out-of-fold predictions on the training data using
cvfolds. - It trains
final_estimatoron those predictions. - It refits every base model on the full training set, so they are ready for new data.
At prediction time, the refit base models produce meta-features, and the meta-learner turns them into the final prediction.
A complete example
from sklearn.datasets import make_classification
from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier, StackingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import 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())),
]
stack = StackingClassifier(
estimators=base,
final_estimator=LogisticRegression(max_iter=1000),
cv=5,
stack_method="predict_proba",
)
stack.fit(X_train, y_train)
print("stack accuracy:", stack.score(X_test, y_test))The three base models are different kinds of learner, so their errors are less likely to coincide. The k-nearest-neighbours model sits in a pipeline with a scaler because it is distance based. Each base model keeps its own preprocessing.
The parameters that matter
| Parameter | Meaning | Default |
|---|---|---|
| `estimators` | List of `(name, model)` pairs | required |
| `final_estimator` | The meta-learner | logistic regression (classifier), ridge (regressor) |
| `cv` | Folds used to create out-of-fold predictions | 5, stratified for classifiers |
| `stack_method` | `predict_proba`, `decision_function`, `predict`, or `auto` | `auto` |
| `passthrough` | Also give the original features to the meta-learner | `False` |
| `n_jobs` | Parallel fitting of base models | `None` |
Use predict_proba when your base models support it. Class labels throw away confidence, and the meta-learner can use that confidence.
Common errors
- Passing a fitted model as the evaluation.
stack.scoreon the training data is optimistic. Score only on held-out data. - Forgetting cost. With
cv=5, each base model is fit six times: five for the folds and once on all the data. Budget for that, and considern_jobs=-1. - Expecting
cvto be your evaluation. It only builds meta-features. It does not give you an honest estimate of the whole stack. - A complex meta-learner. A deep model on a few correlated columns overfits. Keep it simple and regularized.
- Inspecting the wrong models. After fitting,
stack.estimators_holds the base models refit on all the training data. These are the ones used at prediction time.
Exercise
You set cv=10 instead of cv=5 in StackingClassifier. Which parts of training cost change, and does the meta-learner see more rows?
Show answer
Each base model is fit 11 times instead of 6 (ten folds plus one refit on all data), so training is slower. The meta-learner still sees one row per training sample, because every sample receives exactly one out-of-fold prediction. Only the quality of those predictions changes, since each fold's model trains on more data.