Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 20 min · revision 2

Worked Example: Is the Ensemble Worth Its Cost?

Compare logistic regression, a random forest and a gradient-boosted model on the same cross-validation folds for two tables, read fold-by-fold gaps, see why trees cannot extrapolate a linear trend, measure single-request latency of the whole pipeline as percentiles, measure model size, and turn the numbers into a justified choice.

Contentsand lesson path

What you will learn

  • Compare a tree ensemble with a linear baseline on score, training and inference time and model size, and justify the choice.

01. The problem

A subscription app scores each customer for churn risk when they open it. Each request carries one row, and the whole call, preprocessing included, has a budget of 20 ms at the 99th percentile (p99: 99% of requests must finish faster). The model also has to fit in a small container, so its file should stay under 50 MB. The team has three candidates: a regularised logistic regression, a random forest and a gradient-boosted model. Should the ensemble replace the linear model?

The data decides, so this worked example runs the same comparison on two seeded tables. In the interactions table, the label depends on thresholds and on products of features. In the linear table, the log-odds of the label are a weighted sum of the features. Both have 4,000 rows, eight numeric columns and one categorical column, segment. Each candidate is a complete pipeline: logistic regression scales and one-hot encodes, the forest one-hot encodes, and HistGradientBoostingClassifier handles the category natively. The code uses scikit-learn 1.9.

Python · setup.py
"""Two seeded tables and three candidate pipelines, shared by every step."""
import numpy as np
import pandas as pd
from sklearn.compose import make_column_transformer
from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

NUMERIC = [f"x{i}" for i in range(8)]


def make_table(kind, n=4000, seed=0):
    rng = np.random.default_rng(seed)
    X = pd.DataFrame(rng.normal(size=(n, 8)), columns=NUMERIC)
    X["segment"] = pd.Categorical(rng.choice(["a", "b", "c", "d"], n))
    if kind == "interactions":      # thresholds and products of features
        logit = (1.5 * (X.x0 > 0.5) * (X.x1 > 0) - 1.5 * (X.x2 > 1)
                 + 1.2 * X.x3 * X.x4 + 1.0 * (X.segment == "b") * (X.x5 > 0) - 0.5)
    else:                           # "linear": a weighted sum of the features
        logit = (0.8 * X.x0 - 0.6 * X.x1 + 0.5 * X.x2 + 0.4 * X.x3
                 + 0.5 * (X.segment == "b") - 0.5)
    y = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
    return X, y


def candidates():
    scale_and_encode = make_column_transformer(
        (StandardScaler(), NUMERIC), (OneHotEncoder(), ["segment"]))
    encode_only = make_column_transformer(
        (OneHotEncoder(), ["segment"]), remainder="passthrough")
    return {
        "logistic": make_pipeline(scale_and_encode, LogisticRegression(max_iter=1000)),
        "forest": make_pipeline(encode_only, RandomForestClassifier(
            300, min_samples_leaf=3, n_jobs=-1, random_state=0)),
        "boosting": HistGradientBoostingClassifier(
            learning_rate=0.05, max_iter=2000, early_stopping=True,
            validation_fraction=0.15, n_iter_no_change=20, random_state=0),
    }


FOLDS = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)

if __name__ == "__main__":
    for kind in ["interactions", "linear"]:
        X, y = make_table(kind)
        print(f"{kind:<12} rows {len(X)}  columns {X.shape[1]}  "
              f"positive share {y.mean():.3f}")
Terminal
python setup.py
Expected output
interactions rows 4000  columns 9  positive share 0.426
linear       rows 4000  columns 9  positive share 0.420

02. Step 1: Score every model on the same folds

All three pipelines are scored with ROC AUC on one StratifiedKFold object with a fixed seed, so every model is trained and tested on exactly the same rows. That makes a paired comparison possible: for each fold, subtract the logistic score from the ensemble score. The fold-to-fold spread of each model mixes two things, how hard each fold happens to be and how much the model itself varies, and the first part is shared by all models. The paired gap removes it.

Python · compare.py
from sklearn.model_selection import cross_validate

from setup import FOLDS, candidates, make_table

for kind in ["interactions", "linear"]:
    X, y = make_table(kind)
    scores = {}
    for name, model in candidates().items():
        res = cross_validate(model, X, y, cv=FOLDS, scoring="roc_auc")
        scores[name] = res["test_score"]
    print(f"{kind} table          fold AUCs              mean ± std   gap to logistic")
    for name, s in scores.items():
        folds = " ".join(f"{v:.3f}" for v in s)
        line = f"  {name:<9} {folds}  {s.mean():.3f} ± {s.std():.3f}"
        if name != "logistic":
            gap = s - scores["logistic"]
            line += f"  {gap.mean():+.3f} ({gap.min():+.3f} to {gap.max():+.3f})"
        print(line)
Terminal
python compare.py
Expected output
interactions table          fold AUCs              mean ± std   gap to logistic
  logistic  0.603 0.592 0.607 0.583 0.624  0.602 ± 0.014
  forest    0.717 0.715 0.712 0.722 0.699  0.713 ± 0.008  +0.111 (+0.075 to +0.139)
  boosting  0.726 0.724 0.718 0.727 0.727  0.725 ± 0.004  +0.123 (+0.104 to +0.144)
linear table          fold AUCs              mean ± std   gap to logistic
  logistic  0.777 0.755 0.791 0.777 0.791  0.778 ± 0.013
  forest    0.753 0.753 0.773 0.757 0.759  0.759 ± 0.007  -0.019 (-0.032 to -0.002)
  boosting  0.746 0.751 0.764 0.767 0.756  0.757 ± 0.008  -0.022 (-0.035 to -0.005)

On the interactions table, boosting averages 0.725 against 0.602 for logistic regression, and it wins in every fold, by between 0.104 and 0.144. That gap is many times the spread of either model, so it is not luck of the split. A linear model can only add up the effect of each feature, so without hand-made features such as x3 * x4 or x0 > 0.5 it misses most of this signal.

On the linear table the order flips. Logistic regression scores 0.778, and both ensembles trail it in every fold. When the truth is a weighted sum, the linear model has the right shape, while the trees must approximate each straight effect with many small steps, which costs variance on 4,000 rows.

03. Step 2: Where the linear model wins

The step approximation has a second cost that cross-validation will not show if the test rows look like the training rows: a tree model cannot continue a trend beyond the inputs it was trained on. An input above the largest training value goes to the same outermost leaves in every tree, so the prediction stops changing. The script trains on x between 0 and 10 with a straight-line target and asks both models about larger values.

Python · extrapolate.py
import numpy as np
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.linear_model import Ridge

rng = np.random.default_rng(0)
x = rng.uniform(0, 10, 500).reshape(-1, 1)          # training range: 0 to 10
y = 3 * x.ravel() + rng.normal(0, 2, 500)           # a straight-line target
ridge = Ridge(alpha=1.0).fit(x, y)
boost = HistGradientBoostingRegressor(random_state=0).fit(x, y)

print("   x   truth   ridge   boosting")
for value in [2.0, 5.0, 9.5, 12.0, 15.0]:
    q = np.array([[value]])
    print(f"{value:4.1f} {3 * value:7.1f} {ridge.predict(q)[0]:7.1f} "
          f"{boost.predict(q)[0]:10.1f}")
Terminal
python extrapolate.py
Expected output
   x   truth   ridge   boosting
 2.0     6.0     5.8        6.2
 5.0    15.0    14.9       14.4
 9.5    28.5    28.4       29.2
12.0    36.0    35.9       29.3
15.0    45.0    45.0       29.3

Inside the training range both models are close to the truth. At 12 and 15, ridge regression continues the line, while boosting stays at 29.3, near the largest targets it saw. If production inputs can drift beyond the training range, this can matter more than a small difference in AUC.

Linear models also tend to win in three other situations. With very sparse, high-dimensional features, such as bag-of-words text with hundreds of thousands of columns, each column is rarely non-zero and a regularised linear model uses them all at once, while a tree can only split on a few. With tiny datasets, a few hundred rows, an ensemble has too little data to find reliable splits and its variance dominates. And when the target is close to linear, as in the second table, the linear model is already the right shape. Trees win where effects depend on thresholds and on each other, as in the first table.

04. Step 3: Latency of the whole pipeline

The service answers one row at a time, so measure that: call predict_proba on a one-row DataFrame through the complete pipeline, 300 times after an untimed warm-up call, and report the median (p50) and p99. The script also times the model alone on prepared input, and the cost per row in a batch of 1,000, as a nightly scoring job would see. A fourth line times the forest with n_jobs=1, because the n_jobs=-1 setting that speeds up training starts worker threads at every prediction.

Timings depend on the machine and its load. The output below is one run on a shared 8-core Linux machine; yours will differ, so compare the models with each other.

Python · timing.py
import time

import numpy as np

from setup import candidates, make_table


def latency_ms(fn, data, repeats=300):
    fn(data)                                   # warm-up call, not timed
    times = []
    for _ in range(repeats):
        start = time.perf_counter()
        fn(data)
        times.append((time.perf_counter() - start) * 1000)
    return np.percentile(times, [50, 99])


X, y = make_table("interactions")
one_row, batch = X.iloc[[0]], X.iloc[:1000]   # one request, and a batch job

models = candidates()
serial = candidates()["forest"].set_params(randomforestclassifier__n_jobs=1)
models["forest, n_jobs=1"] = serial
print("model             fit s  p50 ms  p99 ms  model-only p50  batch µs/row")
for name, model in models.items():
    start = time.perf_counter()
    model.fit(X, y)
    fit_s = time.perf_counter() - start
    p50, p99 = latency_ms(model.predict_proba, one_row)      # the whole pipeline
    if hasattr(model, "steps"):                            # model without its prep
        prepared = model[:-1].transform(one_row)
        bare = latency_ms(model[-1].predict_proba, prepared)[0]
    else:                                                  # boosting has no prep
        bare = p50
    start = time.perf_counter()
    model.predict_proba(batch)
    per_row = (time.perf_counter() - start) / len(batch) * 1e6
    print(f"{name:<17} {fit_s:5.2f} {p50:7.2f} {p99:7.2f} {bare:15.2f} {per_row:13.1f}")
Terminal
python timing.py
Illustrative output: one run on a shared machine, yours will differ
model             fit s  p50 ms  p99 ms  model-only p50  batch µs/row
logistic           0.04    2.81    4.82            0.16           3.4
forest             0.73   59.86   97.40           49.06          68.0
boosting           0.46    5.70    7.53            5.70           8.1
forest, n_jobs=1   2.25   27.07   41.35           28.20          65.7

Three lessons come out of these numbers. First, for one-row requests, the preprocessing and the Python overhead of each call can cost more than the model: the logistic regression itself needs 0.16 ms, but the full pipeline takes about 3 ms, mostly in the ColumnTransformer. Timing only the final estimator would have hidden that. Second, the forest is over budget with either setting: predicting means walking 300 deep trees, and with n_jobs=-1 there is extra thread overhead on every call. Third, the cost per row in a batch is far lower than the one-row cost, so a large-batch benchmark says little about a one-row service. The boosted model fits inside 20 ms at p99 in this run. In other runs on the same machine, while other jobs kept it busy, its p99 jumped above 100 ms although its p50 hardly moved: tail latency is sensitive to contention, so measure it under realistic load before the decision is final.

05. Step 4: Model size

The container limit applies to the saved model. pickle.dumps gives the size of the fitted pipeline as it would be written with joblib or pickle. The sizes depend on library versions, so treat them as illustrative too.

Python · size.py
import pickle

from setup import candidates, make_table

X, y = make_table("interactions")
fitted = {name: model.fit(X, y) for name, model in candidates().items()}
for name, model in fitted.items():
    print(f"{name:<9} pickled size {len(pickle.dumps(model)) / 1024:8.0f} KB")

forest = fitted["forest"][-1]
nodes = sum(tree.tree_.node_count for tree in forest.estimators_)
n_trees = len(forest.estimators_)
print(f"forest:   {n_trees} trees, {nodes / n_trees:.0f} nodes per tree on average")
boost = fitted["boosting"]
print(f"boosting: {boost.n_iter_} trees, at most {boost.max_leaf_nodes} leaves each")
Terminal
python size.py
Illustrative output: sizes vary with library versions
logistic  pickled size        2 KB
forest    pickled size    24033 KB
boosting  pickled size      463 KB
forest:   300 trees, 1021 nodes per tree on average
boosting: 124 trees, at most 31 leaves each

The logistic regression is a handful of coefficients, a few kilobytes. The forest stores 300 trees of about 1,000 nodes each, because its trees are grown deep, and that comes to about 24 MB. The boosted model has 124 small trees and fits in under half a megabyte. Size grows with the number of trees and nodes, so a forest on a few million rows can easily reach gigabytes, while boosting is usually much more compact.

06. Step 5: The decision

Write the decision down with the numbers that justify it.

  • Interactions table: ship the boosted model. Its lead of about 0.12 AUC holds in every fold and is many times the fold spread. It met the 20 ms p99 budget in our run and it is under 1 MB. The forest scores slightly lower, is much larger, and misses the latency budget. Logistic regression stays as the baseline and fallback.
  • Linear table: ship logistic regression. Both ensembles score lower in every fold, so their extra cost buys nothing. Even a tie would favour the simpler, faster and smaller model.

Before the boosted model goes live, re-measure its p99 on the production hardware and check that production inputs stay inside the training range. If the gain had been within the fold noise, for example 0.005 with spreads of 0.01, the decision for the interactions table would have flipped to the cheaper model too.

07. Check your understanding

Practice check · 3 questions

Reading the comparison

Use the outputs of this worked example.

Q1. In step 3, the forest with `n_jobs=-1` has a one-row p50 of about 60 ms, against about 27 ms with `n_jobs=1`. Why is the parallel setting slower here?
Q2. In step 4 the forest pickle is about 50 times larger than the boosted one. What causes most of that difference?
Q3. In `extrapolate.py`, boosting predicts about 29.3 for both x = 12 and x = 15, while the truth is 36 and 45. Why?
Practice only: not graded, not saved, not evidence.

08. Apply it

This is the core of the skill project.

  1. On your project dataset and your fixed folds, score a regularised linear model, a random forest and your tuned boosted model from the lab. Report every fold score, the mean and standard deviation, and the paired gaps to the linear model.
  2. Measure fit time, one-row p50 and p99 latency of the whole pipeline, cost per row in a batch, and pickled size for all three.
  3. Set a latency and size budget that fits your use case, and write a five-line decision record: the chosen model, the score evidence, the cost evidence, the risks (such as inputs outside the training range), and what would change your mind.

09. Review prompt

Without looking back, explain why models should be compared on the same folds and what a paired gap shows; name the kinds of data where tree ensembles beat linear models and three where linear models tend to win; say what you would time for a one-row service and why percentiles matter; explain why a forest is usually much larger than a boosted model; and describe what a tree predicts for inputs beyond its training range.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check