Sub topic 5
Meta-features: probabilities or labels
This chapter assumes you know k-fold cross-validation and basic scikit-learn. It also assumes you know how stacking is organised: base learners feed a meta-learner. The question here is what the base learners should hand over. Out-of-fold predictions are covered in a later chapter. Here the focus is the form of the numbers.
What a meta-feature is
A meta-feature is one input column for the meta-learner. Each is built from a base learner's output for one row. The meta-learner never sees the original features unless you pass them through. Whatever form the output takes sets an upper limit on what the meta-learner can learn.
A classifier can give you three kinds of output:
- A hard label from
predict, such as 0 or 1. - A probability from
predict_proba, such as 0.83. - A raw score from
decision_function, such as a signed distance from a margin.
Why probabilities usually win
A label throws away confidence. Suppose a random forest predicts class 1 with probability 0.51 and a k-nearest-neighbours model predicts class 1 with probability 0.99. Both become "1" as labels. The meta-learner cannot tell a coin flip from a near certainty.
Probabilities keep that information. The meta-learner can learn rules such as "trust the forest when it is far from 0.5, otherwise lean on the neighbours model". Labels only allow a vote with learned weights.
Probabilities also help with ties. With three models and two classes you rarely get a tie, but with four models you do. Probabilities break ties by confidence.
| Property | Labels | Probabilities |
|---|---|---|
| Information kept | Only the decision | Decision and confidence |
| Columns per model (k classes) | 1 | k (k-1 in binary scikit-learn) |
| Works for any classifier | Yes | Only if the model estimates probabilities |
| Sensitive to calibration | No | Yes |
| Typical use | Models without probabilities, or very noisy ones | Default choice |
The calibration catch
Probabilities from different models are not on the same scale. A random forest averages tree votes, so it rarely outputs values near 0 or 1. Naive Bayes tends to push values to the extremes. A support vector machine has no native probabilities, and scikit-learn fits an extra internal calibration step to get them.
A linear meta-learner can partly correct these differences. It learns one weight per column, which acts as a rescaling. It cannot fix a distortion that is not linear. If a model is badly overconfident, you have two options:
- Wrap it in
CalibratedClassifierCV. - Transform the probabilities, for example with a logit, before the meta-learner sees them.
The logit is log(p / (1 - p)). It stretches the area near 0 and 1, which suits logistic regression because that model is linear in log-odds. Clip p first, since a probability of exactly 0 or 1 gives an infinite logit.
Raw scores
decision_function returns an unbounded score for models such as LinearSVC and logistic regression. These scores are often a good meta-feature. They avoid saturation near 0 and 1, and they need no calibration step. In a binary problem a score of 0 is the decision boundary, and its sign is the label.
The stack_method argument of StackingClassifier controls the choice. It accepts "auto", "predict_proba", "decision_function" and "predict". With "auto", scikit-learn tries predict_proba, then decision_function, then predict, and uses the first one each base model supports. It decides per model, so a mixed set of columns is possible.
Shape of the meta-feature matrix
The number of columns depends on the problem type.
- Regression: one column per base model.
- Binary classification with probabilities: one column per model. scikit-learn drops the first probability column because the two columns sum to 1, so keeping both would be redundant.
- Multiclass with k classes: k columns per model. A stack of 5 models on a 10-class problem gives 50 columns. For multiclass the full set is kept, because one column cannot be inferred from the rest by sight alone, even though it is redundant in principle.
More columns means more meta-learner parameters and more room to overfit, which is one reason a small, regularised meta-learner is preferred.
Redundant columns also cause collinearity. If two base models produce nearly identical probabilities, a plain linear meta-learner can assign large offsetting weights. Regularisation reduces this, and so does removing near-duplicate models.
Comparing labels and probabilities in code
The script below builds the same stack twice. The only difference is stack_method. It prints the shape of the meta-feature matrix for the test set and two metrics. Accuracy only checks the final label. Log loss also checks the confidence of the final probabilities.
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier, StackingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, log_loss
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)
def make_base():
return [
("rf", RandomForestClassifier(n_estimators=200, random_state=0)),
("knn", make_pipeline(StandardScaler(), KNeighborsClassifier())),
("lr", make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))),
]
for method in ["predict_proba", "predict"]:
stack = StackingClassifier(
estimators=make_base(),
final_estimator=LogisticRegression(max_iter=1000),
cv=5,
stack_method=method,
)
stack.fit(X_train, y_train)
meta_test = stack.transform(X_test)
proba = stack.predict_proba(X_test)
print(
method,
"meta shape:", meta_test.shape,
"accuracy: %.3f" % accuracy_score(y_test, stack.predict(X_test)),
"log loss: %.3f" % log_loss(y_test, proba),
)Both runs give a (500, 3) meta-feature matrix, since the problem is binary and there are three models. Expect the probability version to match or beat the label version on log loss. The gap in accuracy is often small. Exact numbers depend on your library versions, so run it and read your own output.
Building the logit meta-features by hand
This script produces out-of-fold probabilities, converts them to logits, and inspects how correlated the columns are. It is self-contained.
import numpy as np
from sklearn.base import clone
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_predict, 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)
models = [
RandomForestClassifier(n_estimators=200, random_state=0),
make_pipeline(StandardScaler(), KNeighborsClassifier()),
]
def to_logit(p, eps=1e-3):
p = np.clip(p, eps, 1 - eps)
return np.log(p / (1 - p))
oof = np.column_stack([
cross_val_predict(clone(m), X_train, y_train, cv=5, method="predict_proba")[:, 1]
for m in models
])
print("correlation of raw probabilities:", np.corrcoef(oof.T)[0, 1].round(3))
meta = LogisticRegression(max_iter=1000).fit(to_logit(oof), y_train)
fitted = [clone(m).fit(X_train, y_train) for m in models]
test_meta = np.column_stack([m.predict_proba(X_test)[:, 1] for m in fitted])
print("logit stack accuracy:", meta.score(to_logit(test_meta), y_test))The clip value eps matters. A random forest with 200 trees can output exactly 0.0 or 1.0. Without clipping, the logit is infinite and LogisticRegression raises an error.
Deciding which to use
- Start with probabilities from every model that supports them. This is the default and rarely hurts.
- If a model offers only scores, use
decision_function. Do not discard it. - Use labels only when a base model gives no usable score, or when you want the simplest possible vote.
- If a base model's probabilities look extreme or flat, calibrate it or apply a logit before the meta-learner.
- In multiclass problems, watch the column count and consider a stronger penalty on the meta-learner.
Exercise
A stack has 4 base models and a 6-class problem. Using probabilities from every model, how many columns does the meta-feature matrix have? What changes if you switch to labels, and what do you lose?
Show answer
With probabilities it has 4 x 6 = 24 columns. With labels it has 4 columns, one integer class per model. Because the labels are integers with no order, they should be one-hot encoded for a linear meta-learner. You lose the confidence of each model, so the meta-learner cannot tell a barely winning class from a clear winner.