Sub topic 7
Out-of-fold predictions
This chapter assumes you know k-fold cross-validation, the difference between training and test error, and basic scikit-learn. It covers how to produce the training data for a meta-learner without leaking labels.
The problem out-of-fold predictions solve
A meta-learner needs a table with one row per training example and one column per base model. Each cell is that base model's prediction for that row. The meta-learner then learns how much to trust each column.
The obvious way to build this table is to fit each base model on the training set and call predict_proba on that same set. This fails. A base model has already seen those rows and their labels, so its predictions there are optimistic. A random forest may score near 100% on its own training data. The meta-learner then learns to trust the most overfit model most, and it does worse on new data.
An out-of-fold (OOF) prediction for row i comes from a model that was trained without row i. Every training row gets a prediction that looks like what the model would say about unseen data.
How the procedure works
For one base model and K folds:
- Split the training set into K folds.
- For each fold, train a fresh copy of the model on the other K−1 folds.
- Predict the held-out fold and write the results into the matching rows of an array.
- After K rounds, every row has exactly one prediction, made by a model that never saw it.
Repeat this for every base model and place the resulting columns side by side. That table is the meta-feature matrix.
Doing it by hand
The loop below produces OOF probabilities for one model. It also shows how different in-sample predictions are from OOF predictions.
import numpy as np
from sklearn.base import clone
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import StratifiedKFold, cross_val_predict, train_test_split
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)
model = RandomForestClassifier(n_estimators=200, random_state=0)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
oof = np.full(len(y_train), np.nan)
for fit_idx, val_idx in cv.split(X_train, y_train):
fold_model = clone(model).fit(X_train[fit_idx], y_train[fit_idx])
oof[val_idx] = fold_model.predict_proba(X_train[val_idx])[:, 1]
assert not np.isnan(oof).any() # every row received a prediction
# The same result in one call, using the same folds.
oof_auto = cross_val_predict(model, X_train, y_train, cv=cv, method="predict_proba")[:, 1]
print("matches cross_val_predict:", np.allclose(oof, oof_auto))
# In-sample predictions versus out-of-fold predictions.
in_sample = clone(model).fit(X_train, y_train).predict_proba(X_train)[:, 1]
print("in-sample accuracy:", accuracy_score(y_train, in_sample > 0.5))
print("out-of-fold accuracy:", accuracy_score(y_train, oof > 0.5))The in-sample accuracy will be close to 1.0 and the OOF accuracy will be clearly lower. The OOF number is the honest estimate, and it is what the meta-learner should see.
cross_val_predict does the loop for you. Passing the same cv object to every base model matters, as the pitfalls below explain.
What the OOF predictions are, and are not
OOF predictions are not produced by one model. Each fold's predictions come from a different fitted model, trained on a different 80% of the data (with K=5). The column is a mix of five slightly different models' outputs.
This has two consequences.
- Training and test inputs differ slightly. At test time you usually refit each base model on the whole training set. That model saw 100% of the data, so its predictions are a little better and a little more confident than the OOF ones the meta-learner trained on. The mismatch is small for a reasonable K and a stable model. It grows when models are unstable or when data is scarce.
- There are two ways to make test meta-features. You can refit on all training data, as the earlier stacking example does. Or you can average the K fold models' predictions on the test set, which avoids one extra fit and matches the training distribution more closely. scikit-learn's
StackingClassifierrefits the base models on all of the data.
Why leakage is avoided but not zero
OOF predictions are not perfectly clean. The fold-1 model was trained on rows that include fold 2, and fold-2 predictions feed the meta-learner. Information flows across folds, but only through model parameters and never through a row's own label. In practice this is accepted, and it is far safer than in-sample predictions. It does mean you cannot treat the meta-learner's cross-validated score as perfectly unbiased. The evaluation chapter returns to this.
Seeing the leak
This second example compares a meta-learner trained on in-sample predictions with one trained on OOF predictions. It continues from the previous code.
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
base = [
RandomForestClassifier(n_estimators=200, random_state=0),
GradientBoostingClassifier(random_state=0),
make_pipeline(StandardScaler(), KNeighborsClassifier()),
]
def proba1(m, X_):
return m.predict_proba(X_)[:, 1]
# Leaky: meta-features are predictions on the data the models were fit on.
fitted = [clone(m).fit(X_train, y_train) for m in base]
leaky_meta_train = np.column_stack([proba1(m, X_train) for m in fitted])
# Correct: meta-features are out-of-fold predictions.
oof_meta_train = np.column_stack([
cross_val_predict(m, X_train, y_train, cv=cv, method="predict_proba")[:, 1]
for m in base
])
test_meta = np.column_stack([proba1(m, X_test) for m in fitted])
for name, meta_train in [("leaky", leaky_meta_train), ("out-of-fold", oof_meta_train)]:
meta = LogisticRegression(max_iter=1000).fit(meta_train, y_train)
print(name, "meta-learner test accuracy:", meta.score(test_meta, y_test))
print(name, "coefficients:", meta.coef_.round(2))Look at the coefficients. The leaky version puts a large weight on the random forest, because on training rows the forest looks nearly perfect. The OOF version spreads weight more evenly. The test accuracy gap depends on the data, and it can be small on easy problems, but the leaky pipeline can only be worse.
Common errors
- Using different folds for different base models. Each column is valid on its own, but a shared fold split keeps the columns comparable and makes the pipeline reproducible. Pass the same
cvobject everywhere. - Fitting preprocessing before the split. If you scale or impute on the full training set, then split, statistics from the held-out fold leak into the fold model. Put preprocessing inside a
Pipeline, as the KNN above does. - Ignoring structure in the rows. Plain K-fold is wrong when rows are grouped (several rows per patient or user) or ordered in time. Use
GroupKFoldfor groups. For time-ordered data, ordinary shuffled folds let the model train on the future, so the OOF predictions are too optimistic. Time series needs forward-chaining splits, andcross_val_predictdoes not work with them because they leave the earliest rows without a prediction. - Unshuffled folds on sorted data. If the file is sorted by label, unshuffled folds can have very different class balance. Use
StratifiedKFoldwithshuffle=Truefor classification. - Using
predictinstead ofpredict_proba. Hard labels discard confidence. Probabilities usually give the meta-learner more to work with. The earlier chapter on meta-features covers when labels are acceptable. - Keeping every probability column in multiclass problems. The columns for each model sum to 1, so they are collinear. Dropping one class column per model avoids this for a linear meta-learner. For binary problems, keep only the class-1 column as above.
- Forgetting regression. For regression, call
predictrather thanpredict_proba, withcross_val_predict(..., method="predict").
Cost
OOF generation fits each base model K times, plus one more fit on the full training set. With three models and K=5, that is 18 fits instead of 3. A larger K gives each fold model more data and a closer match to the final model, but costs more. K=5 is a common default and K=10 is rarely worth the time for expensive models.
Exercise
You build meta-features by fitting each base model on the training set and calling predict_proba on that same training set. The meta-learner's cross-validated score looks excellent, but test accuracy is poor. What went wrong, and what is the fix?
Show answer
The base models had already seen the labels of the rows they predicted, so their predictions were over-optimistic, especially for flexible models like random forests. The meta-learner learned to over-trust those models. The fix is to generate out-of-fold predictions with K-fold cross-validation (for example, crossvalpredict with the same cv for every base model), so each training row is predicted by a model that never saw it.
Exercise
A dataset contains several rows per customer. Why can plain shuffled K-fold produce misleading OOF predictions, and which splitter should you use instead?
Show answer
Rows from the same customer can land in both the training and held-out folds, so the fold model effectively sees the customer it is predicting, which makes the OOF predictions too optimistic. Use GroupKFold with the customer ID as the group, so all rows from one customer fall in the same fold.