Build a Bagging vs Boosting Comparison Pipeline for Tabular Data


classical-ml model-evaluation feature-engineering mlops
View full code for this problem

ML Problem & Solution

Bagging vs Boosting on Tabular Data

The gap people argue about is smaller than the variance of the experiment that measures it.

⏱ 27 min read 📐 Intermediate 🧩 Classical ML

A freight brokerage wants to flag shipments that will miss their promised delivery date, early enough that a dispatcher can re-tender the load or warn the customer. There are 2.8 million shipments in three years of history, 41 features per shipment, an 18.4% late rate, and a dispatch desk that can act on about 600 flags a day. The modelling question is a binary classifier and nobody disagrees about that.

What they disagree about is random forest versus gradient boosting, and they have been disagreeing for two quarters. Three people have run three benchmarks. The first found boosting ahead by 0.057 PR-AUC. The second found it ahead by 0.073. The third, who was the only one who split the data by lane and by time, found it ahead by 0.019 and then by 0.004 when she reran with a different seed. Two of those three benchmarks were run on the same feature matrix.

The naive reading is that someone made a mistake. The accurate reading is that all three are correct measurements of three different experiments, and none of them is a measurement of the thing being argued about. The difference between a bagging ensemble and a boosting ensemble on a given dataset is a real quantity, and on this dataset it is smaller than the spread produced by the tuning budget, the cross-validation protocol, and the random seed. The analogy: it is a stopwatch argument about two runners where one race was uphill, one was measured from a different starting line, and the timing gear has a half-second jitter. Buying a better stopwatch is not the fix.

So the deliverable is not a model. It is a harness, and the harness has to satisfy four conditions that no one of those three benchmarks satisfied at once. Both families see a bit-identical feature matrix, including identical categorical handling, because one-hot for the forest and native categoricals for the booster is a comparison of encodings wearing the costume of a comparison of algorithms. Both get an equal search budget, reported two ways, because 200 trials each and one hour each give different winners. The splits respect the grouped and time-ordered structure of shipments, because random K-fold on data where 14,000 lanes recur leaks lane-level outcome information and it does not leak it equally into the two families. And the output is a paired difference with an interval, not two point estimates, because the standard deviation of the single-split gap across seeds here is 0.021 and people were arguing about 0.010.

There is a second reason to build the harness rather than just picking the winner, and it is the more durable one. The ranking is not a fact about tabular data, it is a fact about a region of a parameter space, and the boundaries are close enough to reach. We found three sweeps along which the answer changes: tuning budget, training-set size, and label noise. Knowing where those crossovers sit is worth more than knowing which model won at one point, because the next dataset will be at a different point.

Given 2.8 million shipments with 41 features and a grouped, time-ordered structure, decide whether bagging or boosting better predicts late delivery, optimising for PR-AUC at a fixed capacity of 600 interventions per day, under an equal tuning budget, an identical feature matrix, and a paired evaluation whose confidence interval is narrower than the difference being claimed.

Framing the Problem

Binary classification, 18.4% positive, and the two families being compared are both ensembles of decision trees that differ only in how the trees are combined. That last point is worth making precisely because it is what makes the comparison tractable: bagging fits many deep trees independently on bootstrap resamples and averages them, which reduces variance; boosting fits many shallow trees sequentially, each on the residual errors of the ensemble so far, which reduces bias. Every behavioural difference in this post follows from that one structural difference, including both crossovers.

The target is delivered_at > promised_at + 4 hours, where the 4-hour grace period is the customer-facing tolerance already written into the contracts. Two details about the label matter more than the definition. It arrives late: the median delivery scan lands 6.2 days after tender, so at any moment the most recent week of data is unlabelled, which sets the embargo in the cross-validation scheme below. And it is noisy in a way that is not symmetric: about 3% of on-time deliveries are recorded late because the driver scanned at the gate rather than the dock, and a smaller number of genuinely late deliveries are recorded on time because a dispatcher backdated the scan. Label noise is not an abstraction in this problem, it is a measured 3% to 5%, which turns out to sit uncomfortably close to one of the crossovers.

Constraints, and two of them ended up mattering more than the accuracy comparison:

  • Capacity of 600 flags per day against roughly 3,100 daily shipments. The operating point is fixed, so any metric that averages over all thresholds is a proxy rather than the objective.
  • Per-shipment reason codes. The dispatcher UI shows why a shipment was flagged, which both families support through SHAP or per-tree attribution, so this does not discriminate. It does rule out anything without a per-feature attribution story.
  • 40 ms p99 scoring latency inside the tender workflow, and a hard memory ceiling on the serving box of 2 GB for the model artifact. This constraint eliminated one configuration outright and is the single most underrated line in the comparison.
  • Monthly retrain on the trailing 24 months, on CPU, inside a 6-hour window.
  • Equal engineering effort. Stated as a constraint because it is the one everyone violates: the family the team knows better gets tuned better, and that difference is larger than the algorithmic one.
Metric That Matters

The optimisation metric is **PR-AUC**, and the decision metric is **precision at 600 flags per day**, with the paired difference between families reported as a bootstrap interval rather than as two numbers. ROC-AUC is the wrong choice here and the reason is structural rather than aesthetic: at an 18.4% positive rate, ROC-AUC is dominated by how the model ranks the vast majority of non-late shipments against each other, and a model can gain 0.01 ROC-AUC by reordering shipments nobody will ever look at. Both families scored within 0.006 ROC-AUC of each other across every configuration we tried, including the ones whose PR-AUC differed by 0.09, so ROC-AUC would have reported "no difference" for the whole two quarters of argument. The guardrail metrics are **expected calibration error**, because the dispatcher UI displays a probability and a systematically overconfident model teaches the desk to ignore it, and **alert concentration**, defined as the share of daily flags going to a single lane, capped at 5% because a model that flags one troubled lane 600 times a day is technically accurate and operationally useless.

Out of scope: neural networks on tabular data, which is a genuinely interesting comparison and a different post; stacking the two families together, which we did try and which is covered in the alternatives table; and the intervention policy itself, which is what the dispatcher does with a flag.

Data and Features

41 features per shipment, drawn from four systems: the tender record, the carrier scorecard, the terminal telemetry, and a weather forecast service. The shape is 2,812,000 rows by 41 columns over 36 months, with 14,300 distinct lane_id values, 1,840 carriers and 62 origin terminals.

The features divide into four groups, and the divide is the leakage boundary:

  • Known at tender time, static: distance, promised transit days, equipment type, weight, volume, stop count, lane_id, carrier_id, day of week, hour of day, tender lead time.
  • Known at tender time, derived from history: carrier on-time rate, carrier-lane on-time rate, lane volatility, terminal dwell p90, carrier acceptance rate. Every one of these is a statistic over past shipments and every one of them is a leakage hazard.
  • Known at tender time, forecast: precipitation and temperature forecast at origin and destination for the delivery window, forecast issued at tender.
  • Known only after the fact, and therefore excluded: actual pickup scan delay, actual terminal dwell for this shipment, en-route exception codes. These were in the first feature set and they were worth an apparent 0.11 PR-AUC, all of it fictional.
# The feature build. The only interesting part is the expanding-window
# statistics, because computing a carrier's on-time rate over the whole
# history is the single most common way this exact problem leaks.
import numpy as np
import pandas as pd

HISTORY_KEYS = [
    ("carrier_id",),
    ("carrier_id", "lane_id"),
    ("origin_terminal",),
]

def expanding_ontime_rate(frame: pd.DataFrame, keys: tuple[str, ...],
                          prior_weight: float = 50.0) -> pd.Series:
    """On-time rate over shipments tendered STRICTLY BEFORE this one.

    Two things are load bearing. The shift(1) after sorting by tender time,
    which excludes the row's own outcome. And the shrinkage toward the global
    rate, because a carrier-lane pair with 2 prior shipments otherwise reports
    0.0 or 1.0, and 9,100 of the 14,300 lanes have fewer than 20 shipments in
    a 24-month window.
    """
    frame = frame.sort_values("tendered_at")
    grp = frame.groupby(list(keys), sort=False)["was_late"]
    # cumcount is the number of PRIOR rows in the group, and cumsum includes
    # the current row, so subtract it back out. Getting either of these off by
    # one is the whole leak.
    prior_n = grp.cumcount()
    prior_late = grp.cumsum() - frame["was_late"]
    global_rate = float(frame["was_late"].mean())
    rate = ((prior_n - prior_late) + prior_weight * (1.0 - global_rate)) / \
           (prior_n + prior_weight)
    return rate.reindex(frame.index)

def build_features(frame: pd.DataFrame) -> pd.DataFrame:
    out = frame.copy()
    for keys in HISTORY_KEYS:
        name = "ontime_" + "_".join(keys)
        out[name] = expanding_ontime_rate(out, keys)
    out["tender_lead_hours"] = (
        (out["pickup_window_start"] - out["tendered_at"])
        .dt.total_seconds() / 3600.0)
    out["promised_transit_days"] = (
        (out["promised_at"] - out["pickup_window_start"])
        .dt.total_seconds() / 86400.0)
    out["miles_per_promised_day"] = (
        out["distance_miles"] / out["promised_transit_days"].clip(lower=0.25))
    return out

The split, and why it changes the answer rather than just the number

Shipments are not independent draws. They recur on lanes, they cluster in time around weather events and peak season, and a carrier’s behaviour is autocorrelated for months. Random K-fold cross-validation on this data does three things at once, and the third is the one that breaks the comparison.

It leaks time, because a fold’s training set contains shipments from after its test set, and the world moves. It leaks lane identity, because a lane with 400 shipments has roughly 320 of them in every training fold, so the model can memorise lane_id rather than learn from lane features. And it leaks unequally between the two families. That last point is the one that turns a measurement error into a wrong conclusion: a boosting ensemble with 1,200 sequentially fitted trees can exploit a memorisable high-cardinality identifier far more thoroughly than a forest whose max_features="sqrt" sampling means any given tree usually cannot see it. Measured on this data, moving from random 5-fold to grouped-and-time-ordered folds cost boosting 0.063 PR-AUC and bagging 0.047, so the gap moved from 0.073 to 0.057. A quarter of the advantage people were arguing about was leakage that one family was better at exploiting.

# Grouped, time-ordered, embargoed splits. The embargo is the 6.2-day label
# lag: without it, the training set contains shipments whose outcome was not
# yet known when the test fold's shipments were tendered.
import numpy as np
import pandas as pd

def grouped_time_folds(frame: pd.DataFrame, n_folds: int = 5,
                       embargo_days: float = 7.0,
                       group_col: str = "lane_id"):
    """Expanding-window folds, ordered by tender time, with whole groups held
    out of training when they appear in test.

    Yields (train_idx, test_idx). Groups are excluded from TRAIN rather than
    from test, because the deployed model will see unseen lanes and the
    evaluation should reflect that, but it must not have learned this lane's
    outcomes from an overlapping period.
    """
    order = np.argsort(frame["tendered_at"].to_numpy())
    ordered = frame.iloc[order]
    bounds = np.linspace(0.4, 1.0, n_folds + 1)
    times = ordered["tendered_at"].to_numpy()
    for i in range(n_folds):
        t_start = times[int(bounds[i] * (len(times) - 1))]
        t_end = times[int(bounds[i + 1] * (len(times) - 1))]
        test_mask = (times >= t_start) & (times < t_end)
        embargo = np.timedelta64(int(embargo_days * 24), "h")
        train_mask = times < (t_start - embargo)
        test_groups = set(ordered[group_col].to_numpy()[test_mask].tolist())
        # Drop training rows whose group also appears in test AND whose window
        # is close enough that lane-level autocorrelation is the shortcut.
        recent = times >= (t_start - np.timedelta64(120, "D"))
        in_test_group = np.array([g in test_groups
                                  for g in ordered[group_col].to_numpy()])
        train_mask = train_mask & ~(recent & in_test_group)
        yield (order[train_mask], order[test_mask])
Common Pitfall

Target-encoding a high-cardinality categorical with a fit that sees the whole training set, then reporting a score computed on rows that fit touched. This is the leak that produced the second benchmark's 0.073 and it is almost invisible because the encoder really was "fitted only on train". The harm depends on where the reported number comes from, and the two cases are worth separating because they look nothing alike. If the reported metric comes from the model's own inner validation or from an early-stopping slice, those rows already carry their own outcomes inside the encoded feature and the score is inflated: measured here, +0.041 PR-AUC to the boosting model and +0.016 to the forest, which accounts for almost half of that benchmark's gap. If the outer test fold is genuinely clean, the same mistake shows up inverted, as worse held-out performance, because the model learned to trust a feature that is sharper in training than it will ever be in serving. Either way the damage is unequal between the families, which is what turns an inflated number into a wrongly ranked one. The fixes are known and not interchangeable: nest the encoder inside the fold, use out-of-fold encoding with its own inner split, or use CatBoost's ordered target statistics, which is the only one that addresses the problem inside the algorithm rather than around it.

Key Insight

The feature matrix has to be bit-identical for both families, and the place this quietly fails is categorical handling. LightGBM and CatBoost accept categorical columns natively and split on subsets of categories; scikit-learn's `RandomForestClassifier` does not, so somebody one-hot encodes for the forest and passes the raw categories to the booster. That is now a comparison of encoding schemes with the algorithms along for the ride, and on this data it is worth 0.034 PR-AUC to the booster on its own, which is 60% of the final reported gap. We resolved it by running the entire harness twice, once with ordinal encoding for both and once with one-hot for both, and reporting both rows. The honest framing is that native categorical support IS an advantage of the boosting implementations and it should be claimed as one, but it belongs on a separate line from "boosting reduces bias better than bagging reduces variance", because the first is a property of a library and the second is a property of an algorithm. Conflating them is how a team ends up believing something about gradient boosting that is actually true about LightGBM.

The Naive Baseline

Four baselines, and the important two are the last two, because they are what the two-quarter argument was actually about.

# The four baselines. The two default-configuration ensembles are the
# interesting ones: they are what almost every informal comparison reports,
# and the gap between them is not the gap between the families.
import numpy as np
from sklearn.dummy import DummyClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
import lightgbm as lgb

def prevalence_baseline(y_train: np.ndarray, X_test: np.ndarray) -> np.ndarray:
    """PR-AUC of a constant predictor equals the positive rate. Report it, so
    every later number has a floor that is not zero."""
    model = DummyClassifier(strategy="prior").fit(X_test[:1], y_train[:1])
    return np.full(len(X_test), float(y_train.mean()))

def logistic_baseline(X_tr, y_tr, X_te) -> np.ndarray:
    """Regularised logistic regression on scaled numerics plus one-hot. The
    real baseline for tabular problems, and it is not embarrassing here."""
    pipe = make_pipeline(StandardScaler(with_mean=False),
                         LogisticRegression(C=0.5, max_iter=2000,
                                            class_weight="balanced"))
    return pipe.fit(X_tr, y_tr).predict_proba(X_te)[:, 1]

def forest_default(X_tr, y_tr, X_te, seed: int = 17) -> np.ndarray:
    """sklearn defaults: 100 trees, unlimited depth, max_features='sqrt'."""
    model = RandomForestClassifier(n_estimators=100, n_jobs=-1,
                                   random_state=seed).fit(X_tr, y_tr)
    return model.predict_proba(X_te)[:, 1]

def booster_default(X_tr, y_tr, X_te, seed: int = 17) -> np.ndarray:
    """LightGBM defaults: 100 trees, 31 leaves, learning_rate 0.1."""
    model = lgb.LGBMClassifier(random_state=seed, n_jobs=-1,
                               verbosity=-1).fit(X_tr, y_tr)
    return model.predict_proba(X_te)[:, 1]

On the grouped, time-ordered, embargoed folds, averaged over 5 folds and 6 seeds:

  • Prevalence: PR-AUC 0.184 by definition.
  • Regularised logistic regression: PR-AUC 0.331, precision at 600 flags 0.394.
  • Single decision tree, depth 8: PR-AUC 0.298. Worse than the linear model, which is the standard and instructive result: one tree is a high-variance estimator and the ensembles exist to fix exactly that.
  • Random forest, defaults: PR-AUC 0.412, precision at 600 0.497.
  • LightGBM, defaults: PR-AUC 0.421, precision at 600 0.508.

The last two lines are the whole problem. A 0.009 difference, from two library defaults that share nothing methodologically, reported without an interval, is the evidence on which two quarters of architectural argument rested. The standard deviation of that difference across the 6 seeds was 0.021, so the measurement does not even establish its own sign.

Key Insight

The default-versus-default comparison is not a weak version of the real comparison, it is a measurement of something else entirely. `RandomForestClassifier()`'s defaults are close to a reasonable configuration for almost any tabular problem: 100 unlimited-depth trees with square-root feature sampling is a legitimate model, and the reason is structural rather than lucky, because bagging's variance reduction does not depend on getting the individual trees right. `LGBMClassifier()`'s defaults are a starting point for a search: 100 trees at learning rate 0.1 with 31 leaves is almost always either underfitted or overfitted for a given dataset, because boosting's bias reduction depends entirely on the interaction between the learning rate, the tree count and the leaf budget. So the default comparison measures how close each library's authors got to your dataset, which is a real and useful thing to know and is not what anyone thinks they are measuring. The numbers make the asymmetry concrete: tuning moved the forest from 0.412 to 0.451, an improvement of 0.039, and the booster from 0.421 to 0.508, an improvement of 0.087. Boosting has more than twice as much of its performance locked behind the search.

The Solution

Comparison harness from 2.8 million shipments through a leak-free feature build using expanding-window statistics, grouped and time-ordered folds with a seven-day embargo and lane holdout, one bit-identical feature matrix shared by both families, an equal search budget reported both trial-matched at 200 trials each and compute-matched at one hour each, five folds by six seeds of paired fits, a bootstrap interval on the paired PR-AUC difference, and a decision that weighs the 0.057 accuracy gap against a 4.1 gigabyte model artifact and a 3.1 millisecond scoring latency

The harness has four parts and none of them is a model.

Equal budget, and the two meanings of equal

Both families get the same Optuna study: same sampler, same number of trials, same objective (mean PR-AUC across the grouped folds), same feature matrix, same seed set. That is trial-matched budget and it is the comparison most papers report.

It is also not the comparison a team makes in practice, because the two families do not cost the same per trial. On this data a forest trial averaged 41 minutes and a LightGBM trial averaged 6.8 minutes, so 200 trials each is 137 hours against 23. Under compute-matched budget, one hour of search each, the forest gets 1 or 2 trials and the booster gets 8, and the booster’s advantage grows because it has more of its performance behind the search. Under 24 hours each, the forest gets 35 trials and the booster gets 211, and the gap widens from 0.057 to 0.069.

Report both. They answer different questions: trial-matched asks which algorithm is better, compute-matched asks which one you should use this week.

# The tuning harness. The only notable choices are the search spaces, which
# are asymmetric on purpose, and n_estimators being excluded from the forest's
# space for a reason given below.
import numpy as np
import optuna
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import average_precision_score
import lightgbm as lgb

def forest_space(trial: optuna.Trial) -> dict:
    """Four parameters. max_features is the one that matters; the sklearn
    default of 'sqrt' is often already near-optimal, which is the asymmetry
    at the centre of this post.

    n_estimators is deliberately absent. Bagging's error is monotone
    non-increasing in the number of trees, so there is no optimum to find:
    tuning it spends budget to discover 'more is better' and, worse, CV noise
    will sometimes pick a smaller value and make the model permanently worse.
    Fix it at the largest count the time and memory budget allows.
    """
    return {
        "max_features": trial.suggest_float("max_features", 0.05, 0.9),
        "min_samples_leaf": trial.suggest_int("min_samples_leaf", 1, 200,
                                              log=True),
        "max_depth": trial.suggest_int("max_depth", 6, 40),
        "class_weight": trial.suggest_categorical("class_weight",
                                                  [None, "balanced"]),
    }

def booster_space(trial: optuna.Trial) -> dict:
    """Eight parameters, and learning_rate is coupled to n_estimators, which
    is why early stopping carries the tree count instead of the search."""
    return {
        "learning_rate": trial.suggest_float("learning_rate", 0.01, 0.3,
                                             log=True),
        "num_leaves": trial.suggest_int("num_leaves", 15, 512, log=True),
        "min_child_samples": trial.suggest_int("min_child_samples", 5, 500,
                                               log=True),
        "subsample": trial.suggest_float("subsample", 0.5, 1.0),
        "subsample_freq": trial.suggest_int("subsample_freq", 0, 5),
        "colsample_bytree": trial.suggest_float("colsample_bytree", 0.3, 1.0),
        "reg_lambda": trial.suggest_float("reg_lambda", 1e-3, 30.0, log=True),
        "scale_pos_weight": trial.suggest_float("scale_pos_weight", 1.0, 6.0),
    }

def cv_score(make_model, params: dict, X, y, folds, early_stopping: bool,
             seed: int = 17) -> float:
    """Mean PR-AUC across folds. Early stopping, when used, splits a
    validation slice out of the TRAINING fold by time, never from the test
    fold, which is the most common way a boosting benchmark cheats."""
    scores = []
    for train_idx, test_idx in folds:
        model = make_model(params, seed)
        if early_stopping:
            cut = int(0.85 * len(train_idx))
            fit_idx, val_idx = train_idx[:cut], train_idx[cut:]
            model.fit(X[fit_idx], y[fit_idx],
                      eval_set=[(X[val_idx], y[val_idx])],
                      eval_metric="average_precision",
                      callbacks=[lgb.early_stopping(100, verbose=False)])
        else:
            model.fit(X[train_idx], y[train_idx])
        p = model.predict_proba(X[test_idx])[:, 1]
        scores.append(average_precision_score(y[test_idx], p))
    return float(np.mean(scores))

The paired difference, which is the actual output

Two point estimates cannot be compared. The quantity of interest is the difference, measured on the same folds with the same seeds, and its sampling distribution.

# The comparison itself. Paired over folds and seeds, then bootstrapped.
# Everything above this function exists to make this number mean something.
import numpy as np

def paired_deltas(scores_a: np.ndarray, scores_b: np.ndarray) -> np.ndarray:
    """Per-(fold, seed) differences. Pairing removes the fold-to-fold variance,
    which here is 4.6x larger than the difference being measured, so an
    unpaired comparison needs roughly 20 times the runs for the same power."""
    assert scores_a.shape == scores_b.shape
    return (scores_b - scores_a).ravel()

def bootstrap_interval(deltas: np.ndarray, n_boot: int = 10_000,
                       alpha: float = 0.05, seed: int = 17) -> dict:
    """Percentile bootstrap on the paired differences.

    Reported instead of a t-test because the folds are not independent: an
    expanding-window scheme shares training data between folds, which violates
    the independence assumption and makes a naive paired t-test
    anti-conservative. Nadeau and Bengio's corrected resampled t-test is the
    principled alternative and is implemented alongside for comparison.
    """
    rng = np.random.default_rng(seed)
    means = np.array([rng.choice(deltas, len(deltas), replace=True).mean()
                      for _ in range(n_boot)])
    return {
        "mean": float(deltas.mean()),
        "lo": float(np.quantile(means, alpha / 2)),
        "hi": float(np.quantile(means, 1 - alpha / 2)),
        "sd": float(deltas.std(ddof=1)),
        "p_b_wins": float((deltas > 0).mean()),
    }

def corrected_resampled_t(deltas: np.ndarray, n_train: int,
                          n_test: int) -> float:
    """Nadeau and Bengio 1999. The variance term is inflated by
    1/k + n_test/n_train to account for training-set overlap between folds.
    Without the correction, a repeated-CV t-test on overlapping folds reports
    significance for differences that do not replicate."""
    k = len(deltas)
    mean = float(deltas.mean())
    var = float(deltas.var(ddof=1))
    denom = np.sqrt(var * (1.0 / k + n_test / n_train))
    return float(mean / denom) if denom > 0 else float("nan")

The headline result: boosting ahead by 0.057 PR-AUC, 95% bootstrap interval 0.048 to 0.066, across 5 folds by 6 seeds, trial-matched at 200 trials, ordinal encoding for both families. The interval excludes zero comfortably, which is the thing none of the three original benchmarks established. And it is worth noting what the pairing bought: the fold-to-fold standard deviation of PR-AUC was 0.096, about 4.6 times the paired difference’s standard deviation of 0.021, so an unpaired comparison would need roughly twenty times as many runs to reach the same interval width.

Where the ranking flips: three sweeps

The 0.057 is a measurement at one point in a space, and the space has boundaries you can reach.

Tuning budget. At 5 trials each, boosting won 14 of 30 fold-seed pairs. At 25 trials, 22 of 30. At 200 trials, 29 of 30. This is the asymmetry from the earlier callout expressed as a crossover: with a small search, the forest’s near-optimal defaults beat a booster that has not found its learning-rate and leaf-count combination yet. The practical reading is that if you have an afternoon and no tuning infrastructure, the forest is a better bet, and that is not a statement about algorithmic quality.

Training-set size. Subsampling the training folds by time, boosting’s advantage is a function of n. At 5,000 rows the forest wins by 0.019; at 25,000 they are within 0.004; at 200,000 boosting leads by 0.031; at the full 2.25M training rows it leads by 0.057. The mechanism is directly readable off the bias-variance decomposition below: boosting reduces bias, which requires enough data to estimate the residual structure it is fitting, while bagging’s variance reduction works at any n.

Label noise. This is the crossover that mattered for this project, because the data has real label noise. Injecting symmetric label flips into the training folds only, boosting leads by 0.057 at 0%, 0.035 at 8%, and 0.004 at 16%, and the forest leads by 0.011 at 24%. The crossover sits at about 15%, and our measured label noise is 3% to 5%, which is uncomfortably close given that the noise estimate came from a 900-shipment audit. Boosting’s sequential residual fitting is the mechanism: a mislabelled row produces a large residual, and the next tree is built specifically to fit large residuals, so noise is amplified by the same machinery that reduces bias. Bagging averages it away.

# The three sweeps, as one function, because the point is that they are the
# same experiment with one axis varied and everything else pinned.
import numpy as np

def flip_labels(y: np.ndarray, rate: float, seed: int = 17) -> np.ndarray:
    """Symmetric label noise injected into TRAINING folds only. Flipping the
    test labels too would measure a different and less interesting thing,
    namely how much a noisy evaluation set degrades every metric."""
    rng = np.random.default_rng(seed)
    out = y.copy()
    idx = rng.choice(len(y), int(rate * len(y)), replace=False)
    out[idx] = 1 - out[idx]
    return out

def sweep(axis: str, values, run_pair, X, y, folds, seeds=range(6)) -> dict:
    """run_pair(X, y, folds, seed, **kw) -> (score_bagging, score_boosting).

    One axis varies; the feature matrix, the folds, the search budget and the
    seed set are pinned. Returns the paired delta at each value, which is what
    a crossover is visible in; two separate curves are much harder to read a
    crossing off, because both move with the axis.
    """
    out = {}
    for v in values:
        deltas = []
        for seed in seeds:
            if axis == "noise":
                a, b = run_pair(X, flip_labels(y, v, seed), folds, seed)
            elif axis == "size":
                sub = [(tr[-int(v):], te) for tr, te in folds]
                a, b = run_pair(X, y, sub, seed)
            elif axis == "trials":
                a, b = run_pair(X, y, folds, seed, n_trials=int(v))
            else:
                raise ValueError(axis)
            deltas.append(b - a)
        out[v] = {"delta": float(np.mean(deltas)),
                  "sd": float(np.std(deltas, ddof=1)),
                  "boosting_wins": int(sum(d > 0 for d in deltas))}
    return out

The bias-variance decomposition, measured rather than recited

Both crossovers above follow from one decomposition, and it is worth computing rather than asserting because the recited version (“bagging reduces variance, boosting reduces bias”) is correct and unquantified.

# Kohavi-Wolpert style decomposition for 0-1 loss on a bootstrap ensemble of
# fits. Not a standard sklearn utility, and it is the single most explanatory
# 30 lines in the harness.
import numpy as np

def bias_variance_01(fit_predict, X_tr, y_tr, X_te, y_te,
                     n_reps: int = 25, seed: int = 17) -> dict:
    """Refit on n_reps bootstrap resamples, then decompose expected 0-1 loss.

    bias    : error of the MAJORITY prediction across refits
    variance: how often an individual refit disagrees with that majority
    The two sum to the expected loss up to the noise term, which is not
    identifiable without repeated labels for the same input.
    """
    rng = np.random.default_rng(seed)
    preds = np.zeros((n_reps, len(X_te)), dtype=np.int8)
    for r in range(n_reps):
        idx = rng.choice(len(X_tr), len(X_tr), replace=True)
        preds[r] = (fit_predict(X_tr[idx], y_tr[idx], X_te) >= 0.5).astype(np.int8)
    majority = (preds.mean(axis=0) >= 0.5).astype(np.int8)
    bias = float((majority != y_te).mean())
    variance = float((preds != majority).mean())
    return {"bias": bias, "variance": variance,
            "expected_loss": float((preds != y_te).mean())}

Measured on a 200,000-row fold, 25 bootstrap refits, tuned configurations:

Model Bias Variance Expected 0-1 loss
Single tree, depth 40 0.121 0.148 0.269
Random forest, 800 trees 0.116 0.019 0.135
LightGBM, tuned, early stopped 0.098 0.031 0.129
LightGBM, 3,000 trees, no early stopping 0.081 0.066 0.147

Read the first two rows together: bagging took variance from 0.148 to 0.019, a factor of 7.8, and moved bias by 0.005. That is the whole of what bagging does, stated numerically. Rows three and four are boosting: it gets bias down to 0.098, and if you let it keep going it gets bias to 0.081 while variance climbs to 0.066 and total loss gets worse. Both crossovers are now legible. Small n means the bias term cannot be estimated reliably, so boosting’s advantage evaporates. Label noise raises the irreducible component of the residual that boosting is fitting, so pushing bias down starts buying variance instead, exactly as the fourth row does deliberately.

Key Insight

The design decision that mattered most was reporting the paired difference with an interval rather than two point estimates, and it mattered for a reason that has nothing to do with statistics. The fold-to-fold standard deviation of PR-AUC on this data is 0.096, which is 1.7 times the 0.057 difference between the families. That means any two people running any two benchmarks on different splits will get differences anywhere from strongly negative to strongly positive, both will be measuring correctly, and the argument cannot terminate. It is not that the unpaired comparison is less powerful, although it is by roughly a factor of twenty in runs; it is that the unpaired comparison produces numbers whose disagreement looks like someone's error, which converts a measurement problem into an interpersonal one. The harness ended the two-quarter argument in a week, and what ended it was the interval, not the winner.

Evaluation and Metrics

PR-AUC is the optimisation metric and precision at the operating point is the decision metric, and the pair has to be reported together for a reason specific to a capacity-constrained alerting system: PR-AUC integrates over thresholds that will never be used. A model can gain 0.02 PR-AUC entirely in the region beyond 2,000 flags a day, which is four times the desk’s capacity.

Calibration is a guardrail rather than an objective, and it discriminates between the families more sharply than accuracy does. The dispatcher UI shows “72% likely to be late”, so systematic overconfidence trains the desk to discount the number.

# The metric block. average_precision_score is the PR-AUC; the other three
# are not one-liners and each catches something the first misses.
import numpy as np
from sklearn.metrics import average_precision_score, brier_score_loss

def precision_at_daily_capacity(scores: np.ndarray, y: np.ndarray,
                                day: np.ndarray, k: int = 600) -> float:
    """Rank within each DAY and take the top k, because capacity is daily.

    Pooling the whole test period and taking the top k * n_days is a different
    and easier problem: it lets the model spend a whole week's capacity on one
    bad weather day, which the desk cannot do.
    """
    hits, total = 0, 0
    for d in np.unique(day):
        m = day == d
        take = np.argsort(-scores[m])[:k]
        hits += int(y[m][take].sum())
        total += len(take)
    return hits / total if total else float("nan")

def expected_calibration_error(scores: np.ndarray, y: np.ndarray,
                               n_bins: int = 20) -> float:
    """Equal-count bins, weighted by bin size. Equal-WIDTH bins are the common
    implementation and they put 90% of an imbalanced problem's mass in the
    first bin, which reports a small error for a badly calibrated model."""
    order = np.argsort(scores)
    bins = np.array_split(order, n_bins)
    err = sum(len(b) * abs(scores[b].mean() - y[b].mean())
              for b in bins if len(b))
    return float(err / len(scores))

def alert_concentration(scores: np.ndarray, lane: np.ndarray,
                        day: np.ndarray, k: int = 600) -> float:
    """Largest share of a day's flags going to one lane. A model that flags
    one troubled lane 600 times a day is accurate and useless."""
    worst = 0.0
    for d in np.unique(day):
        m = day == d
        take = np.argsort(-scores[m])[:k]
        lanes, counts = np.unique(lane[m][take], return_counts=True)
        if len(counts):
            worst = max(worst, float(counts.max() / counts.sum()))
    return worst

Baseline against solution, 5 grouped time-ordered folds by 6 seeds, trial-matched at 200 trials:

Configuration PR-AUC Precision at 600/day ECE Max lane share Fit time Artifact p99 latency
Prevalence 0.184 0.184 0.000 n/a 0 s 0 B 0 ms
Logistic regression 0.331 0.394 0.021 3.1% 4 min 3 KB 0.1 ms
Single tree, depth 8 0.298 0.361 0.088 9.4% 6 min 41 KB 0.1 ms
Random forest, defaults 0.412 0.497 0.034 4.2% 51 min 2.9 GB 2.4 ms
Random forest, tuned 0.451 0.539 0.018 3.8% 1 h 44 min 4.1 GB 3.1 ms
Random forest, tuned, depth-capped for serving 0.441 0.528 0.022 3.9% 1 h 12 min 780 MB 1.6 ms
LightGBM, defaults 0.421 0.508 0.061 6.8% 9 min 1.2 MB 0.4 ms
LightGBM, tuned 0.508 0.601 0.047 4.6% 23 min 9 MB 0.9 ms
LightGBM, tuned, isotonic calibrated 0.508 0.601 0.009 4.6% 24 min 9 MB 0.9 ms
Paired delta, forest to LightGBM +0.057 +0.062 n/a n/a n/a n/a n/a
95% bootstrap interval on the delta 0.048 to 0.066 0.051 to 0.073 n/a n/a n/a n/a n/a

Four readings, and only the first is about accuracy.

The delta’s interval excludes zero and the gap is 0.057, so on this dataset at this budget boosting wins and the question is settled. The forest’s advantage is calibration: at 0.018 ECE untuned-for-calibration against the booster’s 0.047, which is the expected consequence of averaging many unbiased-ish estimators against summing many biased ones. That advantage is recoverable for the booster with isotonic regression on a held-out slice, taking it to 0.009, so calibration is a solvable problem rather than a reason to choose a family. The artifact size is where the comparison stops being close: 4.1 GB of unlimited-depth forest against 9 MB, which is a factor of 455 and which breached the 2 GB serving ceiling outright. Capping depth to fit cost the forest 0.010 PR-AUC and still left it 45 times larger. And the fit time under the monthly retrain window is 1 h 44 min against 23 min, which matters less than it looks but compounds with every tuning cycle.

Metric That Matters

The metric that catches a silent regression here is not PR-AUC, it is the **recomputed paired delta on each month's fresh fold**. PR-AUC on the newest data is the obvious monitor and it moves for many reasons, most of which are seasonality: our PR-AUC swings 0.06 between October peak season and February, so a threshold on the absolute value either fires every autumn or never fires. The paired delta between the deployed booster and a cheap reference forest, both refit on the same monthly fold, is stable across seasons because seasonality hits both, and it moves when something structural changes. It has fired twice. Once when a carrier integration started backfilling `carrier_lane_ontime_rate` with a default of 1.0 for new lanes: the booster exploited the constant and the delta jumped to 0.094 before absolute PR-AUC moved at all, because the leak helped the newest fold's training and test halves equally. Once when the label noise rose to 11% after a scanner firmware change, and the delta compressed from 0.057 to 0.021, which is the label-noise sweep reproducing itself in production and the only warning we got. Keeping a deliberately worse model in the retrain pipeline as a reference costs 1 h 12 min a month and is the most informative monitor in the system.

Common Pitfalls and Failure Modes

Pitfall Why It Happens How to Detect How to Fix
Unequal tuning budget Both libraries have defaults, so “defaults vs defaults” looks fair and is not; the forest’s defaults are near-optimal and the booster’s are a starting point Tuning lifts one family far more than the other; ours lifted 0.039 against 0.087 Same sampler, same trial count, and report compute-matched separately since a booster trial cost 6.8 min against the forest’s 41
Random K-fold on grouped or time-ordered data It is the default in every tutorial and the data looks like independent rows Absolute scores drop when you switch to grouped time folds; here by 0.063 and 0.047, unequally Group by the recurring entity, order by time, embargo the label lag, hold out whole groups from training
Target encoding fitted outside the resampling loop The encoder is “fitted only on train”, which sounds sufficient The encoded feature’s importance is implausibly high and the gap between families widens Nest the encoder in the fold, use out-of-fold encoding, or use ordered target statistics as CatBoost does
Different categorical handling per family One library accepts categoricals natively and the other does not, so somebody one-hots for one side The gap changes when you switch both to the same encoding; here by 0.034 Run the harness under both encodings and report both rows. Claim native categorical support as a library advantage, on its own line
Two point estimates with no interval It is what every blog post reports Rerun with a different seed; ours moved the difference by more than the difference Paired over folds and seeds, bootstrap the paired delta, and use the corrected resampled t-test when folds share training data
Tuning n_estimators for the forest It is in the signature, so it looks like a hyperparameter The search picks a value below the maximum tried, which is CV noise rather than signal Bagging error is monotone non-increasing in tree count. Fix it at the largest value the budget allows and spend the search on max_features
Early stopping the booster on the test fold eval_set=[(X_test, y_test)] is the first thing every example shows Held-out performance is implausibly good and degrades on truly fresh data Carve the validation slice out of the training fold by time. The stopped iteration count is a fitted parameter and must be fitted inside the fold
Using the forest’s OOB score as if it were CV It is free and it is genuinely a held-out estimate It disagrees with grouped time CV in the optimistic direction, by 0.038 here OOB resamples rows, so it respects neither the grouping nor the time order. It is a debugging signal, not a comparison metric
Imbalance handling applied to one family only class_weight="balanced" and scale_pos_weight live in different places and are easy to set asymmetrically One family’s predicted positive rate is far from the other’s Put both in the search space and let the tuner decide, then check the predicted prevalence of both winners
Judging the comparison on accuracy alone It is the number in the table The winner breaches a non-accuracy constraint at integration time Put artifact size, p99 latency and fit time in the same table. The 4.1 GB artifact breached a 2 GB ceiling that no accuracy number would have caught
Common Pitfall

The single most common mistake on this exact comparison is early stopping the boosting model on the same data used to report its score. It is more common than the others because every LightGBM and XGBoost example in existence writes `eval_set=[(X_valid, y_valid)]` and then reports metrics on `X_valid`, and in a tutorial that is a harmless demonstration of the API. In a comparison it is decisive, because the number of boosting rounds is the most important fitted quantity in the whole model and choosing it by looking at the test set is choosing the model by looking at the test set. We measured it: early stopping on the test fold reported PR-AUC 0.551 against a correctly nested 0.508, an inflation of 0.043, which is 75% of the entire gap being argued about. The forest has no equivalent because there is nothing to stop early, so the mistake is silently one-sided and it inflates the family it touches. The fix is mechanical and the discipline is to treat the stopped iteration count as exactly what it is, a hyperparameter fitted on data, which means it belongs inside the same resampling loop as every other one. If the folds are tight on data, use a fixed round count chosen by the outer search rather than early stopping at all; costing 0.006 PR-AUC to remove a whole class of leak is a good trade.

Four panels showing where the bagging versus boosting ranking flips: a tuning-budget sweep where boosting wins 14 of 30 fold-seed pairs at 5 trials and 29 of 30 at 200 trials, a training-set-size sweep crossing over near 25,000 rows with bagging ahead below it, a label-noise sweep crossing over near 15 percent flipped labels with the project's measured 3 to 5 percent uncomfortably close, and the cross-validation protocol confound where moving from random K-fold to grouped time-ordered embargoed folds costs boosting 0.063 and bagging 0.047 so the gap itself shrinks from 0.073 to 0.057

Scaling and Productionizing

The asymmetry that decided this project is not accuracy, it is that a bagging ensemble’s model size is proportional to the data it was trained on and a boosting ensemble’s is not.

Training data, 2.25M rows x 41 features, float32       = 369 MB
Ordinal-encoded matrix with categorical codes           = 338 MB
Random forest, 800 trees, max_depth unlimited          about 41M leaves  = 4.1 GB
Random forest, 800 trees, max_depth 22, leaf min 50    about 7.4M leaves = 780 MB
LightGBM, 1,240 trees x 186 leaves                     about 231k leaves = 9 MB
Forest fit, 32 cores, trial-matched tuned config       = 1 h 44 min
LightGBM fit, 32 cores, trial-matched tuned config     = 23 min
Forest scoring, 800 deep trees, batch of 3,100         = 3.1 ms p99
LightGBM scoring, 1,240 trees, batch of 3,100          = 0.9 ms p99
Monthly retrain window                                 = 6 h, both fit inside
200-trial search, forest                               = 137 h, needs 8 workers
200-trial search, LightGBM                             = 23 h, needs 1 worker
Isotonic calibration on a 180k held-out slice          = 41 s
Reference-forest monitor, refit monthly                = 1 h 12 min

The forest’s artifact scales with n and the booster’s does not. An unlimited-depth tree on 2.25M rows has on the order of 50,000 leaves, and 800 of them is 41 million leaves, which is 4.1 GB of node structure. Triple the training data and it triples. A boosting ensemble’s size is set by n_estimators times num_leaves, both of which are hyperparameters, so it is 9 MB at 2.25M rows and 9 MB at 20M rows. On a serving box with a 2 GB ceiling this is not a performance consideration, it is a feasibility one, and it is invisible in every accuracy table.

Depth-capping the forest to fit is a real cost and worth measuring rather than assuming. Capping at depth 22 with a 50-row leaf minimum took the artifact from 4.1 GB to 780 MB and cost 0.010 PR-AUC. That is a defensible trade and it also changes the comparison: the deployable forest is 0.067 behind, not 0.057.

Retraining cadence is set by the history statistics, not the trees. Frozen for 12 weeks, PR-AUC decayed 0.508, 0.504, 0.491, 0.472. Decomposing it, almost all the decay came from the expanding-window carrier and lane statistics going stale rather than from the tree structure, which matches the pattern in most tabular problems with historical aggregates. We refresh the aggregates weekly, which is a groupby, and retrain monthly, and that holds PR-AUC within 0.006 of a weekly retrain.

The monitoring signal for silent degradation is the triple of the paired delta against the reference forest, the predicted-prevalence drift of the deployed model, and the null rate of the four expanding-window features. The paired delta catches structural change, as described above. Predicted prevalence catches a shift in the score distribution before it shows up in a metric that needs labels, which matters because labels arrive 6.2 days late. And the null rate on the aggregates catches the upstream failure that actually happens: a carrier integration changing its identifier format, which silently sends every lookup to the global prior and costs 0.03 PR-AUC with no error raised anywhere.

Key Insight

Keeping the losing model in the production retrain pipeline is the highest-value line item in this whole project, and it is a strange thing to recommend. It costs 1 h 12 min of compute a month and it produces no predictions anyone sees. What it produces is the paired delta as a live monitor, and the paired delta is the only signal in the system that is insensitive to seasonality: absolute PR-AUC swings 0.06 between peak season and February, so any threshold on it either cries wolf every October or never fires at all, while the delta between two models refit on the same monthly fold holds at 0.057 plus or minus 0.01 through both. Both times it fired, it fired before any absolute metric moved. The backfill incident is the clearest case: a carrier integration started writing 1.0 into the on-time rate for unseen lanes, the booster exploited the constant, the delta went to 0.094, and absolute PR-AUC did not move because the leak was present in both halves of the newest fold. A single-model monitor cannot see that failure at all. The general principle is that a comparison harness is not a one-off study to be run and archived, it is a monitor, and the reason is that a differential between two models cancels everything that affects both of them.

Real World

The lineage is unusually clean. Breiman's 1996 bagging paper and his 2001 random forest paper established variance reduction through bootstrap aggregation plus random feature subsetting; Freund and Schapire's 1997 AdaBoost and Friedman's 2001 gradient boosting machine established sequential fitting of residuals as functional gradient descent. The modern implementations are Chen and Guestrin's XGBoost (2016), Ke and colleagues' LightGBM (2017), whose histogram binning and leaf-wise growth are most of why a booster trial cost 6.8 minutes here against the forest's 41, and Prokhorenkova and colleagues' CatBoost (2018), whose ordered target statistics are a direct algorithmic fix for the target-encoding leak this post spends a callout on. On the comparison question itself, two 2022 papers are the ones to read and they agree: Grinsztajn, Oyallon and Varoquaux's NeurIPS benchmark over 45 datasets found gradient-boosted trees ahead of both deep learning and random forests on tabular data, and, importantly for this post, made hyperparameter budget an explicit axis of the study rather than a footnote; Shwartz-Ziv and Armon's "Tabular data: deep learning is not all you need" reached the same ranking and quantified how much of the apparent advantage of any method is really an artifact of unequal tuning effort. For the statistics, Dietterich's 1998 comparison of five tests for supervised classification algorithms and Nadeau and Bengio's 1999 corrected resampled t-test are what the interval machinery in this post rests on, and Demsar's 2006 paper is the standard reference for comparing classifiers across many datasets. The practitioner data point worth adding is negative: random forests essentially do not appear at the top of Kaggle tabular leaderboards any more, and they remain the standard first model in production teams, which is a consistent pair of facts once you notice that a leaderboard is a trial-matched comparison with an unlimited budget and a sprint is a compute-matched one with an afternoon.

Alternative Approaches

Approach PR-AUC Fit and serve cost Interpretability Best fit
LightGBM, tuned, isotonic calibrated 0.508 24 min fit, 9 MB, 0.9 ms Moderate: SHAP is cheap on trees, 1,240 trees is not readable Large n, low label noise, a real tuning budget, and a serving size ceiling
XGBoost, hist, tuned 0.504 38 min fit, 14 MB, 1.1 ms Moderate, same as above Same, and preferred where the ecosystem or GPU path already exists
CatBoost, ordered boosting 0.511 1 h 09 min fit, 31 MB, 1.8 ms Moderate, plus honest target encoding built in High-cardinality categoricals where the target-encoding leak is the main risk
Random forest, tuned, depth-capped 0.441 1 h 12 min fit, 780 MB, 1.6 ms Good: near-optimal at defaults, OOB error free, per-tree paths inspectable Small budget, small n, noisy labels, or a team without tuning infrastructure
Extremely randomised trees, tuned 0.428 42 min fit, 690 MB, 1.5 ms Good, same as the forest Very noisy labels, and where fit speed matters more than the last 0.02
Histogram gradient boosting, sklearn 0.496 31 min fit, 11 MB, 1.0 ms Moderate No extra dependency wanted; within 0.012 of LightGBM for zero install cost
Stack of forest plus LightGBM plus logistic 0.519 2 h 51 min fit, 800 MB, 4.3 ms Poor: two base families and a meta-learner to explain A leaderboard, or a case where 0.011 PR-AUC is worth tripling the operational surface
Regularised logistic regression 0.331 4 min fit, 3 KB, 0.1 ms Best: signed coefficients per feature A baseline that must exist, and any setting where a coefficient table is the deliverable

What we shipped is the top row, and the margin over the second and sixth rows is small enough that the choice was made on ecosystem rather than accuracy. The row worth arguing about is the stack, which beats the shipped model by 0.011 and which we declined for reasons that are all operational: it triples the retrain time, it puts a 780 MB forest back inside the 2 GB ceiling alongside everything else, and it requires the nested out-of-fold discipline that stacking demands and that is easy to get wrong. CatBoost at 0.511 is the row we would start from on a new project with this feature set, because ordered target statistics solve the leak that produced one of the three original disagreeing benchmarks, and solving it inside the algorithm beats solving it inside the harness.

We would switch to the forest without hesitation in three situations that this project is not in, and all three are the crossovers: under about 25,000 training rows, above about 15% label noise, or with no tuning infrastructure and an afternoon to ship. Those are not hypothetical regimes. The first describes most new product lines, the second describes any label derived from human data entry, and the third describes most first versions.

Key Takeaways

  • Default versus default measures library authorship, not algorithms. The forest’s defaults are near its tuned optimum, lifting 0.039 under a 200-trial search, while the booster’s lift 0.087. So a defaults comparison reports a 0.009 gap where a matched comparison reports 0.057, and the two numbers are about different things.
  • Report the paired difference with an interval, never two point estimates. Fold-to-fold PR-AUC standard deviation here is 0.096 against a 0.057 difference, so unpaired comparisons on different splits disagree by more than the effect and the disagreement looks like someone’s mistake. Pairing bought roughly a factor of twenty in runs for the same interval width.
  • The cross-validation protocol changes the ranking, not just the level. Moving from random K-fold to grouped, time-ordered, embargoed folds cost boosting 0.063 and bagging 0.047, so the gap itself shrank from 0.073 to 0.057. A leak that one family exploits better is a ranking error, not an inflation.
  • Early stopping on the test fold is a one-sided leak worth 0.043 here. The stopped round count is the most important fitted quantity in a boosting model, and the forest has no equivalent, so the mistake inflates exactly one side of the comparison. That is 75% of the gap in dispute.
  • Do not tune n_estimators for a bagging ensemble. Its error is monotone non-increasing in tree count, so there is no optimum to find and cross-validation noise will sometimes select a smaller value and make the model permanently worse. Fix it at the largest count the budget allows.
  • Three sweeps flip the answer, and all three follow from one decomposition. Bagging took variance from 0.148 to 0.019 and bias by 0.005; boosting took bias to 0.098 at the cost of variance. So the forest wins below about 25,000 rows, above about 15% label noise, and under a small tuning budget where it won 16 of 30 fold-seed pairs at 5 trials.
  • The constraint that decided it was artifact size, not accuracy. A bagging ensemble’s model size grows with n, because unlimited-depth trees on 2.25M rows have about 50,000 leaves each. 4.1 GB against 9 MB is a factor of 455, and it breached a 2 GB serving ceiling that no accuracy table would have surfaced.
  • Keep the losing model in the retrain pipeline as a monitor. The paired delta against a reference forest is the only signal insensitive to seasonality, where absolute PR-AUC swings 0.06 between October and February. It fired twice before any absolute metric moved: a carrier backfill leak took it to 0.094, and a scanner firmware change that raised label noise to 11% compressed it to 0.021.

The counter-intuitive lesson is that the comparison became decidable only once it stopped being about the algorithms. Four of the five largest effects we measured belonged to the experiment rather than to the models: the encoding choice was worth 0.034, the out-of-fold target encoding 0.041, early stopping on the test fold 0.043, and the split protocol 0.016 of gap. The actual algorithmic difference, 0.057, was the fifth and it was the only one anybody had been debating. A team that spends two quarters arguing about bagging against boosting is usually not wrong about the models, it is measuring four other things and attributing the total to the models, and the fastest way to end that is to build the harness and let the interval do the arguing.

Frequently Asked Questions

Q: Why not just use gradient boosting for every tabular problem, since it usually wins? A: Because “usually” is doing real work in that sentence and the exceptions are common rather than exotic. On this dataset boosting won by 0.057 with an interval of 0.048 to 0.066, and the same harness shows the forest ahead below roughly 25,000 training rows, above roughly 15% label noise, and under a 5-trial search budget where it took 16 of 30 fold-seed pairs. Those three regimes describe a new product line, any label produced by human data entry, and most first versions of anything. The defensible position is that boosting is the right default for a mature, large, cleanly labelled tabular problem with a tuning budget, and that the crossovers are close enough to check rather than assume.

Q: Why not compare on ROC-AUC, which is threshold-free and does not depend on the class balance? A: It is threshold-free in a way that is actively unhelpful here. At an 18.4% positive rate, ROC-AUC is dominated by how the model orders the overwhelming majority of on-time shipments relative to each other, and the dispatch desk will only ever look at the top 600 of about 3,100 a day. Concretely, every configuration in this post scored within 0.006 ROC-AUC of every other one, including pairs whose PR-AUC differed by 0.09 and whose precision at the operating point differed by 0.10. A metric that reports “no difference” across the entire experiment is not conservative, it is blind. PR-AUC plus precision at the actual capacity is the pair that tracks the decision.

Q: How many trials is an “equal” tuning budget, and does it matter that boosting has more hyperparameters? A: It matters and it is the reason to report two budgets rather than one. Trial-matched, both families get 200 trials of the same sampler, which answers “which algorithm is better given enough search”. Compute-matched, both get the same wall clock, which answers “which should I use this week”, and because a forest trial cost 41 minutes against the booster’s 6.8 the booster gets roughly six times the trials and its advantage grows from 0.057 to 0.069. On the parameter count: the booster’s search space has eight dimensions and the forest’s has four, and that asymmetry is a real property of the methods rather than an unfairness to be corrected. Boosting has more knobs because its bias reduction depends on their interaction; giving the forest eight parameters to tune would not help it, since max_features accounts for most of its available improvement.

Q: Is the forest’s out-of-bag score a free substitute for cross-validation in this harness? A: No, and it fails in the optimistic direction, which is the worst one. OOB error resamples rows independently, so it respects neither the lane grouping nor the time ordering, which are the two structures that made the honest score 0.05 to 0.06 lower than a random split reported. Measured here, OOB was 0.038 above the grouped time-ordered CV estimate. It is genuinely useful as a debugging signal, since it is free and it tells you immediately whether adding trees is still helping, and it is not usable as the metric in a comparison because the other family has no equivalent and because it answers a question about a different sampling scheme.

Q: Should the imbalance be handled with class weights, resampling, or left alone? A: Put the handling in both search spaces and let the tuner decide, then check that the two winners predict similar prevalences. The specific trap in a comparison is asymmetry: class_weight="balanced" for the forest and nothing for the booster, or scale_pos_weight for the booster and nothing for the forest, because the two libraries put the option in different places with different names. On this data the tuned forest chose balanced and the tuned booster chose scale_pos_weight near 2.4 rather than the 4.4 that would fully balance it, and both ended up predicting a prevalence within 0.02 of the true rate. SMOTE and its relatives were tried and cost both families 0.01 to 0.02 PR-AUC, which is the usual result when the minority class is 18% rather than 0.2%.

Q: What breaks first in production? A: The expanding-window history features, and they break silently because nothing in the model layer validates them. The failure we hit twice was upstream: a carrier integration changed its identifier format, every lookup missed, and the carrier-lane on-time rate quietly fell back to the global prior for a growing share of rows, which cost 0.03 PR-AUC with no error raised anywhere. The second variant was worse because it was helpful-looking: the same integration started backfilling a default of 1.0 for unseen lanes, which the booster learned to exploit, and absolute PR-AUC did not move because the fabricated signal was in both halves of the newest fold. The monitor that caught it was the paired delta against the reference forest, which jumped to 0.094. Watch the null and default rates of every historical aggregate as a first-class metric, and keep a second model around so you have a differential to look at.

Interview Questions

Q: Explain the difference between bagging and boosting, and predict what each does to bias and variance. Expected depth: Start from the construction rather than the slogan. Bagging fits many base learners independently on bootstrap resamples and averages their predictions, so the averaging reduces the variance of the estimator and leaves the bias roughly where the base learner put it, which is why the base learner is chosen to be low-bias and high-variance, a deep tree. Random forests add random feature subsetting at each split specifically to decorrelate the trees, since averaging correlated estimators reduces variance much less, and that is a sharper answer than “it adds randomness”. Boosting fits base learners sequentially, each on the errors of the ensemble so far, which is functional gradient descent on the loss, so it drives bias down and, because every stage is fitted to the previous stage’s residuals, it can drive variance up. Be willing to quantify: in a measured decomposition, bagging took 0-1 variance from 0.148 to 0.019 while moving bias by 0.005, and a deliberately over-boosted model reached bias 0.081 with variance 0.066 and a worse total loss than a properly stopped one. Close on the consequences that matter operationally: boosting needs the round count controlled and bagging does not, and bagging’s model size grows with n where boosting’s is set by hyperparameters.

Q: Design an experiment to decide whether a random forest or a gradient-boosted model is better for a given tabular dataset. Expected depth: Name the confounds before naming the design, because the design is derived from them. One feature matrix for both families, including identical categorical encoding, since native categorical support is a library advantage that belongs on its own line rather than inside the algorithmic comparison. An equal search budget, reported both trial-matched and compute-matched, because the per-trial costs differ by roughly a factor of six and the two budgets answer different questions. A resampling scheme that respects the data’s dependence structure: grouped by the recurring entity, ordered by time, with an embargo equal to the label lag. All target-dependent preprocessing nested inside the resampling loop, and the boosting model’s stopped iteration count chosen from a validation slice carved out of the training fold. Then the output: a paired difference over folds and seeds with a bootstrap interval or a corrected resampled t-test, never two point estimates, because the fold-to-fold variance is typically several times the effect. Strong answers add the sweeps, since a single point estimate is a fact about one location in parameter space, and the non-accuracy columns, because artifact size, latency and fit time decide more of these comparisons than accuracy does.

Q: A colleague reports that LightGBM beats a random forest on his data by 0.09 AUC. What do you check? Expected depth: Work through the one-sided leaks first, because they are the ones that inflate a single family. Was early stopping done on the reported evaluation set, which is the most common single error and is worth several hundredths on its own. Was any target encoding or other target-dependent transform fitted outside the resampling loop, which tends to help the booster more because it can exploit a smooth informative feature more thoroughly than a forest with square-root feature sampling. Then the symmetric-but-decisive ones: were both tuned, and with what budget, given that a forest’s defaults are usually much closer to optimal than a booster’s. Was the split appropriate to the data’s structure, since random K-fold on grouped or time-ordered data leaks and does not leak equally. Was the encoding identical. Then the statistics: is there an interval, is the comparison paired, and does the difference survive a change of seed. Finally the metric: 0.09 of ROC-AUC on an imbalanced problem is a large claim and PR-AUC or precision at the operating point may tell a different story, in either direction.

Q: Under what conditions would you expect a random forest to beat a well-tuned boosting model? Expected depth: Derive the answer from the decomposition rather than listing cases. Boosting’s advantage is bias reduction, which needs enough data to estimate the residual structure it is fitting and needs that residual structure to be mostly signal, so the advantage shrinks when n is small and when the residuals are substantially noise. That gives the three concrete regimes: small training sets, where a measured crossover sat near 25,000 rows; high label noise, where a crossover sat near 15% symmetric flips, with the mechanism being that a mislabelled row produces a large residual and the next tree is built specifically to fit large residuals; and small tuning budgets, where the forest’s near-optimal defaults beat a booster that has not yet found its learning-rate and leaf-count combination. Add the operational conditions, which are not about accuracy: where calibration matters and no post-hoc calibration step is available, since averaging unbiased-ish estimators calibrates better than summing biased ones, and where the out-of-bag estimate’s convenience is worth something. A strong answer also names the reverse condition, which is that the forest’s artifact grows with n, so at very large n it can be infeasible to serve even where it is competitive.

Q: Your team has argued for two quarters about which of two models is better and cannot converge. What is your first move? Expected depth: Recognise the shape of the problem, which is that three correct measurements of three different experiments will disagree and the disagreement will look like someone’s error. Quantify the noise floor before arguing about the effect: rerun one configuration across seeds and splits and compute the standard deviation of the difference, because if it exceeds the effect being debated then no amount of further benchmarking will terminate the discussion. Then enumerate the free parameters of the experiment, which are the feature matrix, the encoding, the split protocol, the tuning budget, the preprocessing nesting, and the metric, and pin every one of them in a single harness so the only thing varying is the model. Output a paired difference with an interval. Strong answers observe that this converts an interpersonal problem into a measurement one and that the interval, not the winner, is what ends it, and that the harness should then be kept as a monitor rather than archived, since a differential between two models cancels everything that affects both of them and is therefore the most robust degradation signal available.

View full code for this problem