Sub topic 11
Stacking with scikit-learn
This chapter assumes you know k-fold cross-validation, why out-of-fold predictions avoid leakage, and the basic scikit-learn fit/predict API. Earlier chapters built stacking by hand. Here you will use StackingClassifier and StackingRegressor, which do the out-of-fold bookkeeping for you, and you will learn which arguments matter and where they cause trouble.
What the estimator does when you call fit
StackingClassifier.fit(X, y) runs two phases.
- For each base estimator, it calls
cross_val_predictwith thecvyou supplied. This produces one out-of-fold prediction per training row per estimator. These columns form the meta-feature matrix. - It fits
final_estimatoron that matrix andy. It then refits every base estimator on the full training set, so that prediction time uses models that saw all the data.
At predict time, the refit base models score the new rows, and the final estimator turns those scores into a prediction. The out-of-fold models are thrown away. They exist only to produce honest meta-features.
A complete example
This example builds a three-model stack with a logistic regression on top. The kNN model sits in a pipeline because distance-based models need scaled inputs. The scaler is fitted inside each cross-validation fold, so it does not leak.
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 estimators argument is a list of (name, estimator) pairs. Names must be unique and must not contain double underscores, because they are used to set parameters like rf__n_estimators.
The arguments that matter
| Argument | Meaning | Default |
|---|---|---|
| `estimators` | List of `(name, estimator)` base models | required |
| `final_estimator` | The meta-learner | `LogisticRegression` for classifiers, `RidgeCV` for regressors |
| `cv` | Splitting used to build out-of-fold predictions | `None`, which means 5-fold (stratified for classifiers) |
| `stack_method` | Which method of each base model supplies the meta-features | `"auto"` |
| `passthrough` | Append the original features to the meta-features | `False` |
| `n_jobs` | Parallel jobs across base estimators | `None` |
Choosing stack_method
With "auto", scikit-learn tries predict_proba, then decision_function, then predict for each base model, in that order. This means different base models can contribute different kinds of columns. Set the method explicitly if you want predictable meta-features.
"predict_proba"gives class probabilities. This is usually the best choice because it carries confidence, not only the label."decision_function"gives unbounded margins. It suits models likeLinearSVCthat have no probabilities, but the scales differ between models, so use a scaling-tolerant meta-learner."predict"gives hard labels. It discards confidence and usually performs worse.
For a binary problem, scikit-learn drops the first probability column of each model, since it equals one minus the second. Three base models therefore give three meta-features. For a problem with K classes you get K columns per model (K - 1 in the binary case), so the meta-learner's input grows quickly with many classes.
Inspecting the fitted ensemble
After fitting, the object exposes the pieces. Reading them is the fastest way to confirm the stack behaves as you expect.
meta_test = stack.transform(X_test)
print("meta-feature shape:", meta_test.shape)
for name, coef in zip(stack.named_estimators_, stack.final_estimator_.coef_[0]):
print(f"{name}: weight {coef:.2f}")
for name, model in stack.named_estimators_.items():
print(f"{name} alone:", round(model.score(X_test, y_test), 3))
print("stack:", round(stack.score(X_test, y_test), 3))estimators_holds the base models refit on all training rows.named_estimators_gives the same models by name.final_estimator_is the fitted meta-learner.transform(X)returns the meta-feature matrix. For binary classification withpredict_proba, it has one column per base model.
Compare the stack with the best single model every time. A stack that does not beat its best member by a clear margin is not worth the extra cost.
Controlling the cross-validation
An integer cv uses the default splitter for the task. You can pass a splitter object for more control, for example StratifiedKFold(5, shuffle=True, random_state=0). The splitter must produce a true partition, where every training row lands in exactly one validation fold. Splitters that can repeat or skip rows, such as ShuffleSplit, fail because cross_val_predict cannot build one prediction per row.
Two points are easy to miss.
- The
cvargument only affects how the meta-learner's training data is made. The base models used at prediction time are always fitted on all the training data. They are trained on slightly more data than the models that produced the meta-features, so their predictions are a little more confident than what the meta-learner saw. This mismatch is small and is accepted by design. - Fitting costs roughly
cv + 1fits of every base model. Five folds across three models is 18 fits. Usen_jobsto parallelize across estimators, and be careful if the base models are themselves parallel, since the thread counts multiply.
Passing original features through
Setting passthrough=True appends the original feature columns to the meta-features. The meta-learner can then correct the base models in regions of feature space where they are known to be weak.
stack_pt = StackingClassifier(
estimators=base,
final_estimator=LogisticRegression(max_iter=2000),
cv=5,
stack_method="predict_proba",
passthrough=True,
n_jobs=-1,
)
stack_pt.fit(X_train, y_train)
print("passthrough accuracy:", stack_pt.score(X_test, y_test))
print("meta-feature shape:", stack_pt.transform(X_test).shape)With 20 original features and three base models, the meta-learner now sees 23 columns. This raises its capacity and its risk of overfitting. Scale the inputs if the meta-learner is regularized, because the raw features and the probabilities live on different scales. In a pipeline, a StandardScaler before the final estimator solves this: final_estimator=make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000)). Try passthrough as an experiment, and keep it only if cross-validated scores improve.
Regression
StackingRegressor has the same shape. It has no stack_method, because each base model contributes its predict output. The default meta-learner is RidgeCV, which picks its own regularization strength.
from sklearn.datasets import make_regression
from sklearn.ensemble import RandomForestRegressor, StackingRegressor
from sklearn.linear_model import RidgeCV
from sklearn.neighbors import KNeighborsRegressor
from sklearn.svm import SVR
Xr, yr = make_regression(n_samples=1500, n_features=15, n_informative=6, noise=10, random_state=0)
Xr_train, Xr_test, yr_train, yr_test = train_test_split(Xr, yr, test_size=0.25, random_state=0)
reg_stack = StackingRegressor(
estimators=[
("rf", RandomForestRegressor(n_estimators=200, random_state=0)),
("svr", make_pipeline(StandardScaler(), SVR())),
("knn", make_pipeline(StandardScaler(), KNeighborsRegressor())),
],
final_estimator=RidgeCV(),
cv=5,
)
reg_stack.fit(Xr_train, yr_train)
print("stack R^2:", reg_stack.score(Xr_test, yr_test))Common errors
- Scoring on the training set.
stack.score(X_train, y_train)is optimistic. The base models were refit on those rows, so they have already seen them. Only held-out data gives an honest number. - Tuning on the test set. Choosing
cv, the meta-learner, or the base models by looking at the test score leaks information. Use cross-validation on the training set to choose, then score the test set once. - Nesting costs. Wrapping a stack in
GridSearchCVmultiplies fit time by the number of folds and candidates. Tune base models separately first, then tune only a few stack settings. - Unscaled models in a stack. Put scalers inside pipelines in
estimators. ScalingXbefore the split leaks statistics from validation rows. - Time-ordered data. Shuffled or standard k-fold splits let the meta-learner train on predictions that depend on the future. Use a forward-chaining scheme and treat the setup with care. A later chapter covers this.
Exercise
You fit a StackingClassifier with three base models, stackmethod="predictproba", cv=5, and passthrough=True on a binary problem with 12 features. How many columns does the meta-learner's input have, and how many times is each base model fitted during fit?
Show answer
The input has 15 columns: one probability column per base model (3, because the first class column is dropped in the binary case) plus the 12 original features. Each base model is fitted 6 times: 5 cross-validation fits to build out-of-fold predictions, plus 1 final fit on all training rows.
Exercise
A colleague reports stack.score(Xtrain, ytrain) = 0.99 and stack.score(Xtest, ytest) = 0.90, while the best single base model scores 0.89 on the test set. What should you conclude, and what would you check next?
Show answer
The training score says nothing, because the refit base models have seen those rows. The honest comparison is 0.90 against 0.89 on held-out data, which is a gain too small to trust from one split. Check it with repeated or nested cross-validation on the training data, compare the spread of scores, and weigh the gain against the roughly six-fold training cost.