Build a Stacked Ensemble Model Combining Multiple Classifiers
classical-ml model-evaluation feature-engineering View full code for this problem
ML Problem & Solution
Stacked Ensembles Without the Leak
Stacking is four lines of sklearn and one subtle leak that makes validation look brilliant.
A freight marketplace books 2.8 million truckload shipments a quarter. A shipment is late when it is delivered more than 24 hours past the promised window, which happens to 11.4% of them, and the operations team can proactively intervene on about 1,200 of the roughly 31,000 daily shipments: re-tender to a backup carrier, warn the receiver, or pay for an expedite. Intervening on a shipment that would have arrived fine costs an average of $84 in wasted expedite fees and receiver goodwill. Missing one that arrives late costs an average of $610. So the model’s job is not to be accurate, it is to fill a fixed-size daily queue with the 1,200 shipments most likely to be late.
The data arrives in four shapes that do not sit in one table comfortably. There are 71 tabular features known at tender time: lane distance, weight, equipment type, tender lead time, pickup window width, month, day of week. There is free text: pickup and delivery instructions, address strings, and broker notes, median 34 tokens, which contain things like gate codes, appointment requirements and “receiver closes at 1400 sharp”. There is per-carrier history: the last 90 tenders for the assigned carrier as a sequence of outcomes and timestamps. And there is geography: origin and destination coordinates plus a lane-level congestion signal.
A single LightGBM on all of it flattened reaches PR-AUC 0.412. The flattening is where it loses. Text has to be hashed into a fixed-width block of columns before a tree model will take it, and a tree splitting on hash bucket 4,192 is not reading the gate code. The carrier sequence has to be collapsed into a mean and a count, which erases the difference between a carrier that has been late twice in ninety tenders and a carrier that has been late twice in the last four. Each collapse is a lossy projection chosen for the convenience of one model family, and the information destroyed is exactly the information that model family could not have used anyway.
The naive fix makes it worse in an instructive way. Train four models, one per view, and average their probabilities. That scores PR-AUC 0.398, below the single flattened LightGBM. The text model alone has PR-AUC 0.174 against a base rate of 0.114, so it is barely better than guessing on average, and averaging gives it a quarter of the vote. But that same weak model is the only one that identifies a specific 4.1% of shipments, the ones with appointment language in the instructions, where it is right and everything else is wrong. An average cannot express “listen to this model only here”. The problem is not which models to use, it is how to learn who to trust when.
The analogy: an ensemble average is a committee where everyone gets one vote regardless of expertise. Stacking is hiring a dispatcher who has read every forecaster’s track record, knows the text model is worth listening to only when the instructions mention a gate code, and knows the carrier-history model goes blind on carriers with fewer than ten prior tenders.
Formally: given a shipment’s tabular, text, carrier-history and geospatial views as known at tender time, predict the probability of delivery more than 24 hours late, optimising precision at the top 1,200 alerts per day, subject to a 120 ms p99 scoring budget, a weekly retrain, and a 14-day label lag.
Framing the Problem
This is binary classification scored as ranking at a fixed capacity. The distinction is not pedantic. Nothing downstream consumes a class label, because there is no threshold that produces exactly 1,200 alerts a day across a demand pattern that swings from 19,000 shipments on a Sunday to 41,000 on a Thursday. What ops consumes is a daily ranking, truncated at capacity. A model that improves accuracy while shuffling the top of the ranking is worthless here, and a model that improves nothing below the 96th percentile while sharpening the top 4% is the whole win.
The target is late = actual_delivery_ts > promised_window_end + 24h, and the label lag is what shapes the training regime. Delivery timestamps settle through carrier invoicing, with a median lag of 6 days and a p95 of 14 days. Anything more recent than 14 days is partially labeled, and partially labeled data is worse than no data: the shipments that have settled fastest are systematically the ones that went smoothly, so the most recent two weeks look 3.8 points less late than they will turn out to be. Training data is therefore always at least 14 days stale, and every validation split has to respect that same gap or it is measuring a future the model would not have had.
Constraints, in the order they bind:
- Latency is a sum, not a max. Every base model runs on every shipment, so the p99 budget of 120 ms is shared across all of them plus the meta-learner plus feature fetching. This is the constraint that capped the ensemble at five base models rather than the twelve that scored best offline.
- Each alert needs a reason string. Ops will not act on a bare score. “Carrier has been late on 3 of its last 5 tenders on this lane” is actionable; “ensemble score 0.71” gets ignored, and an ignored alert queue is a deleted alert queue.
- Weekly retrain with a 14-day embargo. The pipeline is retrained every Monday on data through the Monday 15 days prior.
- Base learner count is a budget, not a search space. Each additional base model multiplies training cost by its own fit time times the number of folds, and adds its own failure mode to the on-call surface.
The success metric is precision at the top 1,200 alerts per day, averaged across days rather than pooled. The guardrail metrics are PR-AUC over the whole ranking, because a model can be tuned to sharpen the top 1,200 while degrading everything below it and that shows up the first week capacity changes, Brier score, because ops uses the probability to choose between a cheap notification and an expensive expedite, and recall on shipments over $8,000 of freight value, which must not regress, because the cost matrix is far from uniform and a model that optimises average precision will happily trade a high-value miss for two cheap catches.
Precision at k has to be computed per day and then averaged, not by pooling all predictions and taking the global top `k` times the number of days. The pooled version is systematically optimistic here and the reason is structural: late rates vary by day of week from 8.1% on Sunday to 14.6% on Thursday, and a pooled top-k fills disproportionately from the high-base-rate days. Pooling gave 0.61 precision where the per-day average gave 0.52, and the per-day number is the one ops experiences, because the queue is drained every day regardless of whether it is a Thursday. The same trap appears in any capacity-constrained ranking problem with a periodic base rate, which is most of them.
Out of scope: the causal effect of the intervention itself (which needs an experiment, not a classifier), predicting the delay in hours rather than its occurrence, and multi-horizon scoring where the model reruns as the shipment moves. All three are separate systems.
Data and Features
Four view builders, each owning its own representation, each producing a matrix that its model family is actually good at.
# The four view builders. Each one is a projection chosen for its own model
# family, which is the point: the flattened single-table version had to pick
# one projection and lose the other three.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
TABULAR_NUMERIC = ["lane_miles", "weight_lbs", "tender_lead_hours",
"pickup_window_hours", "stops", "declared_value_usd",
"carrier_fleet_size", "lane_volume_28d"]
TABULAR_CATEGORICAL = ["equipment_type", "origin_state", "dest_state",
"broker_tier", "day_of_week", "month"]
TEXT_COLS = ["pickup_instructions", "delivery_instructions", "broker_notes"]
def build_tabular_view() -> ColumnTransformer:
"""71 columns after one-hot. LightGBM's home turf."""
return ColumnTransformer([
("num", "passthrough", TABULAR_NUMERIC),
("cat", OneHotEncoder(handle_unknown="ignore", min_frequency=200),
TABULAR_CATEGORICAL),
], remainder="drop", verbose_feature_names_out=False)
def build_text_view() -> Pipeline:
"""Word and character n-grams. Char grams catch 'DOCK 4B' and 'APPT REQ'
written eleven different ways by eleven different brokers."""
return Pipeline([
("tfidf", TfidfVectorizer(analyzer="word", ngram_range=(1, 2),
min_df=25, max_features=60000,
sublinear_tf=True, strip_accents="unicode")),
])
def concat_text(frame: pd.DataFrame) -> pd.Series:
"""One text field per shipment, with field markers so the model can tell
a gate code in the pickup instructions from one in the broker note."""
parts = []
for col in TEXT_COLS:
parts.append(col[:4].upper() + ": " + frame[col].fillna("").str.lower())
return pd.Series([" || ".join(row) for row in zip(*parts)],
index=frame.index)
The carrier-history view is where hand-rolled sequence summaries beat both a flattened mean and a recurrent model, and the reason is sample size per carrier rather than anything about the architecture.
# The carrier view. 28 summaries of the last 90 tenders, built so that
# "degrading right now" is separable from "mediocre for two years".
# A single 90-tender mean cannot express that difference and it is the
# difference the whole view exists for.
import numpy as np
import pandas as pd
HALF_LIVES = [3, 10, 30] # tenders, not days: a carrier's recency is in volume
def carrier_sequence_features(history: pd.DataFrame,
as_of: pd.Timestamp) -> dict:
"""history: one row per prior tender for this carrier, columns
[tender_ts, was_late, was_cancelled, lane_miles]. Strictly before as_of."""
past = history[history["tender_ts"] < as_of].sort_values("tender_ts")
past = past.tail(90)
late = past["was_late"].to_numpy(dtype=float)
out = {"carrier_n_prior": float(len(past))}
if len(past) == 0:
# Cold carrier. Sentinels, not zeros: zero late rate and unknown late
# rate are opposite claims and a tree will happily conflate them.
out.update({f"late_ewma_h{h}": np.nan for h in HALF_LIVES})
out.update({"late_rate_90": np.nan, "late_run_length": np.nan,
"late_trend": np.nan, "late_var": np.nan,
"cancel_rate_90": np.nan})
return out
idx = np.arange(len(late))[::-1] # 0 for the most recent tender
for h in HALF_LIVES:
w = 0.5 ** (idx / h)
out[f"late_ewma_h{h}"] = float((w * late).sum() / w.sum())
out["late_rate_90"] = float(late.mean())
out["late_var"] = float(late.var())
out["cancel_rate_90"] = float(past["was_cancelled"].mean())
# Consecutive lates ending at the most recent tender.
run = 0
for value in late[::-1]:
if value != 1.0:
break
run += 1
out["late_run_length"] = float(run)
recent, older = late[-15:], late[:-15]
out["late_trend"] = float(recent.mean() - older.mean()) if len(older) else 0.0
return out
The leakage specific to this problem
Three leaks, and they are ordered by how much fake performance they bought before we found them.
Group leakage through sibling rows, worth 0.074 PR-AUC of illusion. A single load is frequently tendered to two or three carriers in sequence after a rejection, producing multiple rows that share an origin, destination, commodity, receiver and promised window, differing only in carrier. The outcome is heavily determined by the shared part. Under random KFold, siblings land on both sides of the split and every base model learns to recognise the load rather than predict it. The fix is grouping on load_id, and then on lane_week_id as well, because the same receiver on the same lane in the same week has correlated outcomes through a shared cause, namely that the receiver’s dock was backed up all week.
As-of feature computation, worth 0.061 PR-AUC of illusion. carrier_ontime_rate_90d read from the carrier dimension table is a current snapshot, which includes the outcome of the shipment being predicted, plus every shipment after it. A carrier with 40 tenders in the window contributes 2.5% of its own label back into its own feature, which a gradient-boosted model finds immediately. Every history feature has to be computed strictly before tender_ts, which is why carrier_sequence_features takes an as_of and filters on it rather than accepting a pre-joined column.
Template text, worth 0.019 PR-AUC of illusion and a fairness problem. Broker notes are frequently copy-pasted templates. One broker’s 34,000 shipments share a byte-identical note, so the TF-IDF model learns a broker identity indicator disguised as a text feature, and it does so with the accuracy of a lookup table across a random split. The fix is to hash the normalised note and treat any hash appearing more than 200 times as a categorical broker template rather than as language, which removes the memorisation while keeping the genuine signal in the notes that are actually written per shipment.
Grouping correctly and then forgetting the time order. `GroupKFold` on `load_id` fixes sibling leakage and still trains on March to predict January, which for a problem with seasonal capacity cycles and a fuel surcharge that changes quarterly is a different kind of cheating. The two constraints compose: fold `i` must contain only loads strictly after fold `i-1`, groups must not straddle folds, and there must be a gap between the end of training and the start of validation at least as long as the label lag. Getting two of the three is the normal failure. We measured each: grouping alone was worth 0.074 of the correction, time ordering 0.019, and the embargo 0.031, and the embargo is the one that almost nobody implements because sklearn ships no splitter that does it.
# The splitter. Grouped, time-ordered, and embargoed. sklearn has the first
# two separately and neither with the third, so this is 30 lines you write once.
import numpy as np
import pandas as pd
def purged_group_time_splits(groups: np.ndarray, times: np.ndarray,
n_splits: int = 10,
embargo: pd.Timedelta = pd.Timedelta(days=14)):
"""Yield (train_idx, val_idx) with no group straddling a fold, folds in
time order, and an embargo gap equal to the label lag.
The embargo is the part people skip. Without it, training rows from the
day before validation starts had their labels settle after the validation
window opened, so the model is trained on information a live model would
not have had. Worth 0.031 PR-AUC of pure optimism on this problem.
"""
frame = pd.DataFrame({"group": groups, "time": pd.to_datetime(times)})
group_time = frame.groupby("group")["time"].min().sort_values()
blocks = np.array_split(group_time.index.to_numpy(), n_splits)
group_start = group_time.to_dict()
for i in range(1, n_splits):
val_groups = set(blocks[i])
val_start = min(group_start[g] for g in val_groups)
train_cutoff = val_start - embargo
train_groups = {g for block in blocks[:i] for g in block
if group_start[g] < train_cutoff}
train_idx = np.flatnonzero(frame["group"].isin(train_groups).to_numpy())
val_idx = np.flatnonzero(frame["group"].isin(val_groups).to_numpy())
if len(train_idx) and len(val_idx):
yield train_idx, val_idx
Grouping has to be done on the unit of outcome, and working out what that unit is takes a conversation with the business rather than a look at the schema. The row here is a tender; the outcome belongs to the load, because the receiver's dock, the promised window and the commodity are load-level facts and they determine most of the lateness. Then it belongs to the lane-week as well, because a receiver backed up all week produces correlated outcomes across different loads. Those two grouping keys overlap without nesting, which makes the correct group a connected component rather than a concatenated key: two rows are in the same group if they share either key. Concatenating them, which is the natural implementation, produces groups finer than the leakage, so sibling tenders of one load on different lane-weeks still straddle the split and the fix looks like it worked.
The Naive Baseline
Two baselines, because the interesting comparison is not against nothing. The floor is the rule ops already runs by hand. Above it sits the single flattened LightGBM, which is what most teams ship and what stacking has to beat to be worth its complexity.
# The two baselines. The heuristic is what ops does today; the single
# LightGBM is what stacking has to beat to justify five models instead of one.
import lightgbm as lgb
import numpy as np
from sklearn.metrics import average_precision_score
def ops_heuristic(frame) -> np.ndarray:
"""The rule currently in use, as a score so it can be ranked and compared."""
lead_risk = np.clip((6.0 - frame["tender_lead_hours"]) / 6.0, 0, 1)
carrier_risk = np.clip((0.85 - frame["carrier_ontime_rate_asof"]) / 0.15, 0, 1)
return 0.5 * lead_risk + 0.5 * carrier_risk
def single_model_baseline(X_train, y_train, X_val, y_val) -> dict:
"""Everything flattened into one matrix: tabular plus a 512-column hashed
text block plus the 90-tender mean. One projection, chosen for trees."""
model = lgb.LGBMClassifier(
n_estimators=1400, learning_rate=0.03, num_leaves=127,
min_child_samples=120, subsample=0.8, subsample_freq=1,
colsample_bytree=0.7, reg_lambda=5.0, random_state=17, n_jobs=-1)
model.fit(X_train, y_train, eval_set=[(X_val, y_val)],
eval_metric="average_precision",
callbacks=[lgb.early_stopping(100, verbose=False)])
p = model.predict_proba(X_val)[:, 1]
return {"name": "single LightGBM, flattened",
"pr_auc": float(average_precision_score(y_val, p)),
"n_features": int(X_train.shape[1])}
def precision_at_daily_k(y_true, scores, days, k: int = 1200) -> float:
"""Per-day top-k precision, averaged over days. NOT pooled: late rates
swing from 8.1% on Sunday to 14.6% on Thursday, and pooling fills the
queue from the busy days, which reads 9 points optimistic."""
frame = np.rec.fromarrays([days, scores, y_true],
names="day,score,label")
precisions = []
for day in np.unique(frame.day):
block = frame[frame.day == day]
take = block[np.argsort(-block.score)][:k]
if len(take):
precisions.append(take.label.mean())
return float(np.mean(precisions))
Numbers on the last three embargoed validation folds, 604,000 shipments, 11.4% late:
- Ops heuristic: precision at 1,200 per day 0.19, PR-AUC 0.171.
- Single flattened
LightGBM: precision at 1,200 per day 0.34, PR-AUC 0.412, Brier 0.0912. - Naive average of four per-view models: precision at 1,200 per day 0.33, PR-AUC 0.398.
That third number is the useful one. Four specialised models, each trained on the representation it is good at, averaged, lose to one model on a lossy flattened matrix. The specialisation was real and the averaging threw it away, which is the gap stacking exists to close.
The naive average losing to the single model is not an argument against multiple views, it is the argument for learning the combination. An average assigns weight `1/M` to every model unconditionally, which is the correct combination rule only when the models are equally accurate and their errors are equally correlated with each other, and here they are neither: standalone PR-AUC ranges from 0.174 to 0.412 across the four, a factor of 2.4. The weak text model deserves a small unconditional weight and a large weight on the 4.1% of shipments containing appointment language, and no fixed-weight rule can express that sentence. Stacking's entire value is that the combination rule is itself learned from data.
The Solution
Stacked generalisation, from Wolpert’s 1992 paper of that name, is a two-level model. Level 1 is a set of base learners, each producing a prediction. Level 2 is a meta-learner whose input features are those predictions and whose target is the same label. The meta-learner does not see the raw data, or sees only a small slice of it, and its job is exclusively to learn who to trust when.
The analogy that makes the mechanism obvious: level 2 is a hiring manager reading five forecasters’ resumes, where each resume is the forecaster’s prediction on a case the manager already knows the answer to. The entire correctness of the method hinges on the resume being honest, which means every level-1 prediction the meta-learner trains on must come from a model that had never seen that row. Get that wrong and the manager hires the forecaster who memorised the answer key.
Choosing base learners for decorrelated errors, not for accuracy
The wrong way to pick base models is to try twenty and keep the five with the best standalone scores, which reliably produces five gradient-boosted trees with different seeds that agree with each other 96% of the time and contribute nothing beyond the first one. What a meta-learner can exploit is disagreement that is informative, and the quantity to look at is the correlation between models’ errors rather than their individual accuracy.
# Base learner definitions. Deliberately different families on deliberately
# different views, because the meta-learner can only exploit disagreement.
import lightgbm as lgb
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
def base_learners() -> dict:
"""Five models, five views, four model families. Runtime in the comment
is the p50 per-shipment scoring cost measured on the serving host."""
return {
# 6.1 ms. Strongest single model, and the one everything else must
# disagree with usefully.
"lgb_tabular": lgb.LGBMClassifier(
n_estimators=1200, learning_rate=0.03, num_leaves=127,
min_child_samples=120, colsample_bytree=0.7, subsample=0.8,
subsample_freq=1, reg_lambda=5.0, random_state=17, n_jobs=4),
# 2.4 ms. Weakest standalone, lowest error correlation, second largest
# marginal contribution. This is the whole thesis of the section.
"lr_text": LogisticRegression(
penalty="l2", C=0.5, solver="liblinear", max_iter=2000),
# 3.8 ms. Sees the carrier trajectory, which the tabular view flattens
# into a single 90-tender mean.
"lgb_carrier": lgb.LGBMClassifier(
n_estimators=600, learning_rate=0.05, num_leaves=63,
min_child_samples=200, reg_lambda=2.0, random_state=17, n_jobs=4),
# 11.3 ms. Lane-level base rate with neighbourhood smoothing. Weak
# alone, but its errors are geographic where the others' are not.
"knn_lane": KNeighborsClassifier(
n_neighbors=250, weights="distance", metric="euclidean", n_jobs=4),
# 4.9 ms. A dense model on the same tabular features plus a 64-dim SVD
# of the text. Included for family diversity, not for its score.
"mlp_dense": Pipeline([
("scale", StandardScaler()),
("mlp", MLPClassifier(hidden_layer_sizes=(128, 64), alpha=3e-4,
batch_size=1024, learning_rate_init=1e-3,
early_stopping=True, n_iter_no_change=8,
max_iter=120, random_state=17))]),
}
Standalone performance and error decorrelation on the out-of-fold matrix, where the error is the signed residual y - p:
| Base model | Standalone PR-AUC | Mean error correlation with others | Marginal PR-AUC if removed |
|---|---|---|---|
lgb_tabular |
0.412 | 0.58 | 0.463, loses 0.045 |
lr_text |
0.174 | 0.24 | 0.481, loses 0.027 |
lgb_carrier |
0.341 | 0.52 | 0.492, loses 0.016 |
knn_lane |
0.298 | 0.39 | 0.494, loses 0.014 |
mlp_dense |
0.389 | 0.71 | 0.502, loses 0.006 |
Read that table by column rather than by row. lr_text has the worst standalone score by a factor of 2.4 and the second-largest marginal contribution, because its error correlation with the rest is 0.24 against mlp_dense’s 0.71. mlp_dense scores nearly as well as the best model standalone and contributes almost nothing, because it is a differently parameterised function fitted to substantially the same information. A sixth base model, a second LightGBM on the tabular view with a different seed and num_leaves, scored 0.408 standalone, correlated at 0.94, and contributed 0.001. We dropped it.
Generating out-of-fold predictions correctly
This is the part that fails silently. The meta-learner’s training features must be predictions on rows the producing model never saw, which means one pass of cross-validation per base model, with the predictions written back into the validation rows’ slots.
# The core of stacking. Every cell in the returned matrix is a prediction made
# by a model fitted on folds that excluded that row. Get this wrong and the
# ensemble looks better in validation while being worse in production, which
# is the worst possible failure direction.
import numpy as np
import pandas as pd
def generate_oof_matrix(views: dict, y: np.ndarray, groups: np.ndarray,
times: np.ndarray, learners: dict,
n_splits: int = 10) -> tuple:
"""views: {learner_name: feature matrix for that learner's view}.
Returns (oof, fitted_full) where oof is (n_rows, n_learners) and
fitted_full holds each learner refitted on all training data for serving.
"""
names = list(learners)
oof = np.full((len(y), len(names)), np.nan, dtype=np.float64)
folds = list(purged_group_time_splits(groups, times, n_splits=n_splits))
for train_idx, val_idx in folds:
for j, name in enumerate(names):
X = views[name]
model = clone_learner(learners[name])
model.fit(X[train_idx], y[train_idx])
oof[val_idx, j] = model.predict_proba(X[val_idx])[:, 1]
# Rows never in any validation fold (the first time block, and rows
# embargoed out) stay NaN and are dropped from meta training. Imputing
# them with a full-data prediction reintroduces the leak through the
# back door, which is a mistake worth naming because it looks tidy.
usable = ~np.isnan(oof).any(axis=1)
fitted_full = {}
for name in names:
model = clone_learner(learners[name])
model.fit(views[name][usable], y[usable])
fitted_full[name] = model
return oof[usable], usable, fitted_full
def clone_learner(estimator):
"""sklearn clone, kept behind a function so LightGBM boosters and
Pipelines are handled identically at the call site."""
from sklearn.base import clone
return clone(estimator)
Two details in that function are the difference between stacking that works and stacking that reads well and fails.
The first is the NaN handling. Rows in the earliest time block are never in a validation fold, because there is nothing before them to train on, and rows inside the embargo window are excluded by construction. The tempting tidy fix is to fill those cells with predictions from a model fitted on everything. That reintroduces exactly the leak the whole function exists to prevent, on a minority of rows, which is worse than doing it everywhere because the resulting model is subtly rather than obviously broken. Drop the rows.
The second is the distribution mismatch between training and serving, which is real and almost never mentioned. The meta-learner is trained on predictions from base models fitted on roughly 80% of the data, while at serving time the predictions come from base models fitted on 100%. A model fitted on more data is sharper: the mean standard deviation of lgb_tabular’s predictions rose 4.1% between the fold-fitted and full-fitted versions, so the meta-learner’s coefficients are calibrated for slightly flatter inputs than it receives. The principled fix is to serve the bagged fold models and average them, which costs 10 times the inference. The cheap fix, which is what we shipped, is to refit the meta-learner’s intercept and a single global temperature on a held-out slice scored by the full-fitted base models, recovering 0.004 PR-AUC for about 40 lines of code.
The canonical stacking bug is fitting base models on the full training set, predicting on that same training set, and training the meta-learner on those predictions. It is what you get if you write the obvious code, it runs, and it produces a model whose validation score goes up. The mechanism: an overfitted base model's in-sample predictions are nearly perfect, so the meta-learner learns "trust `lgb_tabular` completely" with a coefficient around 9, which is the correct response to the resume it was shown. At serving time that base model is merely good, the meta-learner amplifies its errors by a factor of nine, and the ensemble scores below its own worst base model. We reproduced it deliberately: the leaky version reported validation PR-AUC 0.661 and scored 0.379 on the following month, below the single-model baseline of 0.412. A stacking result that beats the best base model by more than about 0.10 PR-AUC is a leak until proven otherwise.
The meta-learner: why a regularized logistic regression on logits
The meta-learner has five features and 2.1 million usable rows, which is an absurdly favourable ratio, and the instinct is to spend it on something expressive. That instinct is wrong here, and the reason is not the usual hand-waving about overfitting.
# The meta-learner. Logits rather than probabilities, non-negative weights,
# and an isotonic calibrator on the final output only.
import numpy as np
from scipy.optimize import nnls
from sklearn.isotonic import IsotonicRegression
from sklearn.linear_model import LogisticRegression
def to_logit(p: np.ndarray, eps: float = 1e-6) -> np.ndarray:
"""Probabilities are the wrong scale for a linear combiner. A base model
at 0.999 and one at 0.95 differ by 0.049 in probability and by 3.0 in
logit, and the logit gap is the one that reflects evidence."""
p = np.clip(p, eps, 1.0 - eps)
return np.log(p / (1.0 - p))
def fit_meta(oof: np.ndarray, y: np.ndarray, restack: np.ndarray = None,
C: float = 0.1, non_negative: bool = True):
"""L2 logistic regression on base logits, optionally with a handful of
regime features so the weighting can be conditional.
non_negative follows Breiman's 1996 recommendation for stacked
regressions. It costs 0.004 PR-AUC and takes retrain-to-retrain weight
cosine similarity from 0.71 to 0.94, which is the trade we wanted: a
weight vector that flips sign between Mondays is unexplainable to ops.
"""
Z = to_logit(oof)
if non_negative:
# Standardise the columns before the solve. NNLS on raw logits is
# badly conditioned when the base models are correlated, and its
# response to collinearity is to zero all but one column, which is a
# sparse answer to a question about blending.
centre, scale = Z.mean(axis=0), np.where(Z.std(axis=0) > 0,
Z.std(axis=0), 1.0)
Zs = (Z - centre) / scale
w, _ = nnls(Zs, y.astype(float) - y.mean())
# Only the direction carries information, since the logistic
# regression below fits its own slope. Leaving the raw NNLS magnitude
# in place puts the combined score on a different scale from the
# standardised restack features, and a shared L2 penalty then drops
# the base score in favour of them: worth 0.016 PR-AUC.
w = w / np.linalg.norm(w)
features = (Zs @ w).reshape(-1, 1)
else:
centre = scale = w = None
features = Z
if restack is not None:
features = np.hstack([features, restack])
meta = LogisticRegression(penalty="l2", C=C, solver="lbfgs", max_iter=2000)
meta.fit(features, y)
return {"meta": meta, "nnls_weights": w, "non_negative": non_negative,
"centre": centre, "scale": scale}
def calibrate_final(p_raw: np.ndarray, y: np.ndarray) -> IsotonicRegression:
"""Calibrate the ensemble output, not the base models. The meta-learner
reweights logits and is free to be miscalibrated as long as the ranking
is right; ops reads the probability, so the last step must be honest.
Brier 0.0912 to 0.0784 on this problem."""
iso = IsotonicRegression(out_of_bounds="clip", y_min=0.0, y_max=1.0)
iso.fit(p_raw, y)
return iso
Three choices in there are worth their own justification.
Logits rather than probabilities. A linear combiner on probabilities can only express a weighted average, and probabilities compress exactly where the decisions are. Two base models at 0.95 and 0.999 differ by 0.049 on the probability scale and by 3.0 on the logit scale, and the logit gap is the one that reflects how much evidence each model thinks it has. Switching the meta features from probabilities to clipped logits was worth 0.014 PR-AUC, which is more than two of the five base models contribute.
Non-negative weights. Breiman’s 1996 paper on stacked regressions found that constraining the combination weights to be non-negative was essential to making stacking work reliably, and the reason holds here. Unconstrained, the meta-learner assigned knn_lane a coefficient of -0.31 in one retrain and +0.44 in the next, because when two base models are correlated at 0.39 the loss surface is nearly flat along their difference and the optimum wanders. A negative weight is not incoherent, it means a model is usefully wrong in a correctable direction, but it is unstable across refits and unexplainable in a reason string. The constraint cost 0.004 PR-AUC and took the retrain-to-retrain weight cosine similarity from 0.71 to 0.94.
A linear meta-learner rather than a tree. A LightGBM on the five meta features scored 0.006 better under naive cross-validation and 0.005 worse under nested cross-validation, because it was fitting the fold structure of the out-of-fold matrix itself. Predictions in fold 3 come from a model trained on folds 1 and 2 and are systematically flatter than predictions in fold 9, which came from a model trained on eight folds, and a tree with enough capacity discovers that gradient and treats it as signal. A linear model on logits cannot represent it.
Restacking: original features at level 2, and where it stops helping
Pure stacking gives the meta-learner nothing but base predictions, so the combination weights are global. Restacking appends original features so the weighting can be conditional, which is how “trust the text model on appointment lanes” becomes expressible.
The size of the restack set matters more than which features are in it. We tested three configurations on nested cross-validation:
| Restack configuration | Meta features | Nested PR-AUC | Weight stability |
|---|---|---|---|
| None, pure stacking | 5 | 0.497 | 0.96 |
| Six regime features | 11 | 0.508 | 0.94 |
| All 71 tabular features | 76 | 0.499 | 0.68 |
The six are tender_lead_hours, lane_miles bucketed to five levels, equipment_type, month, carrier_n_prior, and a binary has_appointment_language derived from the text. Every one of them is a feature that changes which model should be trusted, not a feature that predicts lateness directly, and that is the selection rule. With all 71 features the meta-learner starts re-solving the level-1 problem on a single linear model with no access to the interactions LightGBM found, and it loses 0.009.
The design decision that mattered most was not in the model at all: it was the embargo in the fold splitter. Every other choice in this post is worth between 0.004 and 0.027 PR-AUC of genuine improvement. The embargo was worth 0.031 PR-AUC of honesty, which is the difference between a number you can plan capacity against and a number that quietly disappears in the first month of production. Stacking amplifies every validation flaw rather than revealing it, because the meta-learner is explicitly trained to exploit whatever makes a base prediction look good on the validation rows. If those rows are contaminated, the meta-learner finds the contamination and weights it up. A leaky split hurts a single model and destroys a stacked one.
Evaluation and Metrics
Four measurements, answering four questions. Per-day precision at capacity decides whether to ship. PR-AUC checks the whole ranking did not degrade below the queue. Brier and reliability check the probability means something. And nested cross-validation checks whether the first three numbers are real.
Nested cross-validation is not optional for stacking. The out-of-fold matrix is produced by cross-validation, and if the meta-learner’s hyperparameters are then selected by scoring on that same matrix, the selection has seen every row’s validation prediction. The outer loop must evaluate the entire procedure, out-of-fold generation included, on data untouched by any part of it.
# Nested CV over the whole stacking procedure. The outer loop refits the base
# models, regenerates the OOF matrix, and selects the meta hyperparameters
# from scratch on each outer training block. Anything less measures the
# procedure's ability to describe the folds it was built on.
import numpy as np
from sklearn.metrics import average_precision_score, brier_score_loss
def nested_stacking_score(views, y, groups, times, learners,
c_grid=(1.0, 0.3, 0.1, 0.03), n_outer: int = 3,
n_inner: int = 10) -> dict:
outer = list(purged_group_time_splits(groups, times, n_splits=n_outer + 1))
rows = []
for tr, te in outer:
sub = {k: v[tr] for k, v in views.items()}
oof, usable, fitted = generate_oof_matrix(
sub, y[tr], groups[tr], times[tr], learners, n_splits=n_inner)
y_meta = y[tr][usable]
best = None
for c in c_grid:
inner = purged_group_time_splits(
groups[tr][usable], times[tr][usable], n_splits=4)
scores = []
for itr, ite in inner:
m = fit_meta(oof[itr], y_meta[itr], C=c)
scores.append(average_precision_score(
y_meta[ite], predict_meta(m, oof[ite])))
mean = float(np.mean(scores))
if best is None or mean > best[1]:
best = (c, mean)
final = fit_meta(oof, y_meta, C=best[0])
test_base = np.column_stack([
fitted[name].predict_proba(views[name][te])[:, 1]
for name in learners])
p = predict_meta(final, test_base)
rows.append({
"C": best[0],
"pr_auc": float(average_precision_score(y[te], p)),
"brier": float(brier_score_loss(y[te], p)),
})
return {"folds": rows,
"pr_auc": float(np.mean([r["pr_auc"] for r in rows])),
"brier": float(np.mean([r["brier"] for r in rows]))}
def predict_meta(fitted_meta, base_probs: np.ndarray,
restack: np.ndarray = None) -> np.ndarray:
Z = to_logit(base_probs)
if fitted_meta["non_negative"]:
Zs = (Z - fitted_meta["centre"]) / fitted_meta["scale"]
features = (Zs @ fitted_meta["nnls_weights"]).reshape(-1, 1)
else:
features = Z
if restack is not None:
features = np.hstack([features, restack])
return fitted_meta["meta"].predict_proba(features)[:, 1]
The gap between naive and nested evaluation on this problem was 0.023 PR-AUC, 0.531 against 0.508. That is not a rounding error and it is entirely attributable to selecting the meta-learner’s regularisation on the same out-of-fold matrix it was trained on.
Baseline against solution, three embargoed outer folds, 604,000 shipments:
| Configuration | PR-AUC | Precision at 1,200 per day | Brier | Recall on loads over $8k | Wasted interventions per day |
|---|---|---|---|---|---|
| Ops heuristic | 0.171 | 0.19 | n/a | 0.14 | 972 |
| Single flattened LightGBM | 0.412 | 0.34 | 0.0912 | 0.31 | 792 |
| Naive average of 4 views | 0.398 | 0.33 | 0.1105 | 0.30 | 804 |
| Stacked, probabilities, no restack | 0.483 | 0.44 | 0.0869 | 0.39 | 672 |
| Stacked, logits, no restack | 0.497 | 0.46 | 0.0841 | 0.41 | 648 |
| Stacked, logits, 6 restack features | 0.508 | 0.48 | 0.0822 | 0.43 | 624 |
| Stacked, plus final isotonic | 0.508 | 0.48 | 0.0784 | 0.43 | 624 |
Three readings from that table are worth more than the headline. The jump from naive averaging at 0.398 to global stacking at 0.497 is a full 0.099 PR-AUC and involved adding zero new information, only learning the weights. The final isotonic step moves PR-AUC by nothing at all, because isotonic regression is monotone and monotone transforms cannot change a ranking, and it improves Brier by 0.0038, which is the entire point: it exists for the probability consumer, not the ranking consumer. And the single flattened model beats the naive average, which is the result that convinces a sceptical reviewer that the combination rule is where the value is.
The number that catches a silent regression is **per-base-model out-of-fold PR-AUC and meta weight, tracked individually**, not the ensemble metric. An ensemble is a redundancy mechanism, and redundancy hides failures: when the text feature service started returning empty strings for 18% of shipments after an upstream schema change, ensemble PR-AUC fell from 0.508 to 0.501, which is inside the week-to-week noise band of 0.009 and fired no alert. What moved unmistakably was `lr_text`'s own out-of-fold PR-AUC, from 0.174 to 0.121, and its non-negative weight, from 0.31 to 0.12. We now alert on any base model whose standalone out-of-fold PR-AUC drops more than 15% relative or whose weight moves more than 0.10 absolute between retrains. Both fire days before the ensemble metric would, and on one occasion the ensemble metric never moved at all.
Common Pitfalls and Failure Modes
| Pitfall | Why It Happens | How to Detect | How to Fix |
|---|---|---|---|
| Meta-learner trained on in-fold base predictions | It is what the obvious code does, and it runs without error | Validation score jumps more than 0.10 PR-AUC over the best base model; meta coefficient on one base model above about 5 | Generate the level-1 matrix strictly out of fold; drop rows that no fold could score rather than imputing them |
| Base models all from one family | Selected by standalone score, which favours whatever family suits the data | Pairwise error correlation above 0.9; marginal contribution of the last model under 0.005 | Select on error decorrelation; require each addition to change nested PR-AUC by a stated minimum |
| Naive CV used to tune the meta-learner | The out-of-fold matrix is sitting right there and looks like a clean validation set | Naive minus nested gap above about 0.01 PR-AUC | Nested CV with the outer loop regenerating the whole level-1 matrix |
| Group leakage through sibling rows | Multiple tenders of one load share everything but the carrier | Base model validation score far above its production score; near-duplicate rows across the split | GroupKFold on the true unit of outcome, here load_id and lane_week_id, not on the row |
| No embargo between train and validation | No sklearn splitter implements it, so it has to be written | Labels in the last lag days of training settled after validation opened |
Gap of at least the label lag between training end and validation start |
| Meta features on the probability scale | Probabilities are the natural output, so nobody converts them | A base model saturating near 0 or 1 dominating the combination | Clipped logits, which makes the combination linear in evidence rather than in probability |
| Unstable meta weights across retrains | Correlated base models leave the loss surface flat along their difference | Weight vector cosine similarity below about 0.9 between consecutive retrains | Constrain weights to be non-negative and raise the L2 penalty; drop the more correlated of the pair |
| Serving-time base models sharper than training-time ones | Level 2 trains on fold-fitted predictions and serves on full-fitted ones | Mean prediction standard deviation differs between the two by more than a few percent | Refit the meta intercept and one global temperature on a held-out slice scored by the full-fitted base models, or bag the fold models at serve time |
The most common beginner mistake on this exact problem is reaching for `StackingClassifier` and assuming the leak is handled. It is: sklearn's implementation does generate the level-1 matrix by internal cross-validation, and that part is correct. What it cannot know is the shape of your leakage. Its `cv` parameter defaults to a stratified 5-fold with no groups and no time ordering, so on this data it splits sibling tenders of the same load across the boundary and trains on March to predict January. The result is a technically leak-free stack over a thoroughly contaminated split, which reported 0.589 validation PR-AUC against a true 0.508. Pass an explicit splitter, and if your leakage is grouped and temporal and embargoed, you will be passing a splitter you wrote, because none exists.
Scaling and Productionizing
Stacking multiplies two costs that a single model pays once, and the multipliers are different, which is worth knowing before committing.
Training cost multiplies by folds. With M base models and F folds, a retrain is M * F fits for the level-1 matrix plus M fits on the full data for serving, plus the nested outer loop if you are re-validating.
Level-1 matrix, 5 models x 10 folds 50 fits, 2.1M rows, 32 cores = 3 h 41 min
Full refits for serving, 5 models 5 fits on 2.1M rows = 27 min
Meta-learner, 11 features x 2.1M rows L2 logistic, lbfgs = 8 s
NNLS weight solve 5 x 2.1M design matrix = 1.4 s
Isotonic calibrator, held-out slice 210k rows = 3 s
Nested CV, 3 outer x 10 inner full procedure, 3 times = 11 h 20 min
Weekly pipeline, no nested CV level-1 plus refits plus meta = 4 h 09 min
Served artifact, 5 models plus meta LightGBM trees dominate = 41 MB
Per-shipment inference, 5 models 6.1 + 2.4 + 3.8 + 11.3 + 4.9 = 28.5 ms p50
Per-shipment inference p99 knn_lane tail dominates = 96 ms
Nested cross-validation at 11 hours 20 minutes is not a weekly cost. It runs when the ensemble’s composition changes, which is a handful of times a year, and the weekly pipeline uses the last validated configuration. Conflating the two is how teams conclude stacking is operationally impossible.
Inference cost is a sum, and one model sets the tail. 28.5 ms p50 across five models is comfortable inside a 120 ms budget, but the p99 of 96 ms is almost entirely knn_lane, whose 250-neighbour search degrades badly on dense lanes. Replacing the exact search with an HNSW index over the lane embedding took its p99 from 71 ms to 9 ms at a cost of 0.002 PR-AUC, which is the kind of trade that only becomes visible once you measure per-base-model latency rather than ensemble latency.
The text vocabulary must be pinned across retrains. This is the same class of bug as component relabelling in a mixture model. TfidfVectorizer refitted on a new week produces a different vocabulary and different IDF weights, so lr_text’s output distribution shifts even when its accuracy does not, and the meta-learner’s weight for it was fitted against the old distribution. We pin the vocabulary and IDF vector for a quarter, refit only the logistic regression weekly, and rebuild the vocabulary on a deliberate cadence with a full nested re-validation. Skipping this cost 0.011 PR-AUC in the second week after a vocabulary rebuild, recovered only at the following retrain.
Retrain cadence is set by base model decay, not ensemble decay. Frozen for four weeks, ensemble PR-AUC decayed 0.508, 0.504, 0.496, 0.481. The decomposition is more useful than the total: lgb_carrier decayed fastest, from 0.341 to 0.302, because carrier behaviour genuinely changes month to month, while knn_lane barely moved. If retraining everything weekly were expensive we would retrain lgb_carrier weekly and the rest monthly, which is available precisely because the models are separable.
The operational compensation for stacking's cost is that the base models are separable, and almost nobody uses it. A single model is one artifact with one retrain cadence set by whichever of its inputs drifts fastest. A stack is five artifacts whose decay rates are individually measurable: `lgb_carrier` lost 0.039 PR-AUC over four frozen weeks and `knn_lane` lost 0.004, so the honest cadence is weekly for the first and monthly for the rest. The same separability is what lets one base model's serving cost be optimised without touching the others, which is how `knn_lane`'s p99 went from 71 ms to 9 ms for 0.002 PR-AUC. The five-model ensemble costs five times as much to train and gives you five independently tunable dials in exchange, and the ensemble's aggregate metrics will never tell you which dial to turn.
The monitoring signal for silent degradation is the triple of per-base standalone out-of-fold PR-AUC, per-base meta weight, and the share of alerts whose top contributing base model changed from the previous week. The first two catch a base model’s inputs breaking. The third catches something neither can: the ensemble producing the same quality of ranking through a different mechanism, which is usually the first visible symptom of a distribution shift in a view. Any base model losing 15% relative PR-AUC pages someone; a weight moving more than 0.10 absolute blocks the retrain from promoting.
The canonical production story of stacking is the Netflix Prize, and the honest lesson is in its ending. BellKor's Pragmatic Chaos won in 2009 with a blend of well over 100 models combined by a learned ensemble, and Netflix's own engineering blog later stated that they implemented two of the algorithms and never shipped the full blend, because the accuracy gain did not justify the engineering to bring it into production. That is the tradeoff in its purest form. The broader lineage is worth knowing: Wolpert's 1992 "Stacked Generalization" introduced the level-1 and level-2 structure and the out-of-fold requirement; Breiman's 1996 "Stacked Regressions" added the non-negativity constraint that makes the weights stable; van der Laan, Polley and Hubbard's 2007 Super Learner gave it the asymptotic guarantee that the stacked model performs at least as well as the best base learner in the library, which is why medical statistics adopted it. In Kaggle competitions multi-level stacks of dozens of models are routine, and the diminishing returns are steep: on this problem the first three base models delivered 0.085 of the 0.096 total improvement over the single model, and models six through twelve delivered 0.004 between them for six times the serving cost.
Alternative Approaches
| Approach | Nested PR-AUC | Train and serve cost | Interpretability | Best fit |
|---|---|---|---|---|
| Stacking, 5 models, logits, restacked | 0.508 | 4 h 09 min weekly, 28.5 ms per shipment | Moderate: per-base weights plus a reason string from the top contributor | Heterogeneous views no single family handles, and enough label volume to train level 2 |
| Simple average of base probabilities | 0.398 | 27 min weekly, 28.5 ms | Good: every model weighted equally by construction | Base models of genuinely similar accuracy and similar calibration |
| Rank averaging across base models | 0.471 | 27 min weekly, 28.5 ms | Good: no weights to explain | You need most of stacking’s gain with no level-2 training and no leak surface |
| Single LightGBM, everything flattened | 0.412 | 22 min weekly, 6.1 ms | Good: one SHAP decomposition | Latency-bound serving, or one view dominating the signal |
| Feature-union into one model | 0.437 | 51 min weekly, 9.4 ms | Moderate: one model, 60k sparse columns | Views that share a scale and a model family that tolerates sparsity |
| Boosting with base predictions as features | 0.494 | 4 h 22 min weekly, 31 ms | Poor: interactions between base predictions | Large label volume and no requirement for stable, explainable weights |
| One model per view with learned gating | 0.511 | 6 h 40 min weekly, 29 ms | Poor: the gate is itself a model | Genuinely disjoint expert regimes with enough data per regime |
What we shipped is the top row, and the deciding factor against the gating network in the last row was not the 0.003 PR-AUC it gave up. It was that the gate is a second model with its own drift, its own monitoring surface and its own failure mode, replacing a five-coefficient non-negative weight vector that ops can read. Rank averaging in the third row is the result worth internalising: it reaches 0.471 of the 0.508 with no level-2 model, no out-of-fold generation, and therefore no leak surface at all. If a team is shipping its first ensemble, rank averaging is the right first version, and stacking is the upgrade once the infrastructure for honest out-of-fold generation exists.
We would drop to the single flattened model immediately if the latency budget fell below about 40 ms, because four of the five base models would have to go and a two-model stack is 0.045 PR-AUC, barely more than the interpretability it costs. We would move to the gating network if the number of views grew past about eight, where a single global weight vector stops being expressive enough and the restack trick stops scaling.
Key Takeaways
- Out-of-fold generation is the method, not a detail of the method. The leaky version of this exact ensemble reported validation PR-AUC 0.661 and delivered 0.379, below the single-model baseline of 0.412. Stacking is the only technique where the standard implementation error makes validation look better, which is why a stack beating its best base model by more than about 0.10 should be treated as broken until proven otherwise.
- Select base models on error decorrelation, not standalone accuracy.
lr_texthad the worst standalone PR-AUC of the five at 0.174 and the second-largest marginal contribution at 0.027, because its mean error correlation with the others was 0.24.mlp_densescored 0.389 standalone and contributed 0.006 at a correlation of 0.71. - Combine logits, not probabilities. Probabilities compress precisely where the decisions are, so a linear combiner on them cannot distinguish 0.95 from 0.999. The switch was worth 0.014 PR-AUC, more than two base models contribute individually.
- Constrain the weights to be non-negative, as Breiman recommended in 1996. Unconstrained weights on correlated base models wander along a flat loss direction and flip sign between retrains. The constraint cost 0.004 PR-AUC and took weight cosine similarity across retrains from 0.71 to 0.94.
- Restack a handful of regime features, not the whole feature set. Six features that change which model to trust were worth 0.011. All 71 tabular features were worth -0.009, because the meta-learner starts re-solving level 1 with a linear model and no interactions.
- Nested cross-validation is mandatory once the meta-learner has hyperparameters. Selecting the meta regularisation on the out-of-fold matrix it was trained on was worth 0.023 PR-AUC of optimism, which is larger than the contribution of three of the five base models.
- Monitor base models individually, because the ensemble hides their failures. An 18% empty-text incident moved ensemble PR-AUC by 0.007, inside the noise band, while moving
lr_text’s standalone PR-AUC by 0.053 and its weight by 0.19. - The embargo is worth more than any modelling choice here. A 14-day gap between training end and validation start, matching the label lag, was worth 0.031 PR-AUC, and no sklearn splitter implements it.
The counter-intuitive lesson is that the worst base model earned its place and the second-best one did not. Everything about how ensembles are usually introduced, as a way to average away the errors of several good models, points toward assembling a roster of strong performers, and that is precisely the roster that produces a stack indistinguishable from its best member. The value in a stacked ensemble lives entirely in the disagreements, so the right question about a candidate base model is not how well it scores but which rows it is right about that nothing else is. A model with PR-AUC 0.174 that owns 4.1% of the data outright is a better addition than a model with PR-AUC 0.389 that agrees with the leader 71% of the time, and the table that tells you which is which is a correlation matrix, not a leaderboard.
Frequently Asked Questions
Q: Why not just use sklearn’s StackingClassifier and move on?
A: Use it, but pass it your own splitter. The implementation is correct about the thing people get wrong: it generates the level-1 matrix by internal cross-validation rather than in-sample. What it cannot infer is the structure of your leakage, and its default stratified 5-fold has no groups, no time ordering and no embargo. On this data those defaults split sibling tenders of the same load across the boundary and produced a technically leak-free stack over a contaminated split, reporting 0.589 against a true 0.508. If your leakage is grouped, temporal and embargoed, you will be writing the splitter yourself and handing it to cv.
Q: Why not just train one bigger model on all the features instead? A: We did, and it is the 0.412 baseline. The obstacle is not capacity, it is that every model family needs its own input representation and only one of them can be served by a single matrix. Trees are excellent on 71 dense tabular columns and poor on 60,000 sparse TF-IDF columns, where a split on one term’s presence is nearly always a low-information split. A feature union of both got to 0.437, which is real improvement and still 0.071 short of stacking, and the gap is the part that requires a model per representation.
Q: Why not gradient boosting on the base predictions as meta-features? A: It scored 0.494 against 0.508, and the reason it lost is specific and instructive. Out-of-fold predictions are not identically distributed across folds: fold 3’s predictions come from a model trained on two folds and fold 9’s from a model trained on eight, so later folds are systematically sharper. A tree with enough capacity discovers that gradient and treats it as signal, which is fitting the cross-validation scheme rather than the data. A linear model on logits cannot represent it. The general rule is that a meta-learner should be less expressive than you think you can afford.
Q: Why PR-AUC and precision at k rather than ROC-AUC? A: At an 11.4% positive rate, ROC-AUC is dominated by the model’s ability to rank the 88.6% of negatives among themselves, which no one downstream cares about. Moving 10,000 easy negatives from the 60th to the 20th percentile improves ROC-AUC measurably and changes the top 1,200 alerts not at all. PR-AUC weights the positive class, and precision at 1,200 per day is the literal experience of the ops team. We report ROC-AUC on the dashboard purely because it is stable enough week to week to be a useful sanity check, and we never make a decision on it.
Q: How many base models before it stops being worth it? A: On this problem, three. The first three delivered 0.085 of the total 0.096 improvement over the single model, models four and five delivered 0.011 between them, and models six through twelve, tested offline, delivered 0.004 for six times the serving cost. The stopping rule we use is a stated minimum: a candidate must add 0.005 nested PR-AUC to stay, measured with it removed rather than with it alone, and the removal test is the one that matters because a correlated model can look strong alone and add nothing.
Q: What breaks first in production?
A: A single base model’s input pipeline, and the ensemble hides it. This is the operational asymmetry of stacking: redundancy is the reason it is accurate and the reason its failures are invisible. When the text service began returning empty strings for 18% of shipments, ensemble PR-AUC moved 0.007, well inside the weekly noise band, while lr_text’s standalone out-of-fold PR-AUC moved 0.053. Monitor every base model as a model in its own right with its own alarm, and monitor the meta weights as a vector, because a weight reallocating is the ensemble telling you one of its inputs changed.
Interview Questions
Q: Explain why stacking requires out-of-fold predictions, and what specifically goes wrong without them.
Expected depth: Start from what the meta-learner is estimating: a mapping from base predictions to the label, which requires the base predictions to be distributed the way they will be at serving time. In-sample predictions from an overfitted base model are far sharper and far more accurate than its out-of-sample predictions, so the meta-learner estimates a relationship that does not exist outside the training set, typically assigning an enormous coefficient to whichever base model overfits hardest. Name the direction of the failure: validation score goes up, not down, because the validation rows were scored by a model that saw them. Then the mechanics of the fix: K folds, fit each base model on K-1, predict the held-out fold, assemble the matrix column by column, and note that rows no fold can legitimately score must be dropped rather than imputed. Strong answers mention the training-to-serving distribution mismatch that remains even when this is done correctly, because level 2 trains on predictions from models fitted on a fraction of the data and serves on models fitted on all of it, and name bagging the fold models or recalibrating the meta intercept as the two fixes.
Q: You have five candidate base models. Two have the best standalone AUC. How do you choose which to include?
Expected depth: Reject standalone score as the criterion and say why: the meta-learner’s achievable gain comes from the residual information one model has that the others do not, so the relevant statistic is the correlation between models’ errors, not their accuracies. Describe the measurement concretely: compute the signed residual y - p for each base model on the out-of-fold matrix, take the pairwise correlation, and prefer additions with low mean correlation to the incumbent set. Then insist on the ablation rather than the correlation alone, because correlation is pairwise and redundancy can be collective: measure nested cross-validated performance with the candidate removed, and require a stated minimum gain to keep it. Mention the diversity mechanisms available when the candidates are too similar, namely different model families, different feature views, different loss functions, and different resampling, and note that different random seeds on the same family and view is the one that reliably produces nothing. Bias-variance framing is welcome if it is specific: stacking reduces variance when base models are decorrelated and cannot reduce bias that all of them share.
Q: Your stacked model scores 0.66 in validation and 0.38 in production. Walk through the diagnosis. Expected depth: Recognise the signature immediately: a stack beating its best base model by a wide margin in validation and underperforming it in production is a leak in the level-1 matrix, not distribution shift. Give the ordered checks. First, confirm the level-1 predictions were generated out of fold, and check whether any rows were imputed with full-data predictions. Second, inspect the meta coefficients: a value far above the others indicates the meta-learner found a base model whose validation predictions were suspiciously good. Third, examine the splitter for group leakage, asking what the true unit of outcome is rather than what the row is, and for time ordering, and for an embargo against the label lag. Fourth, check whether the meta hyperparameters were selected on the same out-of-fold matrix, which produces a smaller but real optimism. Then describe the honest re-measurement: nested cross-validation where the outer loop regenerates everything, and a comparison of naive to nested as a diagnostic in its own right, since a gap above roughly 0.01 says the tuning was contaminated.
Q: Why constrain the meta-learner’s weights to be non-negative, and what does it cost? Expected depth: Cite Breiman’s 1996 stacked regressions result and give the mechanism rather than the citation alone. When two base models are correlated, the loss surface is nearly flat along the direction of their difference, so the unconstrained optimum is poorly determined and moves substantially between refits on similar data, producing coefficients that change sign. A negative weight is statistically legitimate, it means the model is wrong in a correctable direction, but it is fragile and it cannot be explained to a downstream consumer. Quantify the trade: a small accuracy cost against a large stability gain, with weight cosine similarity across retrains as the measurement. Mention the alternatives in order of increasing restriction: raising the L2 penalty, non-negativity, non-negativity plus a sum-to-one constraint which makes the combination a convex blend, and dropping the more correlated member of the pair, which is the fix that addresses the cause rather than the symptom.
Q: How do you evaluate a ranking model that feeds a fixed-capacity queue?
Expected depth: Start by rejecting threshold metrics: accuracy, F1 and any fixed-cutoff precision are undefined for a consumer that takes the top k regardless of score. Name precision at k with k equal to the operational capacity as the primary, and immediately raise the pooling subtlety: precision at k must be computed within each decision period and averaged, because pooling across periods with different base rates fills the queue from the high-rate periods and reads optimistic. Give the magnitude if you can, since a nine-point gap is the kind of thing an interviewer wants to hear is possible. Then the guardrails and why each exists: PR-AUC for the whole ranking so the model is not tuned to sharpen the top while degrading everything below the queue, a proper scoring rule such as Brier or log loss if any consumer reads the probability rather than the rank, recall on a high-cost subpopulation when the cost matrix is non-uniform, and a stability measure across retrains. Close on the economics: the queue size itself is a decision variable, so the deliverable is the precision-at-k curve across plausible capacities rather than a single number, and the point where marginal precision falls below the cost ratio of a false positive to a false negative is where capacity should actually be set.