Sub topic 13
Passing raw features to the meta-learner
This chapter assumes you can build a StackingClassifier, that you know why the meta-learner trains on out-of-fold predictions, and that you can read cross-validation scores. By default, the meta-learner sees only the base models' predictions. Here you will see what changes when you also give it the original input features, when that helps, and how it can hurt.
What passthrough does
In a standard stack, the meta-learner's input has one column per base model (for binary probabilities) or one per class and model (for multiclass). The raw features are discarded after the base models consume them.
Passthrough appends the original feature columns to those meta-features. If you have 3 base models, binary classification, and 20 raw features, the meta-learner trains on 3 + 20 = 23 columns instead of 3.
In scikit-learn this is one argument: passthrough=True. The default is False.
Why it can help
A plain stack lets the meta-learner decide how much to trust each model overall. For example, it might learn "weight the forest at 0.6 and the k-nearest-neighbors model at 0.4". The weights are the same for every row.
Raw features let the meta-learner make that decision depend on the input. Suppose the k-nearest-neighbors model is accurate for rows with small values of feature 3, and the forest is better elsewhere. A meta-learner that sees feature 3 can learn to switch between them. That requires a meta-learner that can express interactions, such as a small tree ensemble. A linear meta-learner can only add a raw-feature term to the prediction. It cannot change how much it trusts a base model based on that feature.
Passthrough can also help when every base model misses the same simple signal. A linear term on a raw feature, which the meta-learner can pick up directly, sometimes recovers it. This is rare, because a diverse base set usually covers such signals.
Why it can hurt
Passthrough widens the meta-learner's input. This has three costs:
- More room to overfit. The meta-learner trains on the same rows as the base models (via out-of-fold predictions), but now it also has all the raw columns to memorize noise with. With 200 raw features and 3 predictions, the predictions are a small share of the input.
- Lost simplicity. A meta-learner on 3 columns is easy to inspect. One on 23 columns is not, and the meta-learner is effectively a fourth full model.
- Scale mismatch. Probabilities lie in [0, 1]. Raw features may have any scale. A regularized linear meta-learner penalizes coefficients unevenly across columns that have different scales, so the penalty no longer treats the columns equally. Standardize the inputs inside the meta-learner.
Note that the base models' predictions are out-of-fold, but the raw features are the real training features. The meta-learner can therefore fit raw-feature patterns as hard as any model fit to the training set. Only the predictions get the protection that out-of-fold training provides.
Comparing the two in scikit-learn
This example builds the same stack with and without passthrough. It scores both with cross-validation on the training set only. The test set stays untouched.
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier, StackingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import 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)),
("knn", make_pipeline(StandardScaler(), KNeighborsClassifier())),
]
def build(passthrough):
# Standardize inside the meta-learner so probabilities and raw features
# are on comparable scales when they are penalized together.
meta = make_pipeline(StandardScaler(), LogisticRegression(C=0.1, max_iter=1000))
return StackingClassifier(
estimators=base,
final_estimator=meta,
cv=5,
stack_method="predict_proba",
passthrough=passthrough,
)
for flag in (False, True):
scores = cross_val_score(build(flag), X_train, y_train, cv=5)
print(f"passthrough={flag}: mean={scores.mean():.3f} std={scores.std():.3f}")
stack = build(True).fit(X_train, y_train)
print("meta-learner input columns:", stack.final_estimator_[-1].coef_.shape[1])The last line prints 22. Each of the 2 base models contributes one column, because for binary classification scikit-learn drops the redundant first probability column. The other 20 columns are the raw features.
The score difference depends on the data and the seed. Do not expect passthrough to win. On this synthetic problem the two scores may be within one standard deviation of each other, and when they are, prefer the simpler stack.
Building it by hand
Passthrough is a horizontal concatenation. The key detail is that the out-of-fold predictions and the raw features are both computed on the training rows, and the same concatenation is applied at test time.
import numpy as np
from sklearn.base import clone
from sklearn.model_selection import cross_val_predict
# Continues from the previous example (base, X_train, X_test, y_train, y_test).
oof = np.column_stack([
cross_val_predict(clone(model), X_train, y_train, cv=5, method="predict_proba")[:, 1]
for _, model in base
])
meta_train = np.hstack([oof, X_train])
fitted = [clone(model).fit(X_train, y_train) for _, model in base]
test_preds = np.column_stack([m.predict_proba(X_test)[:, 1] for m in fitted])
meta_test = np.hstack([test_preds, X_test])
meta = make_pipeline(StandardScaler(), LogisticRegression(C=0.1, max_iter=1000))
meta.fit(meta_train, y_train)
print("manual passthrough accuracy:", meta.score(meta_test, y_test))Keep the column order identical in meta_train and meta_test: predictions first, raw features second. A swapped order trains and predicts without error but gives meaningless results.
Choosing a meta-learner for passthrough
The meta-learner choice matters more with passthrough than without it.
| Meta-learner | What it can do with raw features | Main risk |
|---|---|---|
| Regularized logistic or ridge regression | Add a linear term per feature. Cannot reweight base models by region. | Little gain over a plain stack. Needs scaling. |
| Shallow gradient boosting or random forest | Learn "trust model A when feature 3 is small". | Overfits easily. Tune depth and learning rate. |
| Unregularized linear model | Fits everything. | Overfits with many raw columns. |
If you want the meta-learner to select between base models by region, use a small tree-based model with limited depth and few estimators. If you only want a safety net for signals the base models missed, a strongly regularized linear model is enough.
When to use it
Use these checks in order:
- Build the plain stack first and record its cross-validated score and spread.
- Add passthrough with the same meta-learner and compare. A gain smaller than the fold-to-fold standard deviation is not a gain.
- If the gain is real, try a tree-based meta-learner with passthrough. This tests the region-dependent trust idea directly.
- Check the cost. Passthrough adds no base-model fits, but a flexible meta-learner on many columns trains more slowly and is harder to explain.
Avoid passthrough when the raw feature count is large compared with the number of rows, when the features are sparse and high-dimensional such as text counts, or when you need to explain predictions by base-model weights. With sparse input, scikit-learn concatenates with sparse stacking, but a dense meta-learner may not accept the result.
Exercise
A stack has 4 base models and a multiclass problem with 3 classes, using stackmethod="predictproba". The data has 15 raw features. How many columns does the meta-learner receive with passthrough=True, and why would a linear meta-learner on those columns need scaling?
Show answer
Each base model contributes 3 probability columns in the multiclass case (scikit-learn does not drop a column when there are more than two classes), so 4 × 3 = 12 meta-feature columns. Adding 15 raw features gives 27 columns. Scaling is needed because probabilities lie in [0, 1] while raw features can have any range, so a regularization penalty would shrink the coefficients of differently scaled columns unevenly.
Exercise
Passthrough raised the cross-validated accuracy of a stack from 0.912 to 0.914, and the standard deviation across folds is 0.012. Should you keep it? What would you try next?
Show answer
No. The 0.002 gain is much smaller than the 0.012 fold-to-fold spread, so it is not evidence of a real improvement, and passthrough adds complexity and overfitting risk. Keep the plain stack. If you still suspect that base-model trust depends on the input, try a shallow tree-based meta-learner with passthrough and compare again with cross-validation.