Trees & Ensembles — XGBoost, the Tabular Workhorse
"Single models have blind spots; committees of decision-makers achieve mastery."
~5 hoursBuilds on: Module 02Tools: xgboost · lightgbm · shap · scikit-learnJob-spec line it unlocks: "Classical ML (scikit-learn, XGBoost) remains a baseline expectation"
01 · The hookThe Monday Morning Churn Crisis at SaaSify
One decision tree is unreliable. Hundreds of them, each correcting the last one's
mistakes, is the most reliable thing you can point at a table of business data — and it
still beats deep learning there.
Field report · Emergency exec meeting, 8:45 AM
"Our MRR churn rate hit 7.8% last month. We lost 340 paying
subscribers — over $50,000 in recurring revenue evaporated in
30 days. We are leaking money through the back door while spending millions bringing
customers in the front. And no — we are not carpet-bombing everyone with discount
coupons; spamming healthy customers burns margin. I need surgical precision:
tell me which customers are about to cancel two weeks before they click
'Delete Account'. Early warning system. Operational. By Friday."
— Marcus Vance, CEO of SaaSify
Unpack what Marcus is actually asking for. MRR churn is the percentage of monthly
recurring revenue that walks out the door each month; at SaaSify's growth stage, 7.8%
monthly churn means the company replaces a third of its revenue base every year just to
stand still.
The Head of Product's instinct — "email everyone a coupon" — is the classic
naive fix: a 20% blanket discount across ~4,400 accounts costs six figures a month in
margin, and most of it subsidizes customers who were never leaving.
What Marcus needs is
a ranking: every customer scored by churn probability, refreshed continuously,
with a human-readable reason attached so a customer success manager knows which lever to
pull.
Here is Marcus's problem drawn as three bars, with his own numbers on them. Keep this
picture in mind: every section of this module is one step toward the third bar, and the
numbers on it come back at the end, in the boardroom translation.
Fig. 3.0b — Marcus's Monday as three bars: the leak (340 of 4,400 accounts, $50K a month), the coupon-for-everyone fix that burns $128K a month, and the scalpel that calls 300 ranked accounts and keeps about $7.4K a month for at most $26K. The 55% precision and 30% save rate behind the third bar are the assumptions used in the boardroom translation in section 06.
The leak. The long bar is every paying account. The red slice at the right end is the 340 that cancelled last month. Multiply by the average bill of $147 and that slice is the $50K a month Marcus is losing, and it repeats every month unless something changes.
The shotgun. The Head of Product's fix discounts the whole bar. Twenty percent off every account costs about $128K a month of margin, more than twice the leak, and most of that money goes to customers who were never going to leave. This fix is worse than the disease.
The scalpel. Rank every account by its chance of leaving, call only the 300 at the top of the list, and give offers only there. That needs a model that can put a number on each account and a reason next to it. The chain of numbers under the bar (300 calls, about 165 real risks, about 50 saves) is the promise this module has to keep.
You built linear models in Module 02, and a logistic regression is genuinely the right
first move here — it will be your baseline.
But churn is stubbornly non-linear: a customer
paying $118/month is fine at month 40 and a flight risk at month 3; five support tickets
mean rage on a month-to-month plan and mild annoyance on a two-year contract. Linear
models add effects; churn multiplies them.
The tool that eats this kind of
problem for breakfast — heterogeneous tabular features, interactions everywhere, modest
data sizes — is gradient boosting over decision trees, and its
industrial-strength implementation, XGBoost, is still the single most
deployed model class on business data as of August 2026.
This module takes you from a
tree you write by hand to a production churn engine with explainability a CSM can read.
"Deep learning is the future. It is 2026. Why am I spending five hours on trees?"
— an engineer who has shipped LLM features for two years, reading the hero line
Because most business data still arrives as a table, and on tables gradient-boosted trees still match or beat neural networks. A table mixes dollar amounts, counts, and categories. The boundaries that matter in it are cliffs: a contract type, a tenure threshold. A tree split is a cliff by construction: the first question in Fig. 3.1 below, "MonthlyCharges > $80?", sends an $81 customer one way and a $79 customer the other. A neural network has to learn to imitate one.
The second reason is that trees explain themselves. A single tree is a list of questions you can read aloud. A boosted model can be taken apart per customer, with the SHAP method in section 05, into "these three features pushed the score up". Customer-success teams and regulators need that sentence. Trees also train in minutes on a laptop, so you can try fifty ideas a day.
What trees are bad at, stated plainly: they cannot extrapolate. A tree only ever outputs values it saw in training, so a customer paying twice the highest known price gets the same answer as the most expensive customer on file. Trees cannot read images or text until someone turns them into columns; Module 04 and Module 05 cover that. And a boosted model overfits if nobody stops it, which you will watch happen in section 04.
You already know this
A decision tree is a nested if/else ladder — except the data writes it,
choosing at every level the single most informative condition.
A random forest is what
you already do with flaky services: run N independent replicas with jittered inputs and
take a quorum vote, because uncorrelated failures cancel out.
And gradient boosting is a
patch series in code review: commit #1 is a rough draft, commit #2 exists only to fix
the diff between draft and spec, commit #3 fixes what's still wrong after the first two.
Nobody rewrites the file; each commit is small, targeted at the remaining error,
and the shipped product is the sum of the whole series.
02 · The intuitionFrom 20 Questions to a Committee of Experts
Marcus wants a list of the customers about to cancel, two weeks early, and Fig. 3.0b showed why the list matters: a coupon for all 4,400 accounts costs $128K a month, while 300 well-chosen calls cost at most $26K. The list has to come from the customer table itself: tenure, monthly charges, tickets, logins, contract type. This section is the idea that turns a table into a ranked list. It starts with one tree, shows why one tree cannot be trusted with $50K a month, and ends with the two ways of combining many trees.
Decision trees: the 20 Questions game
SaaSify's table has one row per account and a column for every fact the company records about it. Marcus needs a rule that sorts those rows into "about to leave" and "staying". The first thing to learn is how a single yes-or-no question, asked of one column, does part of that sorting, and how the data itself chooses which question to ask first. That is a decision tree, and it is the atom every model in this module is built from.
Think about how you win 20 Questions: you never ask "is it a 1997 Honda Civic?" first.
You ask the question that best splits the space of possibilities — "is it man-made?" —
then the best question given that answer, and so on. A decision tree plays 20
Questions against your customer table.
At each node it auditions every feature and every
threshold ("MonthlyCharges > $80?", "TenureMonths < 6?"), measures which one
separates churners from stayers most cleanly, asks it, and recurses on each half. The
result is a model you can literally read:
Fig. 3.1 — A depth-2 decision tree on 3,000 SaaSify customers: each node asks the single question that best separates churners from stayers, and each leaf reports the churn rate of the customers who land there. The counts are illustrative; the 400-customer run in section 03 prints a real one.
The first question. The tree tried every column and every threshold and found that "MonthlyCharges > $80?" separates leavers from stayers better than any other single question. That is the whole of what a node does: one column, one cut-off, chosen by the data.
The two branches. Every customer goes one way or the other. 1,140 answered yes and 1,860 answered no, so the question split 3,000 accounts into two smaller tables. Each smaller table then gets its own best question, which is why the yes side asks about tenure while the no side is already calm enough to stop.
The high-risk leaf. Expensive and new: 310 customers, and 71% of them churned. A leaf does not predict a name; it reports the churn rate of the customers who landed in it, and that rate is the score Marcus's list would use for anyone who lands here.
The low-risk leaf. Cheap plans: 1,860 customers, only 6% churned. The tree stopped asking questions here because no further cut made the group much purer. Together the leaves are a ranking with three levels: 71%, 28% and 6%.
Simple, interpretable — and fatally brittle. Grow it deep enough and
a single tree becomes a lookup table of the training set: it memorizes the noise, and one
weird customer near a threshold flips whole branches. You'll measure that brittleness
yourself in a moment. The industry's answer isn't a better tree — it's many
trees, combined. That combining move is called an ensemble, and there
are two great schools of it.
Random forests: the wisdom of the crowd
One tree gives Marcus a rule he can read, like the one in Fig. 3.1. The catch, which section 03 will show with a pencil, is that two customers changing their plan can rewrite the tree's first question. A call list that flips every week because of two accounts is useless to a customer-success team. The team needs the tree's strengths without its swings. The first fix is to grow many trees and let them vote.
School one — bagging (bootstrap aggregating) — is the wisdom of the
crowd. Build 100+ trees, but sabotage their similarity: each tree trains on a random
bootstrap sample of the rows, and at every split it may only consider a random
subset of the features.
Each individual tree is an overfit, opinionated analyst
with its own blind spots — but the blind spots don't overlap, so the majority vote is
calm and accurate.
This is the same reason you run independent replicas behind a quorum:
averaging only helps when failures are uncorrelated. That's a random
forest: nearly zero tuning, embarrassingly parallel, and a strong default.
Here is a forest small enough to read, voting on one SaaSify customer. Customer G has
been with the company 36 months, pays $110 a month, and stayed. Five one-question trees
each give a verdict; the forest's answer is the average of the five.
Fig. 3.1b — A forest of five one-question trees votes on customer G. Two trees are wrong on their own; the average, 0.40, is right. The five questions and thresholds are made up to keep the arithmetic small; the forest in section 04 grows 300 trees on 2,000 customers and does exactly this, 300 votes at a time.
Different rows for every tree. Each tree is grown on its own random re-draw of the customer table (some rows twice, some not at all), and at each split it may only look at a random subset of the columns. That is why the five trees ask five different questions. Trees grown on identical data would ask identical questions and vote identically.
Five verdicts. Customer G is dropped into every tree and follows the thicker branch. Trees 1, 3 and 4 say stay. Tree 2 says leave, because $110 is above its $84 cut-off, and tree 5 says leave for the same reason at $100. Each tree is confident and each is looking at one fact only.
The average. Add the votes and divide by five: 0.40. That is the forest's churn probability for G, and it is below one half, so the forest says G stays, which is true. The two wrong votes did not vanish; they were outnumbered. With 300 trees the same arithmetic runs with 300 votes, and one over-confident tree moves the answer by a third of a percent.
"Why would a hundred bad trees beat one good one? Average garbage and you get averaged garbage."
— a staff engineer who has run a quorum, right about now
Because the trees are not bad in the same way. Each one grows on a different random sample of rows and may use only a random subset of features at each split. So each tree memorizes different noise. Noise that differs from tree to tree averages toward zero. Signal that every tree agrees on survives. Look at marker 2 in Fig. 3.1b: two of the five trees say "leave" for customer G, three say "stay", and the average at marker 3, 0.40, is closer to the truth than either loud tree. Three independent sensors beat one for the same reason: the errors have to be unrelated for the average to help.
The word that matters is unrelated. If every tree made the same mistake, averaging would hand that mistake straight back, which is the Brain Power question below. Marker 1 in Fig. 3.1b, the five different re-draws, is the reason the five votes differ at all. Bootstrap rows and random feature subsets exist to make the trees disagree in useful ways. A forest is not a hundred bad trees. It is a hundred over-confident trees whose confidence points in different directions.
What a forest cannot do: fix a mistake all its trees share. If the signal is not in the columns, a thousand trees will not find it. It cannot extrapolate either. Every prediction is an average of training labels, so a customer far outside the training range gets the answer for the nearest customer the forest remembers. And a hundred trees is no longer an if/else you can code-review. SHAP, later in this module, exists for exactly that reason.
Gradient boosting: the corporate committee
A forest calms one tree's swings by averaging hundreds of votes, and in section 04 a forest of 300 will post the best test score on the board. But every tree in a forest answers the same question, so the mistakes they all share stay in. Marcus's list wants the last few points of accuracy, because each point is a handful of the 300 calls going to the right people. The way to get them is to ask each new tree a different question: what did the trees before you get wrong?
School two — boosting — replaces the parallel crowd with a sequential
committee of specialists. Expert #1 (a small, deliberately weak tree) makes a rough
prediction: gets maybe 70% of the signal, misses 30%.
Expert #2 is hired with a strange
job description: don't predict churn — predict exactly the mistakes Expert #1 made
(the residuals). Expert #3 fixes what's still wrong after the first two, and so on for a
few hundred rounds.
The final model is the weighted sum of the whole committee, each
member contributing a small nudge scaled by a learning rate η.
And the "gradient" in the
name is not decoration: each new tree fits the negative gradient of the loss function —
it's gradient descent, except the steps are trees. The two schools attack different
enemies, and the difference is the picture:
Fig. 3.2 — The difference that matters: bagging trains independent trees on jittered data and votes (averaging away variance); boosting trains a chain where each tree's training target is the previous trees' errors (grinding down bias). What flows along the accented arrows is residuals — not predictions.
The re-draws. The same customer table is sampled three times, and each tree may only look at some of the columns at each split. This is marker 1 of Fig. 3.1b again: it is the only thing that makes the trees differ, and without it the vote at marker 2 is a vote among identical copies.
The vote. Every tree answers the original question, "does this customer churn?", and the forest averages the answers, exactly as (0 + 1 + 0 + 0 + 1) ÷ 5 = 0.40 did for customer G. Nothing travels between the trees; they never see each other.
The leftovers. On the boosting side the accented arrow carries something different: not the labels but what tree 1 got wrong, one number per customer. Tree 2 is trained on those leftovers. Its job is to predict the mistakes, not the churn. Tree 3 then gets the leftovers of the pair.
The weighted sum. The final prediction adds every tree's correction, each shrunk by the learning rate η (eta). Because each tree only fixes what remains, the sum keeps improving on the training rows for as long as you keep adding trees, which is exactly the danger section 04 measures.
Grow many weak trees.
Show each one different rows.
Average their votes to cancel the noise.
Or fit each tree to the mistakes of the last.
Shrink every step, and stop when the held-out score stalls.
Weak trees: the five one-question stumps in Fig. 3.1b. Different rows: marker 1 in Fig. 3.1b and marker 1 in Fig. 3.2, every tree grown on its own re-draw. Average their votes: marker 3 in Fig. 3.1b, (0 + 1 + 0 + 0 + 1) ÷ 5 = 0.40. Fit each tree to the mistakes of the last: marker 3 in Fig. 3.2, the accented arrows carrying leftovers. Shrink every step and stop: the learning rate at marker 4 in Fig. 3.2, and the stopping rule drawn in Fig. 3.3e in section 05.
Now the same picture a second time, with this module's actual files in the boxes. If a box in Fig. 3.2 feels abstract, find its row here. Every stage is a function you will run in the next two sections or a keyword argument you will read in section 05. You are not expected to know these names yet; each one is explained where it appears.
Fig. 3.2 again, concretely: each stage as it exists in this module's code
The one (feature, threshold) pair that purifies most
Make the trees differ
Bootstrap rows and random feature subsets inside RandomForestClassifier(n_estimators=300) in overfit_demo.py
subsample=0.9, colsample_bytree=0.9: each tree sees 90% of the rows and 90% of the columns
Trees whose mistakes do not line up
Decide what each tree learns
Forest: every tree learns the labels
Boosting: every tree learns the residuals left by the trees before it, scaled by learning_rate=0.05
What travels along the arrows in Fig. 3.2: labels on the left, residuals on the right
Combine the trees
The averaged votes of 300 trees behind rf.score()
The sum of every tree's output, squashed to a probability by predict_proba()
One churn probability per customer
Decide when to stop
A fixed count: n_estimators=300
n_estimators=2000 as a ceiling, early_stopping_rounds=50 watching eval_set=[(Xt_va, y_va)]
model.best_iteration: the tree count the data chose
Handle the rare class
Nothing: plain accuracy on a 20% churn rate
scale_pos_weight=spw, computed from the training fold only
A model that pays for every churner it misses
Explain a prediction
json.dumps(grow(...)): read the if/else yourself
shap.TreeExplainer(model) inside churn_report()
Three signed drivers per customer, in JSON a CSM can read
Judge the model
t.score() on the training rows and on the test rows
roc_auc_score and average_precision_score on the untouched test set, against a logistic baseline
Numbers that say whether to ship
🧠 Brain power
Before reading on: suppose you build a "random" forest but forget
the randomness — all 100 trees train on the same rows and may use every feature at
every split. What happens to the ensemble's accuracy compared to a single tree?
Reveal the answer
Almost nothing improves. The 100 trees come out nearly identical, so their votes
are perfectly correlated — and averaging 100 copies of the same mistake
gives you that mistake back.
Variance reduction from averaging only works on the
uncorrelated part of the error (the math is in the hood section, drawn in Fig. 3.4e: the correlated part
ρσ² survives no matter how many trees you add).
That's precisely why bagging jitters
the rows and random forests additionally restrict features per split: both are
decorrelation devices. Diversity isn't a nice-to-have — it's the entire mechanism.
03 · Build it yourselfA Decision Tree in 40 Lines
You now have the two ideas: one tree asks the best question it can find, and a committee of trees covers for one tree's blind spots. Before trusting a library to grow hundreds of trees on SaaSify's table, you should grow one by hand and watch it choose its first question on churn numbers that look like Marcus's. Forty lines of Python are enough. The question the code answers at every step is the one Marcus asked on Monday: which single fact best separates the leavers from the stayers?
Before you touch XGBoost, build the atom it's made of. This is a depth-2 decision
tree, grown greedily with Gini impurity — the "how good is this question?" score. No
frameworks, no magic: just "try every split, keep the one that most purifies the two
buckets, recurse." Run it; it prints the tree as literal nested dicts.
You have not been taught the numpy calls or the Gini formula below yet. That is on purpose. Guess first, then check. Every line in this table is explained in the step-by-step list that follows, and the Gini arithmetic is walked through again in section 06.
Sharpen your pencil
Below are twelve lines lifted from tree_from_scratch.py, the file you are about to read. Three are annotated for you. In the blank rows, write what you think each line does, in plain English, before you open the answers. Wrong guesses are welcome; they are the point of the exercise.
rng = np.random.default_rng(42)
make a random-number generator with a fixed seed, so every run produces the same 400 customers
build a hidden churn score for every customer: it rises with monthly charges above $80 and falls with tenure beyond 12 months. This is the truth the tree has to rediscover
y = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
turn each score into a probability between 0 and 1, then flip a weighted coin: a draw below the probability means churned (1), otherwise stayed (0). The coin is why no model can be perfect here
p = labels.mean()
the share of churners in this bucket: the labels are 0s and 1s, so their mean is the fraction of 1s
return 1.0 - p * p - (1 - p) * (1 - p)
the Gini impurity of the bucket: 0 when every label agrees, 0.5 when it is a coin flip. It is the chance that two customers drawn from the bucket disagree
for t in np.unique(X[:, f]):
try every distinct value of this feature as a candidate threshold, one at a time
left = X[:, f] <= t
a list of True/False, one per customer: True means this customer goes to the left bucket under the candidate split
if left.sum() in (0, y.size):
skip a threshold that sends everyone to one side; that is not a split
score the split as the size-weighted impurity of its two buckets. w is the fraction of rows going left, so a tiny pure bucket cannot outvote a large useful one
if parent - child > best[2]:
keep this split only if its drop in impurity beats the best drop seen so far
stop growing here and record a leaf: the churn rate of the customers who landed in it, and how many there were
"then": grow(X[m], y[m], depth - 1),
call the same function on the customers who went left, with one less level of depth allowed. A function building itself out of smaller copies of itself is recursion
Do not worry if you got half of these. If you guessed that gini() measures how mixed a bucket is and that the loops try every threshold, you already have the whole algorithm. Everything else is bookkeeping.
Step-by-step: what tree_from_scratch.py does, in plain English
Bring in json, to print the finished tree neatly, and numpy for the arithmetic.
Create a random-number generator with seed 42, so every run produces the same 400 customers and therefore the same tree.
Build X, a table of 400 rows and two columns: tenure in months (a whole number from 1 to 71) and monthly charges (a dollar amount between 20 and 150). np.column_stack glues the two columns side by side.
Decide who churns. logit is a hidden score that rises with price and falls with tenure. 1 / (1 + np.exp(-logit)) squashes it into a probability. A random draw below that probability makes the customer a churner (1); otherwise a stayer (0). This is the ground truth the tree must rediscover.
Define gini(labels): for one bucket, take the share of churners p and return 1 minus p squared minus (1 minus p) squared. A pure bucket scores 0; a 50/50 bucket scores 0.5. An empty bucket scores 0, so nothing divides by zero.
Define best_split(X, y): record the impurity of the whole bucket (the parent), and start from "no split found" with a gain of 0.
Loop over both features, and for each feature over every distinct value as a candidate threshold. left is a True/False mask of the rows at or below the threshold.
Skip thresholds that send every row to one side. A split must actually split.
Score the candidate as the size-weighted impurity of its two children. w is the fraction of rows going left. Weighting by size stops a three-customer pure leaf from beating a useful split of hundreds.
If the drop from parent impurity to child impurity beats the best drop so far, remember this feature, threshold, and gain.
Define grow(X, y, depth): find the best split. If depth has run out, or no split reduces impurity, return a leaf holding the churn rate and the row count.
Otherwise split the rows with the mask m and call grow on each half with one less level of depth. A function calling itself on smaller buckets is recursion; it stops at the leaves.
# pip install "numpy>=1.26"
import json
import numpy as np
rng = np.random.default_rng(42)
# 400 customers, two features you can plot in your head:
n = 400
X = np.column_stack([
rng.integers(1, 72, n).astype(float), # tenure (months)
rng.uniform(20, 150, n).round(2), # monthly charges ($)
])
# Ground truth: expensive + new customers churn more (plus noise)
logit = 0.045 * (X[:, 1] - 80) - 0.10 * (X[:, 0] - 12)
y = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
FEATURES = ["tenure_months", "monthly_charges"]
def gini(labels):
"""Impurity of one bucket: 1 - Σp². 0 = pure, 0.5 = coin flip."""
if labels.size == 0:
return 0.0
p = labels.mean() # share of churners in the bucket
return 1.0 - p * p - (1 - p) * (1 - p)
def best_split(X, y):
"""Greedy: audition every (feature, threshold); keep the biggest impurity drop."""
parent, best = gini(y), (None, None, 0.0)
for f in range(X.shape[1]):
for t in np.unique(X[:, f]):
left = X[:, f] <= t
if left.sum() in (0, y.size): # a split must actually split
continue
w = left.mean() # weight children by size — otherwise a
child = w * gini(y[left]) + (1 - w) * gini(y[~left]) # tiny pure leaf wins unfairly
if parent - child > best[2]:
best = (f, t, parent - child)
return best
def grow(X, y, depth=2):
"""Returns nested dicts — literally the if/else ladder the data wrote."""
f, t, gain = best_split(X, y)
if depth == 0 or f is None:
return {"leaf": True, "p_churn": round(float(y.mean()), 2), "n": int(y.size)}
m = X[:, f] <= t
return {"if": f"{FEATURES[f]} <= {t:.1f}",
"then": grow(X[m], y[m], depth - 1),
"else": grow(X[~m], y[~m], depth - 1)}
print(json.dumps(grow(X, y, depth=2), indent=2))
Read that output again: the model is an if/else you could code-review.
It found the tenure threshold on its own, then discovered that price means different
things on each side of it. Customers of 33 months or less are cut at $85.60,
longer-standing ones at $128.80. That is an interaction a linear model can't express
without you hand-crafting the feature. Two details in the code repay attention: children are weighted
by size (so a "pure" leaf with three customers can't beat a useful split of two hundred),
and the split search is greedy — locally best question first, no lookahead.
Greedy is what makes trees fast; it's also part of why a single tree is unstable.
BE the tree
Your turn to play best_split(). Here are eight SaaSify customers with the same two features the script uses, and whether each one churned. Four churned and four stayed, so the parent bucket is a coin flip: its Gini impurity is 1 − 0.5² − 0.5² = 0.5000. With a pencil, score the two most tempting first questions and pick the one the code would choose.
A — tenure 2 months, $120 a month — churned
B — tenure 3 months, $95 a month — churned
C — tenure 5 months, $130 a month — churned
D — tenure 8 months, $60 a month — stayed
E — tenure 14 months, $70 a month — stayed
F — tenure 20 months, $140 a month — churned
G — tenure 36 months, $110 a month — stayed
H — tenure 48 months, $125 a month — stayed
Candidate 1:tenure ≤ 5. Candidate 2:monthly charges ≤ 70. For each one: list who goes left and who goes right. Compute the Gini of each side (1 minus the squared share of churners minus the squared share of stayers). Weight each side by its share of the eight customers, add the two, and subtract the total from 0.5000. The bigger the drop, the better the question. Which one wins? And which single customer does the winner still get wrong?
Check your answer
tenure ≤ 5, left: A, B, C
3 churned, 0 stayed. Gini = 1 − 1.0000 − 0.0000 = 0.0000. A pure bucket.
tenure ≤ 5, with a drop of 0.3000 against 0.1667. The code tries all fourteen usable thresholds across both features and nothing beats it. The one customer it still gets wrong is F: twenty months in, $140 a month, and gone.
Two things to notice. First, the size weighting did real work. Both candidates produced a pure bucket, but the price split's pure bucket held two customers and the tenure split's held three. A pure bucket of two is not worth much, and the weighting says so. Second, the tree is greedy. It asked about tenure first because that was the best single question. It will only find F by asking about price on the right-hand side afterwards.
Now compare with the 400-customer run above, which also put tenure at the root — but with a cut-off of 33 months, not 5. Same feature, a threshold six times larger, because four hundred different customers chose it. Which feature wins is no steadier either. Move G's bill from $110 to $80 and the price split ties the tenure split. Move H's to $80 as well and price wins outright, with a perfect split. Two customers changing their plan rewrote the first question of the whole tree. That is the brittleness the next section measures, and it is why the industry stopped trusting one tree.
Here is the question you just scored, drawn the way the tree sees it. The eight
customers start in one bucket, the question sorts them into two, and the Gini numbers on
the buckets are the ones from your pencil work.
Fig. 3.2b — The first split on the eight BE-the-tree customers: "tenure ≤ 5?" sends A, B, C left (all churned, Gini 0.0000) and D to H right (one churner, Gini 0.3200), a weighted impurity of 0.2000 and a drop of 0.3000 from the parent's 0.5000. The runner-up, "charges ≤ $70?", drops only 0.1667, so the code picks tenure.
The question. One column, one cut-off. The code tried every distinct tenure and every distinct bill as a cut-off, fourteen usable thresholds in all, and scored each one the same way. This one scored best.
The pure bucket. Three customers, all churned, so the share of churners is 1.0 and the Gini is 1 − 1.0² − 0.0² = 0. Draw two customers from this bucket and they can never disagree. That is what "pure" means.
The mixed bucket. Five customers, one churner, so p = 0.2 and the Gini is 1 − 0.04 − 0.64 = 0.32. There is still a churner hiding in here, F, and it is the tree's next job to ask a question on this side that isolates him.
The weighted score. The buckets are weighted by size before they are added: 3/8 of the pure bucket's 0 plus 5/8 of the mixed bucket's 0.32 gives 0.20. The split is scored by how far that falls below the parent's 0.50. Size weighting is why the runner-up's pure bucket of two customers is worth less than this pure bucket of three.
Questions you might be asking now
The exercise scored two questions for eight customers and stopped. The questions below keep going with the same eight. They cover every question the code tries, the tree that never stops asking, and the re-drawn tables a forest grows its trees from. Every number comes from rerunning split_scan_by_hand.py, deep_tree_leaves.py or bootstrap_forest_by_hand.py.
The eight customers every answer below uses: the BE-the-tree customers, four churned and four stayed.
Customer
Tenure (months)
Monthly charges
Churned?
A
2
$120
Yes
B
3
$95
Yes
C
5
$130
Yes
D
8
$60
No
E
14
$70
No
F
20
$140
Yes
G
36
$110
No
H
48
$125
No
How does the tree actually choose where to split? Where do the "fourteen usable thresholds" come from, and what did the other twelve score?
It turns every distinct value in each column into a question, "at or below this?", and scores each one with the weighted Gini you just used. Eight customers give seven usable questions per column, fourteen in all. tenure ≤ 5 wins with a drop of 0.3000; nothing else gets above 0.1667.
A tree does not reason about which fact ought to matter. It runs a contest in five steps, and the highest score is asked first.
List the values. Sort each column's distinct values. Tenure: 2, 3, 5, 8, 14, 20, 36, 48. Charges: 60, 70, 95, 110, 120, 125, 130, 140.
Turn each value into a question. "tenure ≤ 5?" sends every customer with 5 months or fewer into the left bucket, and everyone else into the right. Eight values per column give 8 + 8 = 16 questions.
Throw out the two that split nothing. "tenure ≤ 48?" and "charges ≤ 140?" put all eight customers on the left. A bucket of everyone is not a split, so 16 − 2 = 14 questions remain. This is the if left.sum() in (0, y.size) line of tree_from_scratch.py.
Score each question. Work out each bucket's Gini, 1 − p² − (1 − p)², where p is the share of churners in that bucket. Multiply each bucket's Gini by its share of the eight customers, and add the two.
Keep the biggest drop. The drop is 0.5000, the Gini of all eight together, minus that weighted total. The question with the largest drop is asked first.
One row the exercise skipped, in full: tenure ≤ 8. Left, A to D: three of four churned, so the Gini is 1 − 0.75² − 0.25² = 0.3750. Right, E to H: one of four, also 0.3750. Weighted total 0.3750; drop 0.5000 − 0.3750 = 0.1250. Both buckets stay mixed, so the drop is small.
All fourteen questions for the eight customers, from rerunning split_scan_by_hand.py. Weighted = (left count ÷ 8) × Gini left + (right count ÷ 8) × Gini right; drop = 0.5000 − weighted.
Question
Left bucket
Right bucket
Gini left
Gini right
Weighted
Drop
tenure ≤ 2
A
B C D E F G H
0.0000
0.4898
0.4286
0.0714
tenure ≤ 3
A B
C D E F G H
0.0000
0.4444
0.3333
0.1667
tenure ≤ 5
A B C
D E F G H
0.0000
0.3200
0.2000
0.3000
tenure ≤ 8
A B C D
E F G H
0.3750
0.3750
0.3750
0.1250
tenure ≤ 14
A B C D E
F G H
0.4800
0.4444
0.4667
0.0333
tenure ≤ 20
A B C D E F
G H
0.4444
0.0000
0.3333
0.1667
tenure ≤ 36
A B C D E F G
H
0.4898
0.0000
0.4286
0.0714
charges ≤ 60
D
A B C E F G H
0.0000
0.4898
0.4286
0.0714
charges ≤ 70
D E
A B C F G H
0.0000
0.4444
0.3333
0.1667
charges ≤ 95
B D E
A C F G H
0.4444
0.4800
0.4667
0.0333
charges ≤ 110
B D E G
A C F H
0.3750
0.3750
0.3750
0.1250
charges ≤ 120
A B D E G
C F H
0.4800
0.4444
0.4667
0.0333
charges ≤ 125
A B D E G H
C F
0.4444
0.0000
0.3333
0.1667
charges ≤ 130
A B C D E G H
F
0.4898
0.0000
0.4286
0.0714
Fig. 3.2d draws the drop column as bars, one strip per column.
Fig. 3.2d — The whole contest for the first question. Each bar is one of the fourteen candidate questions, and its length is the drop in Gini it would give. The accented bar, tenure ≤ 5, is the one tree_from_scratch.py keeps. Values from rerunning split_scan_by_hand.py.
The winner. "tenure ≤ 5?" puts A, B and C, all churners, in a pure bucket and leaves one churner among five on the right: weighted Gini 0.2000, drop 0.3000. Nothing on either column gets above 0.1667.
The four-way tie. tenure ≤ 3, tenure ≤ 20, charges ≤ 70 and charges ≤ 125 all score 0.1667, each carving off a pure bucket of two. A tie for first place would go to the question met first, because the code replaces the best only on a strictly bigger drop.
The skipped values. 48 months and $140, the largest value in each column, send all eight customers left. That is not a split, so eight values per column give seven questions.
Two honest limits. The contest looks one question ahead only; it never asks whether a weaker first question would set up a better second one. That shortcut is called greedy search, and it keeps trees fast.
Libraries also vary the details. scikit-learn writes the cut-off halfway to the next value, tenure ≤ 6.5, which sorts these eight the same way. XGBoost's tree_method="hist" first groups each column into at most 256 bins (max_bin) and tries only the bin edges.
A tree picks a split by contest. Every distinct value in every column becomes a question, each is scored by its weighted drop in Gini, and the biggest drop is asked first.
If the tree just keeps asking questions, why does it end up 100% right on the customers it trained on?
Because it keeps splitting while any bucket is mixed, and customers with different numbers can always be split apart. On the eight customers one more question, charges ≤ 125, gives F a bucket of his own, and all eight answers are right. On overfit_demo.py's 1,400 training customers the same process grows 231 leaves, 94 of them holding a single customer.
The script tree_from_scratch.py stopped at depth 2 only because it was told to. Without the limit, grow() keeps calling itself until best_split() finds nothing left to purify.
Question 1, from the contest. tenure ≤ 5. The left bucket, A, B and C, is pure, so nothing more is asked there. The right bucket, D, E, F, G and H, holds one churner and has a Gini of 0.3200.
Question 2, on the right bucket only. The same contest runs on those five customers, and charges ≤ 125 wins. D, E, G and H go left. F, at $140, goes right alone. Both new buckets are pure, so the drop is the whole 0.3200.
Nothing left to ask. Every bucket is pure, so no question can lower any Gini. best_split() returns no feature, and grow() writes leaves.
Check the answers. A, B and C land in a leaf with churn rate 1.0. D, E, G and H land in one with 0.0. F lands in one with 1.0. All eight are right: training accuracy 8 ÷ 8 = 1.000.
Step C is the one to understand. A tree stops only when every bucket is pure, or when two customers with identical numbers disagree. deep_tree_leaves.py found 0 such pairs among overfit_demo.py's 1,400 training customers. So a perfect training score is guaranteed by how the tree grows, not earned by learning.
Now a new customer, I: 30 months in, $135 a month. 30 is more than 5 and $135 is more than $125, so I lands in F's leaf and is scored "churn", rate 1.0, on the evidence of one customer.
A leaf of 300 customers is a rule. A leaf of one customer is an anecdote about F, applied to everyone who resembles F on two numbers. Fig. 3.2e draws the finished tree, then the same process on 1,400 customers.
Fig. 3.2e — Left: the eight customers grown with no depth limit need two questions, and the second one exists only to give F a leaf of his own. A new customer who resembles F on two numbers inherits F's verdict. Right: the same rule on overfit_demo.py's 1,400 training customers, and what its one-customer leaves do to 600 new ones. Values from rerunning split_scan_by_hand.py and deep_tree_leaves.py.
The second question. The contest reruns on the right bucket's five customers, and charges ≤ $125 wins with a drop of 0.3200. It is a good question for these five, and also a question about one customer: F is the only churner it moves.
F's leaf. A pure bucket of one, churn rate 1.0. After it every bucket is pure, no question helps, and the tree stops with all eight customers right.
A stranger in F's leaf. Customer I was never seen, but follows F's path and is scored 1.0. The tree is not measuring I's risk; it is repeating what happened to F.
231 leaves for 1,400 customers. Up to 15 questions deep. 94 leaves hold one training customer, 157 hold three or fewer, and the largest holds 184.
What the anecdotes do. The tree was right on only 36.4% of the 55 test customers who landed in a one-customer leaf, worse than a coin flip. Such a leaf exists because its customer broke the pattern around them, so a newcomer there usually follows the pattern and gets the wrong answer.
A note on these numbers. They come from rerunning overfit_demo.py unchanged, with numpy 2.5 and scikit-learn 1.9, which prints test accuracy 0.787 for the unlimited tree and 0.852 for the forest. The failure box in section 04 quotes that same run, so the box, the bars and the script agree.
Do not expect them to agree with your run to the third decimal. An earlier pass over this page, on older versions of the same two libraries, printed 0.688 for the tree and 0.763 for the forest from this unchanged file.
A seed fixes the draws for one version only. A newer numpy can change how a seed becomes a stream of numbers, and that changes which 2,000 customers you get. A newer scikit-learn can change how it breaks a tie between two equally good splits. Pin your versions whenever a number has to be reproducible.
The pattern is the same in both: the unlimited tree is perfect on the customers it saw and has the worst test score of the four depth settings. Module 02 met the same tree on CartGenius visitors: 561 leaves for 2,400 rows. Its AUC, a ranking score where 0.5 is a coin flip, was 1.000 on training rows and 0.616 on new ones.
Two limits. A perfect training score is a warning, not a verdict: the forest in section 04 also scores 1.000 on training rows and does best on new ones. And depth is only one brake: scikit-learn's min_samples_leaf=2 would forbid F's leaf outright.
A tree with no depth limit is always perfect on its training customers, because it keeps asking until every bucket is pure, even a bucket of one. A leaf of one customer is an anecdote, and new customers pay for it.
What exactly is a "bootstrap sample"? Show me one re-draw of these eight customers.
It is a new table the same size as the original, made by drawing rows at random with replacement: pick a customer, put them back, pick again. Some customers come out twice and some not at all. The re-draw below picked F twice and missed G, and that alone moved the best first question from tenure ≤ 5 to charges ≤ 70.
Picture the eight names on slips in a hat. Draw a slip, write the name down, and put the slip back. Eight draws make a new table of eight rows, and because every slip goes back, one name can come out twice while another never does.
A random forest makes one such table per tree. Here is tree 2's table from the next answer, worked by hand with values from bootstrap_forest_by_hand.py.
Draw eight times.rng.integers(0, 8, 8) rolls an eight-sided die eight times: E, C, D, B, H, F, F, A.
Tally. A, B, C, D, E and H appear once each, F twice, and G never. G is out of bag: left out of this tree's table.
Count the churners in the new table. A, B, C and both copies of F make 5 of 8. So p = 0.625, and the table's Gini is 1 − 0.3906 − 0.1406 = 0.4688. A copy counts exactly like a customer.
Score the old winner, tenure ≤ 5. Left: A, B and C, all churned, Gini 0. Right: D, E, F, F and H, two churned of five, so p = 0.4 and the Gini is 1 − 0.16 − 0.36 = 0.4800. Weighted: 5/8 × 0.4800 = 0.3000. Drop: 0.4688 − 0.3000 = 0.1688.
Score charges ≤ 70. Left: D and E, both stayed, Gini 0. Right: A, B, C, F, F and H, five churned of six, so p = 0.8333 and the Gini is 1 − 0.6944 − 0.0278 = 0.2778. Weighted: 6/8 × 0.2778 = 0.2083. Drop: 0.4688 − 0.2083 = 0.2604.
Crown the winner. charges ≤ 70 wins, 0.2604 against 0.1688. The script scores all twelve usable questions on this table, and no other gets above 0.1688.
Why did the question change? F is the expensive churner the tenure question gets wrong, and he now counts twice. G is the expensive stayer who spoils the price question, and he is gone. One duplicate and one gap made price look more telling than tenure.
The original eight customers against tree 2's re-draw, from bootstrap_forest_by_hand.py
The original eight
Tree 2's re-draw
Who is in the table
A to H, once each
A, B, C, D, E, H once; F twice; G not at all
Churned
4 of 8
5 of 8
Gini of the whole table
0.5000
0.4688
Drop for tenure ≤ 5
0.3000
0.1688
Drop for charges ≤ 70
0.1667
0.2604
First question the tree asks
tenure ≤ 5
charges ≤ 70
Fig. 3.2f draws the draws, the tally, and the two questions scored on the new table.
Fig. 3.2f — One bootstrap re-draw of the eight customers, the one tree 2 is grown from. Eight draws with replacement give F twice and G not at all, and on that table the price question beats the tenure question that won on the original eight. Values from rerunning bootstrap_forest_by_hand.py.
The draws. Each draw picks one of eight customers at random and the slip goes back, so draws 6 and 7 could both be F. That is the luck of this seed, not anything about F.
The tally. Each rectangle is one row of tree 2's table. F has two, so F counts twice in every Gini here, and five of the eight rows are churners where the original had four.
Out of bag. G was never drawn, so tree 2 never sees him. A re-draw of eight leaves out about a third of the customers, and those left out are a fair test for the tree that missed them.
The new winner. With F doubled and G gone, "charges ≤ 70?" leaves one stayer among six rows and drops the Gini by 0.2604; "tenure ≤ 5?" drops it by only 0.1688.
How many does a re-draw leave out? One draw misses a given customer with chance 7/8, so eight draws miss them with chance (7/8)⁸ = 0.344; 20,000 simulated re-draws gave 0.342. With 1,400 customers the same sum gives 0.368, so each tree in section 04's forest never sees about 37% of its training table.
Those left-out customers are a free test. Score each training customer with only the trees that never saw it, and you get the out-of-bag score. For that forest it is 0.841 (deep_tree_leaves.py): close to its 0.852 on test customers, far from the 1.000 on training rows.
The honest limit: re-drawing adds no information. Each tree sees about two thirds of the distinct customers, so alone it is usually a little worse than a tree grown on everything. The gain appears only in the vote. XGBoost's subsample=0.9 in section 05 is a different draw: each row is kept or skipped, never taken twice.
A bootstrap sample is the table redrawn with replacement, at the same size. Its duplicates and gaps are the point: every tree sees a slightly different company, so the trees ask different questions.
Now walk customer G through a forest of five trees grown that way. How do five answers become one number?
Each re-draw grows its own one-question tree, and G lands in one bucket per tree; that bucket's churn rate is the tree's answer. Two trees say leave and three say stay, so the vote is 2 ÷ 5 = 0.40 and G, who stayed, is called a stayer. Over 30,000 re-draws, one tree gets G right 89.2% of the time; a forest of five, 99.1%.
Fig. 3.1b drew this walk with five made-up questions. Here are five grown by best_split(), each on its own re-draw of the eight customers. G has been with SaaSify for 36 months and pays $110 a month.
Customer G through five one-question trees, from bootstrap_forest_by_hand.py. G's bucket counts only the customers in that tree's re-draw, copies included.
Tree
Re-draw (left out)
Question it grew
G's answer
G's bucket
Churn rate
Vote
1
E C H H A B B B (D, F, G)
tenure ≤ 5
no: 36 > 5
E, H, H
0 of 3 = 0.0000
stay
2
E C D B H F F A (G)
charges ≤ 70
no: $110 > $70
A, B, C, F, F, H
5 of 6 = 0.8333
leave
3
B H C G G A D E (F)
tenure ≤ 5
no: 36 > 5
D, E, G, G, H
0 of 5 = 0.0000
stay
4
D A F C C D C D (B, E, G, H)
charges ≤ 60
no: $110 > $60
A, C, C, C, F
5 of 5 = 1.0000
leave
5
G D F H B C E B (A)
tenure ≤ 5
no: 36 > 5
D, E, F, G, H
1 of 5 = 0.2000
stay
Collect the five answers. 0.0000, 0.8333, 0.0000, 1.0000 and 0.2000.
Turn each answer into a vote. A tree votes "leave" when more than half of its bucket churned. That gives 0, 1, 0, 1, 0.
Average the votes. (0 + 1 + 0 + 1 + 0) ÷ 5 = 0.40. That is below one half, so the forest says G stays. G did stay.
Or average the rates, as scikit-learn does.RandomForestClassifier.predict_proba averages each tree's bucket rate instead of its vote: (0 + 0.8333 + 0 + 1.0000 + 0.2000) ÷ 5 = 2.0333 ÷ 5 = 0.4067. Also below one half.
Look at why trees 2 and 4 were wrong. Tree 2's re-draw is the one from the previous answer: F twice, G missing. Tree 4's re-draw left out three of the four stayers, and every customer left in it paying more than $60 churned. Each loud tree had a lopsided table, and each was lopsided in its own way.
Fig. 3.2g draws the five trees and the vote, then repeats the experiment 30,000 times.
Fig. 3.2g — Customer G through a forest of five one-question trees, each grown on its own bootstrap re-draw, then the same experiment repeated with 30,000 re-draws grouped into forests of 1, 5, 25 and 101 trees. The seed of the five-tree forest (12) was picked from the first few that give no tied questions, so the hand arithmetic has one answer; the 30,000-re-draw bars use every draw. Values from rerunning bootstrap_forest_by_hand.py.
Five trees, five tables. Trees 1, 3 and 5 ask about tenure; trees 2 and 4 ask about price. G answers "no" in all five, but "no" leads to a different bucket each time. The thick branch is G's path, and its box holds that bucket's churn rate.
The vote. Two trees put G among mostly churners, so the votes average 0.40; the rates average 0.4067. Both are below one half, and both are right about G.
Many forests. One tree is right about G 89.2% of the time. Five trees are wrong only when three are wrong together, which happened in 0.9% of forests; with 25 it never happened. H climbs the same way, from 79.8% to 100%.
The mistake the vote locks in. Only 43.0% of single trees call F a churner, because most re-draws ask a tenure question that files F, at twenty months, with the stayers. With 101 trees only 7.7% of forests get F right.
For G and H this is the bubble in section 02, with numbers. Most trees are right about them, the wrong ones are wrong on different re-draws, and those mistakes cancel in the vote.
F is the honest limit. Seven in ten re-draws (69.5%) ask about tenure, and the most common question, tenure ≤ 5 (38.6%), files F with the stayers. A mistake most trees share does not cancel; it is the floor in section 06's averaging rule. When most trees are right, the vote removes the noise. When most are wrong, it removes the doubt.
A forest's answer is the average of its trees' answers. The average cancels mistakes that a few trees make, and locks in mistakes that most trees make.
04 · Watch it breakOne Tree Memorizes; It Doesn't Generalize
The hand-built tree found a price threshold and a tenure threshold on 400 customers, and the pencil work showed that two accounts can move its first question. Now comes the natural request: let the tree grow deeper, give it more customers and more columns, and it should get better. It does not. This section measures exactly how a deep tree fails on customers it has never seen, with train-versus-test numbers, and shows a forest of 300 trees fixing that failure in one line. Marcus's Friday list cannot be built on a model that only knows the customers it was trained on.
Now let the tree grow as deep as it wants and watch the wheels come off. Same data
recipe, more customers, four features — and a sweep over max_depth comparing
accuracy on the data the tree saw against data it didn't:
Step-by-step: what overfit_demo.py does, in plain English
Bring in numpy and three scikit-learn pieces: RandomForestClassifier, train_test_split, and DecisionTreeClassifier.
Generate 2,000 customers with four features: tenure, monthly charges, support tickets (a count averaging 2.2), and logins per month (a count averaging 12). rng.poisson draws counts the way real ticket totals look: mostly small, occasionally large.
Compute a hidden churn score from the four features (price pushes up, tenure pushes down, tickets push up, logins push down) and turn it into a 0/1 label with a weighted coin flip, exactly as the first script did.
Split the rows 70/30 into a training set and a test set. stratify=y keeps the churn rate the same in both halves, so neither half is accidentally easier.
Print a header. Then for each max_depth of 2, 4, 8, and None (no limit at all): fit one tree on the training rows and print its accuracy on the rows it trained on and on the rows it has never seen. score() is the fraction of rows classified correctly.
Fit a random forest of 300 trees on the same training rows and print the same two numbers. This is the fix, previewed; the bars after the failure show what the forest does differently.
A representative run prints: depth 2 → train 0.847 / test 0.830 · depth 4 → 0.873 /
0.835 · depth 8 → 0.941 / 0.800 · depth None → train 1.000 / test 0.787.
Perfect training accuracy, worst test accuracy on the board — the unconstrained tree
carved one leaf per handful of customers and memorized the noise. Note the label noise
here is irreducible (churn is genuinely probabilistic), so no model can hit
1.000 honestly; a model that does is confessing. Meanwhile the forest also memorizes
the training set (1.000) yet posts the best test score (0.852) — individual
memorization, collective generalization. That gap between train and test is variance,
and ensembles are the industrial cure.
Those numbers as bars, with the two that matter side by side: the unlimited tree's
train score against its test score, and next to them the forest's test score.
Fig. 3.2c — The failure-mode numbers as bars. A depth-2 tree scores almost the same on seen and unseen customers. The unlimited tree scores a perfect 1.000 on the customers it trained on and 0.787 on new ones, the worst on the board; the 0.213 between those two bars is memorised noise. The forest also scores 1.000 on training rows but 0.852 on new ones, the best on the board.
The honest tree. Two questions deep, 0.847 on seen rows and 0.830 on unseen. A gap of 0.017 means the tree learned something that is true of customers in general, not just of the 1,400 it saw.
The memoriser. Let the same tree grow until every leaf is pure and it scores 1.000 on its training rows. Churn is a weighted coin flip in this data, so no honest model can be perfect; a perfect training score is a confession. On new customers it drops to 0.787, below the two-question tree.
The forest. Three hundred unlimited trees, each one a memoriser on its own, averaged. Training score still 1.000, but the test score is 0.852, the best on the board. Individual memorisation, collective generalisation: this is marker 3 of Fig. 3.1b at scale.
Fig. 3.3 — As depth grows, train accuracy (dashed) marches to 1.0 while test accuracy (solid) peaks and then falls: everything inside the red gap is memorized noise, not learned signal.
The sweet spot. Around depth 4 the solid test line is at its highest, 0.835 in the printed run. Deeper than this, every extra question the tree asks fits the training customers a little better and the unseen customers a little worse.
Training accuracy reaching 1.000. The dashed line keeps climbing until it can climb no more. At unlimited depth the tree has one leaf per handful of customers and gets all of them right, which is the 1.000 bar of Fig. 3.2c.
The gap. The red bracket between the two lines at the right edge is 1.000 minus 0.787. It is the same 0.213 as the bracket in Fig. 3.2c, and it is what people mean by variance: the part of the model that would change if you re-drew the training customers.
So: bagging averages away variance. But a random forest's trees are still redundant —
a hundred experts answering the same question. Boosting asks each new tree a
harder question ("what is everyone before you still getting wrong?"), which
drives error down further — and reintroduces overfitting risk, since a committee obsessed
with residuals will eventually fit noise. The tool that manages that tension with
regularization, shrinkage, and early stopping is the industry workhorse.
Sharpen your pencil
Run two rounds of boosting by hand, once, and the arrows in Fig. 3.2 will never look abstract again. Four customers, A to D. Three churned and one stayed, so the labels are A = 1, B = 1, C = 1, D = 0. Use the simplest loss, squared error, so a residual is just the label minus the current prediction. Use a learning rate of 0.5 to keep the arithmetic short; the production model uses 0.05, which is the same walk in a hundred smaller steps.
Round 0: start every customer at the average label
(1 + 1 + 1 + 0) / 4 = 0.7500 for A, B, C, and D
Residuals after round 0: label − prediction, per customer
Tree 1 splits on tenure ≤ 5 and groups {A, B} against {C, D}. Each leaf outputs the mean residual of its rows
Round 1 prediction: previous prediction + 0.5 × tree 1's leaf value
Residuals after round 1
Tree 2 splits on charges ≤ 130 and groups {A, B, D} against {C}. Leaf values?
Round 2 prediction: previous prediction + 0.5 × tree 2's leaf value
Who is furthest from the truth now, and what would tree 3 have to do?
Work to four decimal places. The trees are given to you; your job is the residuals and the running total, because that is the part of boosting people get wrong.
Check your answers
Residuals after round 0
A +0.2500, B +0.2500, C +0.2500, D −0.7500. The churners are under-predicted; the stayer is over-predicted.
Round 1 prediction
A and B: 0.7500 + 0.5 × 0.2500 = 0.8750. C and D: 0.7500 + 0.5 × (−0.2500) = 0.6250.
Residuals after round 1
A +0.1250, B +0.1250, C +0.3750, D −0.6250. C got worse: it was pulled down with D because tree 1 could not tell them apart.
A and B: 0.8750 − 0.0625 = 0.8125. C: 0.6250 + 0.1875 = 0.8125. D: 0.6250 − 0.0625 = 0.5625.
Furthest from the truth
D, at 0.5625 against a label of 0. Tree 3 would need a leaf that holds D alone, so it can push only D down. A leaf that isolates one customer is a tree memorizing one customer.
Notice three things. First, tree 2 never saw a label. It saw the leftovers of tree 1, and its job was to fix them. That is what travels along the accented arrows in Fig. 3.2. Second, the learning rate of 0.5 meant each tree closed only half the gap it found, so no single tree could dominate. With 0.05 the same walk needs many more rounds, which is why the production model gets a ceiling of 2,000 trees.
Third, look at where the walk was heading. The next useful tree would isolate D. The one after that would chase whichever customer was left, and so on, until every customer had a leaf of its own and the training error was zero. That is the single tree's memorization again, arriving one small step at a time. Early stopping, in section 05, is the rule that says "stop walking when the held-out score stalls".
Here is the walk you just did, drawn. Each panel is one round: a hollow circle is the
true label, a filled dot is the running prediction, and the dashed gap between them is the
leftover the next tree is asked to fix.
Fig. 3.3b — The pencil exercise, drawn: three rounds of boosting on A, B, C (churned) and D (stayed) with a learning rate of 0.5. The dashed leftovers shrink every round, from a total of 1.5000 to 1.2500 to 1.1250, and the next tree is always trained on the dashes, never on the circles.
Round 0. Before any tree, every customer is predicted at the average label, 0.7500. The three churners are under-predicted by 0.2500 each and the stayer is over-predicted by 0.7500. Those four dashes are tree 1's training data.
Round 1. Tree 1 split A and B from C and D and moved each pair half of its leaf value. A and B improved to 0.8750. C got worse, 0.6250, because it shared a leaf with D. That is the price of a tree that cannot tell them apart, and it is the dash tree 2 will see.
Round 2. Tree 2 isolated C and fixed it; A, B and C now sit at 0.8125. D is still at 0.5625 with a label of 0, the largest leftover on the picture. Fixing D needs a leaf with only D in it, which is the first step toward memorising every customer. That is why a boosted model needs a stopping rule.
Before the two of them argue, look at what each one actually does, with the numbers
from this section and the next written on the picture. Every line in the chat below
points at something drawn here.
Fig. 3.3c — The two mechanisms side by side, with their scoreboards. Left: 300 trees grown at once and averaged, which removes the error that differs between trees and keeps the error they share; on section 04's test rows, 0.852 against one deep tree's 0.787. Right: a queue where each tree is trained on the leftovers of the trees before it, shrunk by 0.05, with a rule that stops the queue; on section 05's test rows, ROC-AUC 0.9272 against the logistic baseline's 0.8932, stopping at tree 109.
The forest. Every tree sees the same question and its own re-draw of the rows, and the 300 answers are averaged. The two bars under the trees are the two kinds of error: the part that changes from tree to tree averages to nothing, and the part every tree gets wrong the same way survives, however many trees you add. The scoreboard is Fig. 3.2c in two lines.
Boosting. Trees stand in a queue. The accented arrows carry leftovers, not labels, so tree 2 is asked "what did tree 1 miss?" Each correction is shrunk by the learning rate, and a stopping rule watches a held-out slice. The red dashed line is what happens without that rule: the walk from Fig. 3.3b continues until every customer has a leaf. The scoreboard is the section 05 output: three AUC points over the baseline, 109 trees chosen by the data.
The judge. Neither scoreboard means anything unless the test customers were kept out of training. That is the one point both sides concede, and it is why the module keeps a test slice that is touched once.
Fireside chat
Tonight's talk: The Random Forest and Gradient Boosting argue over the question, "Who's more important?"
The Random Forest
Gradient Boosting
Start with the scoreboard under marker 1 in Fig. 3.3c. One tree, unlimited depth: train 1.000, test 0.787. Me, three hundred trees, no tuning, one line of code: test 0.852, best on the board. Every one of my trees trains at the same time, one per core. I do not have a learning rate. I do not have a schedule. I have a vote.
the forest points at the section 04 numbers on the left of the picture: a single deep tree memorised its training rows (1.000) and did worst on new ones (0.787); 300 averaged trees did best (0.852) with nothing to tune.
Look at the two bars under your trees. Averaging only shrinks the top one, the part of the error that changes from tree to tree. The bottom bar, the mistakes all three hundred of you make the same way, you keep. That bar is the floor with your name on it, and tree three hundred and one does not lower it.
averaging cancels errors only where the trees disagree. Whatever every tree gets wrong in the same way survives the vote, however many trees are added. The bottom red bar in the left panel is that surviving part.
And your trees stand in a queue, marker 2. Number two cannot start until number one has finished being wrong. You call that learning from mistakes. I call it a single point of failure with a learning rate.
boosting is sequential: each tree needs the previous tree's leftovers as its training data, so the trees cannot be grown at the same time the way the forest's can.
Each tree in that queue is built on every core you have; only the queue is sequential. And the queue is the point. Read the words on the accented arrows: tree two is not asked "who churns?", it is asked "what did tree one miss?" That is a harder question and a more useful one. It is why I win the tabular benchmarks and you place.
inside one tree, the search for the best split runs in parallel. The sequence matters because each tree targets the error that is still left, which is how boosting reaches lower error than averaging can.
You win them after someone spends a week tuning you. Learning rate, depth, row sampling, column sampling, a ceiling on trees, a rule for when to stop. Skip the last one and you keep walking. The red dashed line under marker 2 is where that walk ends: a leaf for customer D, then a leaf for everyone. You memorize the training set in slow motion.
boosting has many knobs, and without early stopping it keeps adding trees until it fits every training row. That is the single tree's overfitting from Fig. 3.2c, arriving one small step at a time.
Which is why I ship with early stopping and a validation slice, the third line under my trees, and why a small learning rate is the practitioner's default. You memorized the training set too. Train 1.000, on your own scoreboard. You just got lucky that your errors cancelled. Mine are managed.
the forest also scores 1.000 on its training rows. It generalises because its trees' errors cancel, not because any single tree was careful. Boosting limits its error on purpose, with the learning rate and the stopping rule.
Lucky is a strange word for a mechanism with a proof. Unrelated errors cancel: that is the top bar going to zero. That is not luck; that is why anyone runs replicas behind a quorum. And when a team has ten minutes and a new feature set, they run me first, because I tell them whether the columns carry signal without asking a single question about hyperparameters.
averaging independent errors is a mathematical guarantee, the same one behind replicated services. A forest is the quick check of whether the features are any good, because it needs no tuning to give an honest score.
Agreed, you go first. Then they ship me. The scoreboard under marker 2: logistic baseline 0.8932, me 0.9272, and I stopped myself at tree 109 of 2,000. With a report per customer saying why. Nobody frames a forest's vote count.
on the section 05 test rows, XGBoost beat the logistic baseline by about three AUC points, chose its own number of trees, and its scores can be explained one customer at a time, which is what Marcus's CSMs need.
Nobody frames anything until it beats the baseline on a test set neither of us has touched. Marker 3. If you and I agree and both barely beat 0.8932, the problem is the columns, not the model.
a comparison only counts on held-out customers. If both ensembles land near the baseline, the features lack signal, and no choice of model will fix that.
On that we agree. Run us both on the same held-out slice and we'll revisit who's more important.
the argument is settled by measurement on the same test rows, not by which mechanism sounds better.
I'll be finished first.
the forest trains in parallel, so it finishes sooner. Which one scores higher is a separate question, and the scoreboards answer it.
05 · The industry toolXGBoost, Done Like a Professional
The scoreboard in section 04 says a forest beats one tree, and the pencil rounds showed boosting closing the gap one small step at a time, with the danger that it never stops walking. Marcus needs the production version: a boosted model that stops itself, beats a simple baseline on customers it has never seen, and prints a reason next to every score so a CSM knows which lever to pull. That is XGBoost, run with three habits professionals never skip.
XGBoost ("eXtreme Gradient Boosting") is gradient boosting with the
production engineering already done: L1/L2 regularization built into the split criterion,
second-order optimization, histogram-based split finding, native handling of missing
values, and — the habit that separates practitioners from tutorial-followers —
early stopping against a held-out validation set.
You don't guess the
number of trees; you set a generous ceiling, watch validation AUC every round, and stop
50 rounds after it stops improving.
Three professional habits are baked into the code
below, and each one guards against a real failure: a three-way split (the val
slice exists only for early stopping — touch the test set once, at the end), a
logistic baseline from Module 02 (if boosting can't beat it, ship the simpler
model), and scale_pos_weight for the class imbalance that every churn
dataset has — only ~21% of customers churn, and an unweighted model learns that
predicting "nobody churns" is an easy way to look accurate.
Two of those habits are a picture before they are code. The 12,000 generated customers
are cut into three slices before anything is fitted, and inside every slice about one
customer in five churns, which is why the churners need extra weight.
Fig. 3.3d — The two habits drawn: a 64 / 16 / 20 split of 12,000 customers (train 7,680, validation 1,920, test 2,400, from the script's first output line), and the class balance inside it, 20.6% churners, which gives a class weight of 0.794 ÷ 0.206 ≈ 3.85. The split is stratified, so every slice has the same 20.6%.
Three slices. The training slice is where the preprocessor learns its averages and where every tree is grown. The validation slice is never trained on; its only job is to tell early stopping when to quit. The test slice is looked at once, for the final score, so that score is an honest estimate of how the model will do on next month's customers.
One in five. Predict "nobody churns" and you are right 79.4% of the time while missing every churner Marcus cares about. The class weight multiplies each churner's error by about 3.85, computed from the training slice only, so the model pays for the customers it would otherwise ignore.
The file below is long because it is the real thing. Two parts of it have not been taught yet: the ColumnTransformer that prepares the columns, and the shap calls near the bottom that explain a prediction. The step-by-step list says what each does in one line, and SHAP gets its own subsection right after the output.
Build it in chunks
We build churn_engine.py in six chunks. Each one runs on its own; the whole file comes at the end.
Chunk 1 — make 12,000 fake subscribers
A churn model needs customers to learn from, and we cannot share a real company's. This chunk draws eight columns for each subscriber: how long they have stayed, what they pay, how many support tickets they filed, how often they log in, and three category columns. There is no churn column yet.
Step-by-step: what chunk 1 does, in plain English
Fix the random seed so every run builds the same customers.
Draw the five number columns: tenure, charges, tickets, logins and feature adoption.
Draw the three category columns (contract, tech support, payment method) with the stated odds.
Return all of it as one table.
churn_engine.py — chunk 1runs offline
def generate_churn_data(n=12_000, seed=42):
"""Synthetic SaaS subscribers with realistic — and non-linear — churn signals."""
rng = np.random.default_rng(seed)
tenure = rng.integers(1, 72, n)
charges = np.round(rng.uniform(20, 150, n), 2)
tickets = rng.poisson(2.2, n)
logins = rng.poisson(12, n)
adoption = np.round(rng.beta(2, 5, n) * 100, 1) # % of features used
contract = rng.choice(["Month-to-Month", "One-Year", "Two-Year"], n, p=[0.55, 0.25, 0.20])
support = rng.choice(["Yes", "No"], n, p=[0.40, 0.60])
payment = rng.choice(["Credit Card", "Bank Transfer", "E-Check"], n, p=[0.30, 0.30, 0.40])
m2m = contract == "Month-to-Month"
# (returns a DataFrame of the eight feature columns)
rng.beta(2, 5, n) — draws numbers between 0 and 1 that bunch near the low end, a good shape for “share of features used”. rng.poisson — counts such as tickets.
Run python3 chunk1_features.py. You should see 12,000 rows and 8 columns, then three sample rows.
Chunk 2 — decide who churns, with rules a straight line cannot capture
Chunk 1 has customers but no outcome. This chunk writes the hidden rule: price hurts only people on month-to-month contracts, tickets hurt only without a support plan, and there are two tenure traps. Those “only when” rules are exactly what trees can learn and a straight-line model cannot.
Step-by-step: what chunk 2 does, in plain English
Build a churn score from the columns; each “only when” term is a number multiplied by a True/False condition.
Turn the score into a probability with the logistic S-curve.
Roll a dice per customer: churn if the dice number is below their probability.
Add the Churn column to the returned table.
churn_engine.py — chunk 2runs offline
# Real churn is non-linear, so the generator is too: price pain only bites
# when leaving is frictionless, ticket pain only without a support plan,
# and the tenure hazard has an onboarding cliff plus a renewal-window
# spike. A linear model cannot fully express any of these.
logit = (
0.058 * (charges - 65) * m2m + 0.008 * (charges - 65) * ~m2m
- 0.05 * tenure
+ 1.7 * ((tenure >= 10) & (tenure <= 14)) # renewal-window spike
+ 1.1 * (tenure < 4) # onboarding cliff
+ 0.70 * tickets * (support == "No")
+ 0.10 * tickets * (support == "Yes")
- 0.03 * logins - 0.015 * adoption
+ 0.5 * (payment == "E-Check") + 0.6 * m2m
- 2.4
)
churn = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
# ...and the return now adds: "Churn": churn
Multiplying by a boolean — 0.7 * tickets * (support == "No") — switches a term on only for the rows where the condition is True.
Run python3 chunk2_churn_rule.py. Churn should be about 21% overall: near 30% for Month-to-Month and under 10% for the other two contracts.
Chunk 3 — hold out data honestly and set a baseline to beat
Before a fancy model, split the rows three ways and fit the simple logistic regression from module 02. If XGBoost cannot beat it, you ship the simple one. The validation slice exists only so the next chunk can decide when to stop adding trees.
Step-by-step: what chunk 3 does, in plain English
Split off 20% as the final test set, then 20% of the rest as a validation set, keeping the churn rate equal in all three.
Make a preprocessor: scale the numbers, one-hot the categories.
Fit the preprocessor on the training rows only, then transform all three slices.
Fit a logistic regression on the training rows and score it on the test set with ROC-AUC.
churn_engine.py — chunk 3runs offline
def make_splits(df):
"""64 / 16 / 20. The val slice exists ONLY for early stopping."""
train_full, test = train_test_split(
df, test_size=0.20, stratify=df["Churn"], random_state=42)
train, val = train_test_split(
train_full, test_size=0.20, stratify=train_full["Churn"], random_state=42)
return train, val, test
def build_preprocessor():
# Trees don't need scaling (splits only care about ordering), but the
# logistic baseline does — sharing one preprocessor keeps the comparison fair.
return ColumnTransformer([
("num", StandardScaler(), NUM_COLS),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), CAT_COLS),
])
# in the main block:
train, val, test = make_splits(df)
X_tr, y_tr = train[NUM_COLS + CAT_COLS], train["Churn"].to_numpy()
X_va, y_va = val[NUM_COLS + CAT_COLS], val["Churn"].to_numpy()
X_te, y_te = test[NUM_COLS + CAT_COLS], test["Churn"].to_numpy()
print(f"churn rate {df['Churn'].mean():.1%} "
f"(train {len(train)} / val {len(val)} / test {len(test)})")
pre = build_preprocessor().fit(X_tr) # fit on TRAIN only — no leakage
Xt_tr, Xt_va, Xt_te = pre.transform(X_tr), pre.transform(X_va), pre.transform(X_te)
feat_names = [n.split("__", 1)[1] for n in pre.get_feature_names_out()]
# --- Baseline: the Module 02 workhorse. Beat this, or ship the simpler model.
base = LogisticRegression(max_iter=2000, class_weight="balanced").fit(Xt_tr, y_tr)
base_auc = roc_auc_score(y_te, base.predict_proba(Xt_te)[:, 1])
train_test_split(..., stratify=...) — keeps the class mix equal in both halves. class_weight="balanced" — counts the rarer class more.
Run python3 chunk3_baseline.py. Expect the split sizes and a logistic AUC near 0.89.
terminalactual output
churn rate 20.6% (train 7680 / val 1920 / test 2400)
logistic ROC-AUC 0.8932
Chunk 4 — the challenger: XGBoost that stops itself
Now the real model. XGBoost builds trees one after another, each fixing the last one's mistakes. We allow up to 2,000 trees and let the validation slice call a halt when more trees stop helping.
Step-by-step: what chunk 4 does, in plain English
Compute the ratio of stayers to churners in the training rows, so the rare class is not drowned out.
Create the classifier: slow learning rate, trees at most 5 questions deep, each tree sees 90% of rows and columns.
Fit with the validation slice as a referee; stop after 50 trees in a row bring no improvement.
Score the test set and print the stopping point, logistic AUC, XGBoost AUC and PR-AUC.
churn_engine.py — chunk 4runs offline
# --- Challenger: XGBoost with early stopping against the val set.
spw = (y_tr == 0).sum() / (y_tr == 1).sum() # from the TRAIN fold only
model = xgb.XGBClassifier(
n_estimators=2000, # a ceiling, not a target —
early_stopping_rounds=50, # validation AUC picks the real number
learning_rate=0.05, max_depth=5,
subsample=0.9, colsample_bytree=0.9,
scale_pos_weight=spw, # pay ~4x more attention to the rare class
eval_metric="auc", tree_method="hist", random_state=42,
)
model.fit(Xt_tr, y_tr, eval_set=[(Xt_va, y_va)], verbose=False)
proba_te = model.predict_proba(Xt_te)[:, 1]
print(f"stopped at tree {model.best_iteration} of 2000")
print(f"logistic ROC-AUC {base_auc:.4f}")
print(f"xgboost ROC-AUC {roc_auc_score(y_te, proba_te):.4f} "
f"PR-AUC {average_precision_score(y_te, proba_te):.4f}")
early_stopping_rounds — stop training when the validation score stalls. eval_set — the slice used as the referee.
Run python3 chunk4_xgboost.py. The new lines print where it stopped and both AUCs; XGBoost should win.
terminalactual output
...
stopped at tree 109 of 2000
logistic ROC-AUC 0.8932
xgboost ROC-AUC 0.9272 PR-AUC 0.8112
Chunk 5 — ask which columns drive the model (SHAP)
A CSM will not act on “the model says 0.87”. SHAP gives every feature a signed push for every customer. Averaging the size of those pushes over the test set gives a global ranking.
Step-by-step: what chunk 5 does, in plain English
Build a tree explainer from the fitted model.
Compute each feature's push for every test customer.
Average the absolute pushes per feature.
Print the five biggest.
churn_engine.py — chunk 5runs offline
# --- SHAP: signed, per-prediction attributions (log-odds space).
explainer = shap.TreeExplainer(model)
mean_abs = np.abs(explainer.shap_values(Xt_te)).mean(axis=0)
print("\nglobal drivers (mean |SHAP|):")
for name, v in sorted(zip(feat_names, mean_abs), key=lambda kv: -kv[1])[:5]:
print(f" {name:<30s} {v:.3f}")
shap.TreeExplainer — the fast, exact SHAP calculator for tree models. Pushes are in log-odds, positive means toward churn.
Run python3 chunk5_shap.py. Five “global drivers” lines appear at the end.
The last step packages everything: one customer in, a risk band, an action and the three strongest reasons out. It is a function over the objects built in chunks 3 to 5. Chunk 6 is the finished file.
Step-by-step: what chunk 6 does, in plain English
Turn the customer dictionary into a one-row table and apply the saved preprocessor.
Ask the model for the churn probability, and the explainer for per-feature pushes.
Keep the three biggest pushes by size.
Pick a band (0.40 and 0.70 are the cut-offs) and return everything as JSON.
churn_engine.py — chunk 6runs offline
def churn_report(customer: dict, pre, model, explainer, feat_names) -> str:
"""JSON in → risk band + the top reasons, in terms a CSM can read."""
row = pd.DataFrame([customer])[NUM_COLS + CAT_COLS]
x = pre.transform(row)
prob = float(model.predict_proba(x)[0, 1])
contrib = explainer.shap_values(x)[0] # signed, log-odds space
top = sorted(zip(feat_names, contrib), key=lambda kv: -abs(kv[1]))[:3]
if prob >= 0.70:
band, action = "CRITICAL", "CSM call within 24h + targeted retention offer"
elif prob >= 0.40:
band, action = "MEDIUM", "proactive check-in + feature-adoption guide"
else:
band, action = "LOW", "no intervention"
return json.dumps({
"customer_id": customer.get("CustomerID", "UNKNOWN"),
"churn_probability": round(prob, 3),
"risk_level": band,
"action": action,
"top_drivers": [{"feature": name,
"direction": "towards churn" if v > 0 else "protective",
"weight": round(float(v), 2)} for name, v in top],
}, indent=2)
# at the end of the main block:
# --- Real-time inference: one at-risk customer through the full path.
print("\n" + churn_report({
"CustomerID": "CUST-9842", "TenureMonths": 3, "MonthlyCharges": 118.50,
"SupportTickets": 5, "LoginFrequency": 2, "FeatureAdoption": 8.5,
"ContractType": "Month-to-Month", "TechSupport": "No",
"PaymentMethod": "E-Check",
}, pre, model, explainer, feat_names))
sorted(..., key=lambda kv: -abs(kv[1])) — sort by the size of the push, ignoring its sign.
Run python3 chunk6_report.py. The tail is a JSON report for CUST-9842.
The file below is the finished program. Its chunk comments mark where each rung landed: lines 7–37 are chunk 1; lines 38–62 are chunk 2; lines 63–81 are chunk 3, first half; lines 82–107 are chunk 6, first half; lines 108–124 are chunk 3, second half; lines 125–143 are chunk 4; lines 144–151 are chunk 5; lines 152–159 are chunk 6, second half.
Step-by-step: what churn_engine.py does, in plain English
Bring in json for the report, numpy and pandas for the data, shap for explanations, xgboost for the model, and from scikit-learn: a column transformer, logistic regression, two metrics, the splitter, and two encoders.
Name the columns: NUM_COLS holds the five numeric features, CAT_COLS the three categorical ones (contract type, tech support, payment method).
Define generate_churn_data(n, seed): draw 12,000 synthetic subscribers. The churn score is built from interactions on purpose: price pain only bites on month-to-month plans, ticket pain only without a support plan, and tenure has an onboarding cliff plus a renewal-window spike. Return everything as a DataFrame with a 0/1 Churn column.
Define make_splits(df): carve off 20% as the test set, then 20% of what remains as the validation set, giving 64/16/20. Both splits are stratified so each slice has the same churn rate. The validation slice exists only so early stopping has something to watch.
Define build_preprocessor(): a ColumnTransformer that standardizes the numeric columns and one-hot encodes the categorical ones (one 0/1 column per category). Trees do not need the scaling; the logistic baseline does. Sharing one preprocessor keeps the comparison fair.
Define churn_report(customer, ...): turn one customer's dictionary into a one-row DataFrame, transform it, read the churn probability, and ask the SHAP explainer for one signed contribution per feature. Keep the three largest by absolute size, choose a risk band and an action from the probability, and return it all as JSON.
In the main block: generate the data, split it, separate the features from the label in each slice, and print the churn rate and the slice sizes.
Fit the preprocessor on the training rows only, then transform all three slices with it. Fitting on everything would leak the test set's averages into training. Recover readable feature names for the report.
Baseline: fit a logistic regression with balanced class weights and record its ROC-AUC on the test set. If XGBoost cannot beat this, ship the simpler model.
Compute spw, stayers divided by churners, from the training fold only. It comes to about 4.
Build the XGBClassifier: a ceiling of 2,000 trees, stop when validation AUC has not improved for 50 rounds, learning rate 0.05, depth 5, 90% of rows and 90% of columns per tree, the class weight, AUC as the watched metric, and histogram-based split finding.
Fit it with the validation slice as eval_set, then predict churn probabilities for the test rows.
Print the round at which validation AUC peaked, the baseline's ROC-AUC, and XGBoost's ROC-AUC and PR-AUC on the same untouched test set.
SHAP: build a TreeExplainer around the model, compute the mean absolute contribution of each feature over the test rows, and print the top five. These are the global drivers.
Run one at-risk customer through churn_report and print the JSON. This is the path a real-time endpoint would take.
churn_engine.pyruns offline
"""SaaSify Churn Prediction Engine — XGBoost + early stopping + SHAP.
Proper train/val/test discipline, a logistic baseline to beat, and
per-customer explanations a CSM can actually read.
"""
# pip install "xgboost>=3.0,<4" "scikit-learn>=1.6" "shap>=0.48" "pandas>=2.2"
# ── chunk 1: fake subscribers ──
import json
import numpy as np
import pandas as pd
import shap
import xgboost as xgb
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score, roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder, StandardScaler
NUM_COLS = ["TenureMonths", "MonthlyCharges", "SupportTickets",
"LoginFrequency", "FeatureAdoption"]
CAT_COLS = ["ContractType", "TechSupport", "PaymentMethod"]
def generate_churn_data(n=12_000, seed=42):
"""Synthetic SaaS subscribers with realistic — and non-linear — churn signals."""
rng = np.random.default_rng(seed)
tenure = rng.integers(1, 72, n)
charges = np.round(rng.uniform(20, 150, n), 2)
tickets = rng.poisson(2.2, n)
logins = rng.poisson(12, n)
adoption = np.round(rng.beta(2, 5, n) * 100, 1) # % of features used
contract = rng.choice(["Month-to-Month", "One-Year", "Two-Year"], n, p=[0.55, 0.25, 0.20])
support = rng.choice(["Yes", "No"], n, p=[0.40, 0.60])
payment = rng.choice(["Credit Card", "Bank Transfer", "E-Check"], n, p=[0.30, 0.30, 0.40])
m2m = contract == "Month-to-Month"
# ── chunk 2: who churns ──
# Real churn is non-linear, so the generator is too: price pain only bites
# when leaving is frictionless, ticket pain only without a support plan,
# and the tenure hazard has an onboarding cliff plus a renewal-window
# spike. A linear model cannot fully express any of these.
logit = (
0.058 * (charges - 65) * m2m + 0.008 * (charges - 65) * ~m2m
- 0.05 * tenure
+ 1.7 * ((tenure >= 10) & (tenure <= 14)) # renewal-window spike
+ 1.1 * (tenure < 4) # onboarding cliff
+ 0.70 * tickets * (support == "No")
+ 0.10 * tickets * (support == "Yes")
- 0.03 * logins - 0.015 * adoption
+ 0.5 * (payment == "E-Check") + 0.6 * m2m
- 2.4
)
churn = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
return pd.DataFrame({
"TenureMonths": tenure, "MonthlyCharges": charges,
"SupportTickets": tickets, "LoginFrequency": logins,
"FeatureAdoption": adoption, "ContractType": contract,
"TechSupport": support, "PaymentMethod": payment, "Churn": churn,
})
# ── chunk 3 (part 1): the splits and the preprocessor ──
def make_splits(df):
"""64 / 16 / 20. The val slice exists ONLY for early stopping."""
train_full, test = train_test_split(
df, test_size=0.20, stratify=df["Churn"], random_state=42)
train, val = train_test_split(
train_full, test_size=0.20, stratify=train_full["Churn"], random_state=42)
return train, val, test
def build_preprocessor():
# Trees don't need scaling (splits only care about ordering), but the
# logistic baseline does — sharing one preprocessor keeps the comparison fair.
return ColumnTransformer([
("num", StandardScaler(), NUM_COLS),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), CAT_COLS),
])
# ── chunk 6 (part 1): the report function, defined here and called at the bottom ──
def churn_report(customer: dict, pre, model, explainer, feat_names) -> str:
"""JSON in → risk band + the top reasons, in terms a CSM can read."""
row = pd.DataFrame([customer])[NUM_COLS + CAT_COLS]
x = pre.transform(row)
prob = float(model.predict_proba(x)[0, 1])
contrib = explainer.shap_values(x)[0] # signed, log-odds space
top = sorted(zip(feat_names, contrib), key=lambda kv: -abs(kv[1]))[:3]
if prob >= 0.70:
band, action = "CRITICAL", "CSM call within 24h + targeted retention offer"
elif prob >= 0.40:
band, action = "MEDIUM", "proactive check-in + feature-adoption guide"
else:
band, action = "LOW", "no intervention"
return json.dumps({
"customer_id": customer.get("CustomerID", "UNKNOWN"),
"churn_probability": round(prob, 3),
"risk_level": band,
"action": action,
"top_drivers": [{"feature": name,
"direction": "towards churn" if v > 0 else "protective",
"weight": round(float(v), 2)} for name, v in top],
}, indent=2)
if __name__ == "__main__":
# ── chunk 3 (part 2): split, preprocess, fit the baseline ──
df = generate_churn_data()
train, val, test = make_splits(df)
X_tr, y_tr = train[NUM_COLS + CAT_COLS], train["Churn"].to_numpy()
X_va, y_va = val[NUM_COLS + CAT_COLS], val["Churn"].to_numpy()
X_te, y_te = test[NUM_COLS + CAT_COLS], test["Churn"].to_numpy()
print(f"churn rate {df['Churn'].mean():.1%} "
f"(train {len(train)} / val {len(val)} / test {len(test)})")
pre = build_preprocessor().fit(X_tr) # fit on TRAIN only — no leakage
Xt_tr, Xt_va, Xt_te = pre.transform(X_tr), pre.transform(X_va), pre.transform(X_te)
feat_names = [n.split("__", 1)[1] for n in pre.get_feature_names_out()]
# --- Baseline: the Module 02 workhorse. Beat this, or ship the simpler model.
base = LogisticRegression(max_iter=2000, class_weight="balanced").fit(Xt_tr, y_tr)
base_auc = roc_auc_score(y_te, base.predict_proba(Xt_te)[:, 1])
# ── chunk 4: XGBoost with early stopping ──
# --- Challenger: XGBoost with early stopping against the val set.
spw = (y_tr == 0).sum() / (y_tr == 1).sum() # from the TRAIN fold only
model = xgb.XGBClassifier(
n_estimators=2000, # a ceiling, not a target —
early_stopping_rounds=50, # validation AUC picks the real number
learning_rate=0.05, max_depth=5,
subsample=0.9, colsample_bytree=0.9,
scale_pos_weight=spw, # pay ~4x more attention to the rare class
eval_metric="auc", tree_method="hist", random_state=42,
)
model.fit(Xt_tr, y_tr, eval_set=[(Xt_va, y_va)], verbose=False)
proba_te = model.predict_proba(Xt_te)[:, 1]
print(f"stopped at tree {model.best_iteration} of 2000")
print(f"logistic ROC-AUC {base_auc:.4f}")
print(f"xgboost ROC-AUC {roc_auc_score(y_te, proba_te):.4f} "
f"PR-AUC {average_precision_score(y_te, proba_te):.4f}")
# ── chunk 5: global SHAP drivers ──
# --- SHAP: signed, per-prediction attributions (log-odds space).
explainer = shap.TreeExplainer(model)
mean_abs = np.abs(explainer.shap_values(Xt_te)).mean(axis=0)
print("\nglobal drivers (mean |SHAP|):")
for name, v in sorted(zip(feat_names, mean_abs), key=lambda kv: -kv[1])[:5]:
print(f" {name:<30s} {v:.3f}")
# ── chunk 6 (part 2): one customer through the full path ──
# --- Real-time inference: one at-risk customer through the full path.
print("\n" + churn_report({
"CustomerID": "CUST-9842", "TenureMonths": 3, "MonthlyCharges": 118.50,
"SupportTickets": 5, "LoginFrequency": 2, "FeatureAdoption": 8.5,
"ContractType": "Month-to-Month", "TechSupport": "No",
"PaymentMethod": "E-Check",
}, pre, model, explainer, feat_names))
Three things to notice in that output. The model stopped itself after tree 109 — the
validation set said "no further improvement", training halted 50 rounds later, and
roughly 1,840 of the 2,000 allowed trees were never built. XGBoost beat the logistic baseline by ~3 AUC points, and it earned that gap
honestly: the lift comes from the interaction terms (new-and-expensive,
month-to-month-with-tickets) that no amount of coefficient-fitting can express. And the
per-customer report is signed: it doesn't just say "TenureMonths matters", it
says tenure pushed this customer toward churn and by how much. That last part is
SHAP, and it deserves its own picture.
The first of those three, the model stopping itself, is a rule you should be able to
draw. Here it is, with the two numbers the output printed marked on it.
Fig. 3.3e — Early stopping, drawn. After every new tree the model scores the validation slice. The score peaked at tree 109 and did not beat that peak for 50 rounds, so training stopped at tree 159 and the model kept the version from tree 109. The only numbers taken from the output are 109, the patience of 50 and the ceiling of 2,000; the shape of the curve is representative, because the script does not print the per-round scores.
The best round. Each tree adds a small correction (learning rate 0.05), so validation AUC climbs quickly at first and then levels off. Tree 109 is where it stopped climbing. model.best_iteration is this number, and predictions use the model as it was at this round.
The stop. The model does not know the peak is a peak until it has waited. Fifty more trees were built, none improved the validation score, and at tree 159 training quit. The 50 is early_stopping_rounds; too small and a bumpy curve stops early by accident, too large and you waste time past the peak.
The ceiling.n_estimators=2000 is the most trees allowed, not a target. Here 1,840 of them were never built. If the best round had come out near 2,000, the ceiling was too low and the curve was still climbing when it hit the wall.
Anatomy of the XGBoost call — the one constructor to know by heart
The ceiling.n_estimators is the most trees the model may build, not the number it will use. Early stopping picks the real count. The mistake is setting it low, say 100, so training hits the ceiling while the validation score is still climbing. Check that best_iteration sits well below it: marker 3 in Fig. 3.3e, 109 against 2,000.
The stopping rule. After each new tree the model scores the validation slice. If the score has not improved for 50 rounds, it stops and keeps the best round: the bracket between markers 1 and 2 in Fig. 3.3e. Without an eval_set there is nothing to score, and XGBoost raises an error: "Must have at least 1 validation dataset for early stopping."
The learning rate. How much of each tree's correction is kept: 0.05 means a twentieth. The library's own default is 0.3. Raising it to train faster is the trade the Brain Power below walks through: fewer trees, a coarser model, and usually a lower test score.
Tree depth. How many questions deep each tree may go; depth 5 allows up to 32 leaves. Boosting wants shallow trees, because deep ones memorize in a few rounds. A forest wants deep trees. Copying a forest's depth into a booster is a common first mistake.
Row and column sampling. Each tree sees a random 90% of the rows and 90% of the columns. This is the forest's decorrelation trick borrowed into boosting, and it acts as a regularizer. Set both far lower on a small table and each tree is starved of data.
The class weight. Multiplies the weight of every churner by stayers-divided-by-churners, about 4 here, so the rare class matters during training. Compute it from the training fold only. And remember that it distorts the probabilities: a weighted model's 0.70 is not a 70% chance until you calibrate it, which is the lab's stretch goal. The weight itself is marker 2 in Fig. 3.3d.
The watched metric. The number early stopping listens to. The library default is log-loss, which is fine, but watch the metric the business cares about. Under heavy imbalance that is often "aucpr", the area under the precision-recall curve.
The validation slice. The data early stopping watches. It must be the validation split, never the test split: if the test set chooses the number of trees, the test score is no longer an honest estimate. Pass it already transformed by the preprocessor that was fit on the training rows.
SHAP: from "the model said so" to "here's why"
The engine scored every customer and beat the logistic baseline, 0.9272 to 0.8932 on the untouched test rows. But a score alone does not tell a customer-success manager which lever to pull, and Marcus asked for the reason next to the name. SHAP is the method that splits one customer's score into a signed share per feature. It is what turns the ranked list into a call list, and the third bar of Fig. 3.0b into a plan.
SHAP (SHapley Additive exPlanations) borrows a fair-credit-assignment
result from cooperative game theory: treat each feature as a player, the prediction as
the payout, and compute each player's fair share.
For one customer, SHAP decomposes the
score into a sum — start at the model's base value (the average customer's log-odds) and
add one signed contribution per feature until you land exactly on this customer's score.
That additivity is what makes it a stakeholder tool, not just a debugging tool: it turns
a black-box number into a walkable ledger.
It's also increasingly a compliance
requirement — under the EU AI Act, customers affected by automated decisions have a
right to a meaningful explanation.
Fig. 3.4 — SHAP waterfall for one flagged customer (CUST-7311): starting from the model's base value, each feature adds a signed contribution — six push toward churn (right), the below-average price is mildly protective (left) — landing exactly on the final score, σ(1.25) ≈ 0.78.
The starting point. Every customer starts at the same base value, −1.35 in log-odds, which is the average customer's score and corresponds to the 21% churn rate of the whole table. SHAP explains the distance from here to this customer's score, not the score from zero.
The biggest push. A month-to-month contract adds +0.78. Each red bar starts where the previous one ended, so the bars are a ledger: read them top to bottom and you have walked from the average customer to this one, one feature at a time.
The one protective feature. A $62 bill, below the average, pulls the score back by 0.23. The sign is the point: a CSM reading this knows price is not the lever to pull for CUST-7311, and tickets or the contract are.
The landing. −1.35 + 0.78 + 0.66 + 0.55 + 0.37 + 0.26 + 0.21 − 0.23 = +1.25 exactly, and squashing +1.25 through the logistic function gives 0.78. The contributions add up to the prediction with nothing left over. That additivity is what makes the report trustworthy.
The same tool run over all 2,400 test customers, and averaged, gives the five global
drivers the output printed. This is the answer to Marcus's second question, which levers
matter across the whole customer base, and it is a picture of the output block above.
Fig. 3.4b — The global drivers from the output: the average size of each feature's push, ignoring direction, across the 2,400 test customers. Price and tenure lead; the contract type and the support-plan and ticket pair follow, and those last two are the interaction the data generator built in.
The two big levers. MonthlyCharges (1.055) and TenureMonths (0.924) move scores most, on average. These are unsigned averages, so they say how much a feature matters, not which way it pushes. For direction on one customer you read the waterfall in Fig. 3.4.
The pair at the bottom. TechSupport = No (0.499) and SupportTickets (0.492) are almost tied because they act together: the generator made tickets painful only for customers without a support plan. A boosted tree learned that interaction from the data; a linear model would have needed it hand-built.
🧠 Brain power
Before reading on: you bump learning_rate from 0.05 to
0.5 and keep early stopping on. What happens to (a) the number of trees built, (b)
training time, and (c) test AUC?
Reveal the answer
(a) Far fewer trees — each one takes a 10× bigger step, so validation AUC plateaus
after a few dozen rounds instead of a couple hundred. (b) Training gets proportionally
faster.
(c) Test AUC usually drops slightly: big steps build a coarser function that
overshoots fine structure in the data.
η vs. number-of-trees is the fundamental
boosting trade — the practitioner default is a small learning rate (0.01–0.1)
with a high tree ceiling, letting early stopping find the sweet spot. You pay compute
to buy generalization.
Questions you might be asking now
The engine printed one probability per customer and a stopping round, and the Brain Power question just turned the learning rate up. The questions below open the boosted model, using the same four customers throughout. Every number comes from rerunning boosting_lr_sweep.py, trace_one_customer.py or forest_vs_boosting.py, which rebuild churn_engine.py's exact data and model.
The four customers every answer below uses. The first three are rows of the 7,680-customer training slice, so their outcome is known. CUST-9842 is the live customer from the output above. The last column is the boosted model's churn probability.
Customer
Tenure
Monthly charges
Support tickets
Contract
Support plan
Churned?
Model says
#6023
64 months
$22.77
0
Two-year
Yes
No
0.0070
#10792
22 months
$76.01
1
Month-to-month
No
Yes
0.4512
#1476
35 months
$82.42
3
Month-to-month
No
No
0.5701
CUST-9842
3 months
$118.50
5
Month-to-month
No
Not yet known
0.9855
What is the learning rate in gradient boosting? Is it the same learning rate as in Module 02?
Partly. The letter η (eta) and its job, keeping only a fraction of each proposed step, are the same. What gets shrunk is different: in Module 02 it was a step of the weights; here it is one tree's correction to every customer's score. For CUST-9842, tree 1 adds +0.0872 at η = 0.05 and ten times as much, +0.8724, at η = 0.5.
A boosted model's score for a customer is a log-odds: a number the sigmoid squashes into a probability, where 0 means 50% and bigger means likelier to churn. Every customer starts at the same log-odds, and every tree adds one small number to it.
The learning rate sets the size of those numbers: each tree works out a full correction, and the model keeps η times it. The pencil exercise in section 04 did this in probabilities; here it is at three rates.
Before any tree. A, B, C and D start at 0.7500. Tree 1 proposes +0.2500 for A and B, and −0.2500 for C and D.
η = 1.0 keeps all of it. A and B jump to 0.7500 + 1.0 × 0.2500 = 1.0000. C and D drop to 0.5000. C, a churner, is now at a coin flip, because tree 1 could not tell C from D.
η = 0.5, the exercise's choice. A and B move to 0.8750, and C and D to 0.6250.
η = 0.05, churn_engine.py's choice. A and B move to 0.7625, and C and D to 0.7375. The mistake about C costs only 0.0125, and later trees have room to fix it.
The real model does exactly this. boosting_lr_sweep.py trains churn_engine.py's model twice, at η = 0.05 and at η = 0.5. Tree 1 asks the same questions both times; only the size of its answers changes.
What tree 1 adds to each customer's log-odds at two learning rates. Everyone starts at log-odds 0.0000 (XGBoost's base_score of 0.5). From boosting_lr_sweep.py.
Customer
η = 0.05: tree 1 adds
Probability after tree 1
η = 0.5: tree 1 adds
Probability after tree 1
#6023
−0.0935
0.4767
−0.9345
0.2820
#10792
+0.0013
0.5003
+0.0130
0.5033
#1476
+0.0013
0.5003
+0.0130
0.5033
CUST-9842
+0.0872
0.5218
+0.8724
0.7052
Every number in the η = 0.5 column is ten times its neighbour in the η = 0.05 column. XGBoost stores each leaf already multiplied by η, so the learning rate is literally a multiplier on every tree's output.
The loss climbs to infinity: 123 steps on raw cart values
Nothing blows up; the model overfits in fewer trees
Units of the columns
Matter: unscaled columns shrink the safe η
Do not matter: a tree only compares values with cut-offs
How η is chosen
The largest value whose loss still falls smoothly
A small value, a high tree ceiling, and early stopping
Now the Brain Power question's trade, measured: the same model, data and early stopping, with only η changed.
A learning-rate sweep on SaaSify's split, from boosting_lr_sweep.py. Trees kept is best_iteration + 1; trees built includes the 50 patience rounds.
η (eta)
Trees kept
Trees built
Validation AUC
Test AUC
1.0
5
55
0.9049
0.9106
0.5
9
59
0.9100
0.9237
0.3
27
77
0.9139
0.9213
0.1
46
96
0.9144
0.9239
0.05
110
160
0.9171
0.9272
0.01
564
614
0.9169
0.9267
Each step down in η needs more trees: 5 at η = 1.0, 110 at 0.05, 564 at 0.01. The test AUC rises from 0.9106 to 0.9272 and then stops improving; η = 0.01 builds about five times as many trees for 0.9267. A bigger η means far fewer trees and a slightly lower test score.
Fig. 3.4h draws the multiplier, the sweep, and what η = 1.0 does when nothing stops it.
Fig. 3.4h — The learning rate in boosting, three ways. Top left: the same first tree at η = 0.05 and η = 0.5, its output scaled exactly ten times. Bottom left: six learning rates with early stopping, trees kept against test AUC. Right: η = 1.0 with early stopping switched off, where the training loss keeps falling and the validation loss turns up after tree 5. Values from rerunning boosting_lr_sweep.py.
The multiplier. Same tree, same leaf for CUST-9842 at both rates. At η = 0.5 one tree moves this customer from 50% to 70.52%; at η = 0.05, to 52.18%, leaving room for a hundred more trees.
The sweep. The bars use a log scale, so equal extra length means ten times the trees. The accented row is churn_engine.py's setting and the best test AUC; η = 0.01 needs five times the trees for 0.0005 less.
No explosion. Log-loss is the average penalty for confident wrong probabilities. At η = 1.0 with no stopping, the training log-loss falls every round to 0.0053: the model memorising its training customers. In Module 02 a too-big η sent the loss up to infinity instead.
Where it should have stopped. The validation log-loss is lowest at tree 5, 0.3711, and every later tree makes new customers' probabilities worse, up to 0.7089. With early stopping on, η = 1.0 kept exactly those 5 trees.
Two honest limits. The test AUC differences are small, 0.9106 at worst against 0.9272 at best, and one split can reorder neighbours: η = 0.3 scored below η = 0.5 here. And a small η is paid for in trees: 614 built at η = 0.01 against 160 at 0.05, for no better score.
In boosting, η is the share of each tree's correction that the model keeps. A too-big η does not blow up as in Module 02; it overfits in fewer trees. Keep η small and let early stopping choose the number of trees.
Walk CUST-9842 through the model. How do the trees add up to 0.985?
Every customer starts at a log-odds of 0, a 50% chance. Each of the 110 kept trees drops CUST-9842 into one leaf and adds that leaf's number: +0.0872, then +0.0917, then +0.0886, and so on. The 110 numbers sum to 4.2165, and the sigmoid turns 4.2165 into 0.9855, the 0.985 in the output.
First, which trees count. "stopped at tree 109" counts from 0, so the kept model is 110 trees. Training ran 50 more rounds to confirm the peak, so 160 trees were built, and predict_proba uses only the first 110, numbered 1 to 110 below.
The walk needs one formula, the sigmoid σ (sigma): σ(z) = 1 ÷ (1 + e−z), where z is the log-odds and e is Euler's number, about 2.718.
Start. Every customer begins at log-odds 0.0000, and σ(0) = 1 ÷ (1 + 1) = 0.5000.
Tree 1. CUST-9842 answers up to five yes-or-no questions and lands in a leaf worth +0.0872. Log-odds 0.0872; probability 0.5218.
Trees 2 and 3. Leaves worth +0.0917 and +0.0886. Log-odds 0.1790, then 0.2676; probability 0.5446, then 0.5665.
Trees 4 to 10. Seven more leaves. Log-odds 0.7589; probability 0.6811.
Trees 11 to 110. One hundred more leaves add another 3.4576. The log-odds passes 1.6031 at tree 25, 2.6780 at tree 50 and 4.0186 at tree 100.
Finish. After tree 110 the log-odds is 4.2165, and σ(4.2165) = 1 ÷ (1 + e−4.2165) = 0.9855.
Two things deserve a second look. 108 of the 110 leaves push CUST-9842 toward churn; the two that push away are tiny, the bigger −0.0035 at tree 72. And the pushes shrink: the first 10 trees add about 0.076 each, the last 100 about 0.035 each, because each tree fixes only what earlier trees left over.
Fig. 3.4i — CUST-9842's score as trees are added. The accented line is the kept model, trees 1 to 110; the dashed line is the 50 patience trees that were built and then dropped. Each point on the line is the sum of the leaves so far; the right edge reads each log-odds as a probability. Values from rerunning trace_one_customer.py.
The start. Before any tree, every customer sits at log-odds 0, probability 0.500, set by XGBoost's base_score of 0.5.
The steep first trees. +0.0872, +0.0917 and +0.0886, and ten trees reach 0.7589, probability 0.6811. Early trees are fitted to the largest leftovers in the training table, so they move a customer like this one furthest.
The last kept tree. At tree 110 the sum is 4.2165 and σ(4.2165) = 0.9855, which the output rounds to 0.985. The dotted vertical marks where the validation score peaked.
The dropped trees. Trees 111 to 160 would have taken this customer to 4.7976, probability 0.9918. They did not improve the validation score, so they are never used.
All four customers after the 110 kept trees, from trace_one_customer.py
Customer
Sum of 110 leaves (log-odds)
σ of that sum (probability)
What happened
#6023
−4.9489
0.0070
Stayed
#10792
−0.1957
0.4512
Churned
#1476
+0.2821
0.5701
Stayed
CUST-9842
+4.2165
0.9855
Not yet known
The same arithmetic runs for everyone. #6023's leaves push down to −4.9489. #10792 and #1476 end near zero on the wrong sides, a churner at 0.4512 and a stayer at 0.5701, although both are training customers. Early stopping does not aim for zero training error; it stops when new trees stop helping on the validation slice.
The same 4.2165 can be split by column instead of by tree. XGBoost's built-in TreeSHAP gives TenureMonths +1.330, MonthlyCharges +1.009, SupportTickets +0.694, the month-to-month contract +0.368 and no support plan +0.329, plus smaller parts.
All 14 parts, including SHAP's bias term, add up to 4.2165, and the first three are the top drivers in the output above: 1.33, 1.01 and 0.69. The trace shows how the score was built; SHAP regroups it into reasons.
The honest limit: the walk shows how the score is built, not whether it is right. CUST-9842 is a live customer, and nobody knows yet whether this account will leave. The 0.9855 is only as good as the 0.9272 test AUC behind it.
A boosted model's score is a sum: a starting log-odds plus one small leaf value from every kept tree, squashed by the sigmoid. For CUST-9842 that is 110 leaves adding up to 4.2165, which is a probability of 0.9855.
Is bagging the same thing as boosting? Both grow a lot of trees and combine them.
No. A random forest (bagging) grows its trees independently, each on its own re-draw of the rows, each learning who churned, and averages their answers. Boosting grows trees one after another, each learning what is still wrong, and adds their corrections. On SaaSify's split the forest reaches a test AUC of 0.9169, and XGBoost 0.9272.
The difference is clearest in what tree 2 is given to learn. forest_vs_boosting.py fits both models on the same 7,680 training customers; here are the three from the table above.
What tree 2 is trained on, per customer, from forest_vs_boosting.py. Boosting's leftover is the label minus the probability after tree 1.
Customer
Label
Forest: tree 2 learns
Boosting: probability after tree 1
Boosting: tree 2 learns
#6023
0 (stayed)
0, if its re-draw picked #6023
0.4767
0 − 0.4767 = −0.4767
#10792
1 (churned)
1, if picked
0.5003
1 − 0.5003 = +0.4997
#1476
0 (stayed)
0, if picked
0.5003
0 − 0.5003 = −0.5003
The forest's tree 2 never hears about tree 1. It gets the same labels every other tree gets, on its own re-draw. Boosting's tree 2 gets leftovers instead, so #6023, already nudged down to 0.4767, needs a slightly smaller push than #1476. XGBoost also counts each churner's leftover 3.84 times, the scale_pos_weight.
Everything else follows from that one difference.
Bagging and boosting side by side on SaaSify's split, from forest_vs_boosting.py
Random forest (bagging)
XGBoost (boosting)
How trees are grown
Independently, in any order, on any number of cores
One after another; tree 2 needs tree 1's leftovers
What each tree learns
The label: who churned
The leftover: label minus current probability
How deep each tree goes
No limit: it memorises its re-draw
At most 5 questions: a small correction
How trees combine
The average of 300 answers
The sum of 110 leaf values, then the sigmoid
What combining removes
Mistakes that differ between trees (variance)
Mistakes the trees so far share (bias)
What stops it
A fixed tree count; more trees only settle the average
Early stopping; without it, it keeps fitting leftovers until it memorises
Training AUC
1.0000
0.9524
Test AUC (logistic baseline 0.8932)
0.9169
0.9272
CUST-9842
257 of 300 trees say churn → 0.8567
110 leaves sum to 4.2165 → 0.9855
Fig. 3.4j puts the two combining rules next to each other, with CUST-9842's numbers.
Fig. 3.4j — The two ways of combining trees, on SaaSify's split. Left: 300 independent trees each vote on CUST-9842 and the forest averages the votes. Right: what boosting's tree 2 is asked to learn for three training customers, and the sum that 110 such trees give CUST-9842. Values from rerunning forest_vs_boosting.py and trace_one_customer.py.
The forest's vote. Each square is one of the 300 trees. Grown without a depth limit, each tree answers 0 or 1 for CUST-9842; 257 say churn, so the average is 0.8567. No tree knows what any other said.
Boosting's leftovers. After tree 1 each customer sits near 0.5, and each arrow points from there to the real outcome. Its length and direction are what tree 2 learns; the churner's arrow counts 3.84 times (scale_pos_weight).
The two combining rules. Averaging helps only where trees disagree, so the forest grows them on different re-draws. Adding helps only while leftovers hold signal rather than noise, so boosting needs early stopping.
The two words in the figure's last lines come from statistics. Variance is the error that changes when the training rows change, like the duplicated customer who flipped a tree's first question in section 03. Bias is the error that stays however the rows are drawn. Averaging shrinks the first; adding corrections shrinks the second.
Three honest limits. The forest's training AUC of 1.0000 says nothing, for the reason in section 03. The gap here is 0.0103 AUC, and on another table the forest can win. And the forest needs no learning rate or stopping rule, so run it first as a quick check that the columns carry signal. Ship boosting only if it beats both the forest and the baseline's 0.8932.
Bagging averages independent trees that each learn the labels, which cancels their disagreements. Boosting adds a chain of small trees that each learn the leftovers, which removes shared mistakes until early stopping says enough.
Why gradient boosting still wins on tabular data in 2026
Marcus's engine works, and the first colleague to see it will ask why it is not a neural network. The answer is a judgment about the shape of SaaSify's table: dollars next to counts next to contract types, with cliffs where the risk changes. Interviewers ask the same question. This section gives you the reasons in the data's own terms and a decision table for choosing between the candidates.
Here is a judgment call interviewers explicitly probe, because so many candidates get
it backwards: deep learning loses on most tabular business problems, and
that is still true as of August 2026.
Benchmark studies (Grinsztajn et al.'s
NeurIPS work and its successors) keep finding gradient-boosted trees matching or beating
tuned neural networks on mid-sized tables, and a decade of Kaggle tabular leaderboards
agrees.
The reasons are structural, not fashion: tabular features are heterogeneous
(dollars next to counts next to categories), targets are non-smooth (a contract-type
boundary is a cliff, not a gradient), and informative interactions are axis-aligned —
exactly the shape a tree split captures natively.
Trees are invariant to feature scaling,
shrug off missing values, and train in minutes on a laptop, so you iterate 50 times a
day instead of 5.
Neural networks win where data is homogeneous and perceptual — images,
audio, text (Modules 04–05) — or where you need embeddings feeding a larger system.
The
one genuinely interesting tabular exception is TabPFN-style foundation models on small
tables (<10K rows), worth knowing for interviews; the production default remains
boosted trees.
Saying this crisply — "I'd start with XGBoost and a logistic baseline;
I'd need a specific reason to reach for a neural net on this table" — is a senior-signal
answer.
The decision table below, drawn as a map. Left to right is how many rows the table
has; bottom to top is what kind of columns it holds. SaaSify's 12,000-row table of
dollars, counts and contract types sits in the bottom-middle cell.
Fig. 3.4c — The decision table as a map. On tables of numbers and categories (the bottom row) the choice is set by size: a logistic baseline always, XGBoost as the default, LightGBM when the rows run into the tens of millions. Deep learning owns the top row, where columns are text or images. SaaSify's table sits in the accented cell.
The baseline cell. Logistic regression is not a competitor; it is the floor every other model must clear. It trains in seconds and its coefficients can be audited. On very small tables, TabPFN-style models are the one interesting newcomer.
SaaSify's cell. Twelve thousand rows of dollars, counts and contract types, with cliffs in the risk (a contract type, a tenure window). That is the regime where boosted trees match or beat tuned neural networks, and where an afternoon of iteration on a laptop beats a week on a GPU.
The big-table cell. Same family, same API shape. LightGBM grows the most promising leaf first, which is faster and lighter on memory but happier to overfit a small table. Switching from XGBoost later is an afternoon, not a rewrite.
The top row. When a column is free text or an image, a tree cannot read it until someone turns it into numbers. Neural networks do that reading themselves, which is Module 04 and Module 05, and it is the honest exception to "boosted trees first".
Decision table — picking a model for tabular prediction (as of Aug 2026)
Option
Choose when
Avoid when
Typical cost
Logistic regression
Always, as the baseline: fast, calibrated-ish probabilities, auditable coefficients
Interactions dominate and you can't hand-craft them all
Seconds to train
XGBoost
The tabular default: strongest regularization story (level-wise growth, L1/L2, early stopping), robust on small-to-mid data
Data so large that training time dominates iteration speed
Minutes on a laptop
LightGBM
Large datasets: leaf-wise growth is 2–10× faster with lower memory; native categorical support (no one-hot)
Small datasets — leaf-wise trees grow deep and overfit faster without careful limits
Minutes, even at 10M+ rows
Deep learning on tables
Huge data plus multimodal columns (free text, images), or you need learned embeddings downstream
Most business tables — GBDTs match or beat it with 100× less tuning
GPU hours + tuning weeks
Within the boosted-tree family, the XGBoost-vs-LightGBM call comes down to growth
strategy: XGBoost grows trees level-wise (balanced, conservative, lower
overfitting risk), LightGBM grows leaf-wise (always split the most promising
leaf — faster and more memory-efficient, but happier to overfit small data). Same
algorithmic family, same API shape; switching later is an afternoon, not a rewrite.
CatBoost rounds out the trio when your table is dominated by high-cardinality
categoricals.
The stack, and why
XGBoost is not the only boosting library, and “why not LightGBM?” is a common interview follow-up. Here is every tool the churn engine uses, what else you could pick, and the point where each switch pays off.
The stack, and why
The one question that decides it: is the table big or high-cardinality enough that the default boosting library hurts?
What module 03 uses, what else you could use, and when to switch (as of October 2026)
The most documented of the three, with early stopping, class weights and SHAP support that all work out of the box. Weakness: slower than LightGBM on very large tables, and it wants categories turned into numbers first.
Over roughly 1 million rows and training time hurts (LightGBM), or several categories have thousands of values such as merchant or zip code (CatBoost). If you cannot add a dependency, use HistGradientBoosting.
Baseline
Logistic regression (scikit-learn 1.9)
A single decision tree, a random forest
A fair, fast yardstick: if boosting cannot beat it, ship the simple model. Weakness: straight-line only, so it misses the “only when” rules.
Never drop it. Replace it only when a stronger model is already in production and becomes the new bar.
Data splits
Train 64% / validation 16% / test 20%
5-fold cross-validation, time-based split
Gives early stopping its own referee without peeking at the test set. Weakness: only 7,680 rows train the model, because two slices are held back.
The table has a date column and you predict the future: split by time. Under ~2,000 rows: use cross-validation.
Tuning
Hand-picked settings plus early stopping
Grid search, Optuna
Two or three knobs matter most and a human can read the effect. Weakness: you may miss a better corner of the settings.
You have more than ~5 settings to tune and a budget of 50+ training runs: let Optuna search.
Signed and per customer, so a CSM sees why this account is at risk. Weakness: an extra dependency, and explaining 1 million rows takes real time.
You only need a global ranking, once: permutation importance is simpler. Over ~1 million rows per day to explain: sample them.
Serving
A Python function over the fitted objects
XGBoost saved as JSON, ONNX Runtime, Treelite
Zero extra parts while you learn, and it returns the SHAP reasons too. Weakness: tied to Python and to the same library versions.
A non-Python service must score, or you need under ~5 ms per call in bulk: export the model and serve it from ONNX Runtime.
For a table of tens of thousands of rows, XGBoost with early stopping, a logistic baseline and SHAP is the boring right answer; swap the booster only when a number in the last column is crossed.
06 · Under the hoodThe Math, If You Want It
Everything above ran on two ideas that were used but not proved: a split is chosen by how much purer it makes its two buckets, and a vote only helps when the voters' mistakes are unrelated. The BE-the-tree scores, 0.3000 against 0.1667, came from the first idea. The fireside's "floor with your name on it" came from the second. This section writes both down with SaaSify's numbers, and adds the formula XGBoost actually uses to score a split. Then the boardroom translation turns the model back into Marcus's dollars.
How a tree picks its split — Gini, entropy, and why votes need to be uncorrelated
Gini impurity scores how mixed a bucket of labels is:
Gini = 1 − Σᵢ pᵢ², where pᵢ is the fraction of the bucket belonging to class i.
A pure bucket (100% churners): 1 − (1.0² + 0.0²) = 0 — no impurity.
A coin-flip bucket (50/50): 1 − (0.5² + 0.5²) = 0.5 — maximum
uncertainty for two classes. Intuition for the formula: Σpᵢ² is the probability that
two customers drawn from the bucket agree on their label; Gini is the probability
they disagree.
That second reading is a picture. Take the two buckets from Fig. 3.2b, list every
way of drawing two customers from each (the first draw down the side, the second
along the top), and shade the pairs that disagree.
Fig. 3.4d — Gini impurity is the chance that two customers drawn from a bucket disagree. In the pure bucket no pair disagrees, so Gini is 0. In the mixed bucket 8 of the 25 ordered pairs disagree, so Gini is 0.32, the same 0.3200 the formula gave in the BE-the-tree exercise.
The pure bucket. Three churners. Whichever two you draw, they agree, so there is nothing to shade and the impurity is zero. This is the left bucket of Fig. 3.2b.
The mixed bucket. One churner among five. A pair disagrees only when one draw is F and the other is not: four such pairs with F first, four with F second, eight of twenty-five. Σpᵢ² counts the agreeing pairs (0.04 + 0.64 = 0.68) and 1 minus that is the disagreeing share, 0.32.
The alternative, entropy,
H = −Σᵢ pᵢ log₂ pᵢ, measures the same mixedness in bits; in practice the two pick
nearly identical splits, and Gini is the default (scikit-learn's too) because it
skips the logarithm.
A candidate split is scored by the weighted impurity of its children:
Δ = Gini(parent) − [ w·Gini(left) + (1−w)·Gini(right) ], where w is the fraction of
rows going left. The weighting is why a three-customer "pure" leaf can't beat a
genuinely informative split of hundreds — small buckets get small votes. The tree
greedily takes the split with the largest Δ and recurses.
Why forests need decorrelation: for n trees each with error
variance σ², with average pairwise correlation ρ between their errors, the variance
of the averaged vote is ρσ² + (1−ρ)σ²/n.
The second term dies as n grows — that's
the free lunch of averaging — but the first term, ρσ², is a floor that no amount of
extra trees removes. Bootstrap sampling and per-split feature restriction exist
purely to push ρ down.
Put numbers in and the floor is visible. Take σ² = 1 for one tree's error variance
and ρ = 0.3 for the correlation between two trees' errors, both made up to keep the
arithmetic small, and add trees.
Fig. 3.4e — The averaging formula with σ² = 1 and ρ = 0.3 (made up to keep the arithmetic small). Ten trees cut the variance from 1.0000 to 0.3700; three hundred only reach 0.3023. The dashed line at 0.30 is ρσ², the part of the error every tree shares, and no number of trees goes below it.
The free lunch. The second term, (1 − ρ)σ²/n, is 0.70 for one tree, 0.07 for ten, 0.007 for a hundred. That is the part averaging removes, and it is why a forest of 300 beat one tree in Fig. 3.2c.
The floor. The first term, ρσ², does not have n in it. With ρ = 0.3 it is 0.30 whether you grow ten trees or ten thousand. Bootstrap rows and random feature subsets exist to make ρ smaller, which lowers the floor itself; adding trees only brings you down to it.
The boosting objective — residuals, shrinkage, and XGBoost's regularized gain
Plain gradient boosting. After m−1 rounds the ensemble predicts
ŷ⁽ᵐ⁻¹⁾(x). The m-th tree hₘ doesn't fit the target y — it fits the residuals
rᵢ⁽ᵐ⁾ = yᵢ − ŷᵢ⁽ᵐ⁻¹⁾ (for squared loss), and the ensemble updates as
ŷ⁽ᵐ⁾(x) = ŷ⁽ᵐ⁻¹⁾(x) + η·hₘ(x).
The learning rate η (typically 0.01–0.1) shrinks
each step so no single tree dominates. The name "gradient": for squared loss the
residual is the negative gradient −∂L/∂ŷ, so each tree is a gradient-descent
step — taken in function space, with a tree as the step direction. Swap the loss for
log-loss and the same machinery does classification.
What XGBoost adds. The objective is explicitly regularized:
Obj = Σᵢ l(yᵢ, ŷᵢ) + Σₖ Ω(fₖ), with Ω(f) = γT + ½λΣⱼ wⱼ² — T is the number of
leaves in a tree, wⱼ the score a leaf outputs, γ a per-leaf complexity tax, λ an L2
penalty on leaf scores.
XGBoost then takes a second-order Taylor expansion of the
loss, so each row contributes a gradient gᵢ and a curvature (hessian) hᵢ. Two clean
results fall out.
The optimal score of a leaf is wⱼ* = −Σg / (Σh + λ) — big
aggregate gradient means a big correction, damped by curvature and by λ.
And the
gain of a candidate split is
½ [ G²_L/(H_L+λ) + G²_R/(H_R+λ) − (G_L+G_R)²/(H_L+H_R+λ) ] − γ, where G and H are
the summed gradients/hessians of the left, right, and combined sets. Read that last
term: a split must pay the γ tax to exist.
Regularization isn't a
post-hoc prune — it's inside the split decision itself, which is why XGBoost
overfits less than the vanilla algorithm it descends from, and why
scale_pos_weight works the way it does: it multiplies the gᵢ and hᵢ of
minority-class rows, making their errors literally weigh more in every split.
There are no dumb questions
Why not just write the if/else ladder myself? I've been writing business rules for years.
For three rules, do. But churn risk lives in the interactions of eight-plus
features, which means thousands of threshold combinations — and they drift as your
product and pricing change. A tree learns the thresholds from data and re-learns
them on retrain; your hand-written ladder fossilizes the day you ship it. The honest
framing: a decision tree is the business-rules engine that maintains itself.
Won't 500 trees just memorize the training set?
Any one of them would. The ensemble is protected three ways: the learning rate
means each tree contributes only a small nudge; L1/L2 regularization and the γ
leaf-tax penalize complexity inside every split decision; and early stopping halts
the whole process the moment held-out performance stalls. You watched the forest do
this in the break section: 1.000 train accuracy, best-in-class test accuracy.
My data is 95% non-churn. The model predicts "no churn" for everyone and scores 95% accuracy!
Fig. 3.4f — The accuracy trap on 100 customers with a 5% churn rate (the numbers in the question). Saying "no churn" to everyone is 95% accurate and catches no churners at all. Accuracy reports the base rate; a ranking metric reports whether the churners are scored above the stayers.
The five that matter. Marcus's whole request is about the red dots. A metric that can score 95% while ignoring every one of them is measuring the wrong thing.
The constant model. It never looks at a feature. Its 95 correct answers are the 95 customers who were staying anyway, the same customers the shotgun coupon in Fig. 3.0b would have paid.
The classic class-imbalance trap — and the first thing to fix is your metric,
because accuracy is lying to you. Evaluate with ROC-AUC and PR-AUC (PR-AUC is more
honest under heavy imbalance). Then rebalance the training signal:
scale_pos_weight = neg/pos makes each churner count ~5–20× in the loss.
Finally, tune the decision threshold to business costs rather than accepting 0.5 —
missing a churner costs $147/month; a needless retention call costs $20. SMOTE-style
oversampling exists but is rarely the first tool anymore; reweighting plus threshold
tuning is cleaner and doesn't invent synthetic customers.
Do I need to scale or normalize features for XGBoost?
No — and it's worth understanding why: a split like charges > 80
only cares about the ordering of values, so trees are invariant to any
monotone transform (log, standardize, min-max — all no-ops). The pipeline above
scales anyway because the logistic baseline shares the preprocessor, and logistic
regression genuinely needs it. One-hot encoding is still required for XGBoost's
categoricals; LightGBM and CatBoost handle them natively.
Random forest or XGBoost — which do I reach for first?
Forest first, boosted model to ship. A random forest is nearly tuning-free and
trivially parallel, which makes it a great ten-minute sanity check of your features.
A tuned XGBoost with early stopping almost always edges it out on final metrics,
at the cost of more knobs. If the forest and XGBoost agree and barely beat logistic
regression, that's evidence your features — not your model — are the bottleneck.
Boardroom translation
Marcus doesn't want an AUC — he wants the leak plugged, so pitch the model as
margin math. Status quo: 340 lost subscribers × $147 average = the $50K/month leak.
The naive fix — a blanket 20% discount across all ~4,400 accounts — burns roughly
$128K/month of margin, mostly on customers who were never leaving.
The model is the
scalpel: contact only the top-300 risk list; at ~55% precision that's ~165 genuine
flight risks, and a 30% save rate retains ~50 subscribers × $147 ≈ $7.4K of MRR
per month, recurring — with an 18-month average remaining lifetime, each
monthly cohort of saves is worth ~$130K against ~$26K of worst-case offer cost
(300 offers × 20% × 3 months).
Fig. 3.4g — Fig. 3.0b again, only the scalpel, with the chain of numbers written out: 300 calls become about 165 real risks at 55% precision, about 50 saves at a 30% save rate, and $7.4K a month of recurring revenue, worth about $130K per cohort over an 18-month lifetime against at most $26K of offers. Precision and save rate are assumptions to be measured, not outputs of the model.
The ranked list. Everything in this chain starts with the model's ordering. Precision at the top 300 is the number the lab asks you to report, because it is the only model metric in the chain; the save rate belongs to the CSM team.
The return. Five times the cost, and the shotgun's $128K a month is not in the chain at all. This is the sentence Marcus can repeat to the board, and the SHAP report is what makes each of the 300 calls a specific conversation rather than a coupon.
Call it a 5× return, and the SHAP report is what makes
the play executable: it tells each CSM which lever to pull — a support-pain
account gets an engineering escalation, not a coupon.
Elevator version: "We stop
discounting everyone to save anyone — the model finds the 300 accounts worth calling
and tells us why each one is leaving, turning a $128K shotgun into a $26K scalpel
that returns 5×."
07 · The labBuild the Real Thing
The engine, the stopping rule and the SHAP report exist. What Marcus asked for on Monday was an operational early-warning system with a reason a CSM can read, by Friday. The lab turns churn_engine.py into that deliverable: a ranked list of the 300 riskiest accounts, a per-customer explanation in plain English, and a model card that says what the numbers mean and where they fail.
LAB 03 — Churn early-warning system with a CSM-readable SHAP report
Mission: extend churn_engine.py into a deliverable a
customer-success team could actually run: a scored risk list plus a per-customer
"why" report in plain English. You have ~80% of the machinery above; the 20% you
build is the reporting layer and the evaluation discipline.
XGBoost beats the logistic baseline by ≥ 0.02 test ROC-AUC — report both
numbers from the same untouched test set, and report precision@top-300 (the
business actually acts on a ranked list, not a threshold)
Early stopping used against a dedicated validation slice; the README states
best_iteration and shows the val-AUC curve flattening
report_customer(id) renders the top-3 churn drivers and top-1
protective factor as English sentences from SHAP values — e.g. "5 support tickets
this quarter raised churn risk by 14 points" — no raw feature names, no log-odds
jargon
Batch mode writes the 20 riskiest test customers to a Markdown table:
probability, risk band, top driver, recommended action
A written model card in the README: training data and its
synthetic provenance, metrics (ROC-AUC, PR-AUC, precision@top-300), intended use
and explicit non-uses, plus 3 failure modes you found (e.g. probabilities
miscalibrated by scale_pos_weight, SHAP splitting credit across the
correlated tenure/contract pair, threshold brittleness under drift) and what you
did about each
Stretch goal: swap in LightGBM behind the same interface and
compare AUC + training time on 100K generated rows; or calibrate the probabilities
(isotonic regression on the val set) and show a before/after reliability curve —
weighted models are famously miscalibrated, and calibration is what makes the 0.70
"CRITICAL" threshold mean what it says.
08 · Interview radarHow This Shows Up in Interviews
Interview radar
Per the market research, classical ML is still a baseline
expectation even for GenAI-titled roles — "bias/variance, XGBoost-era modeling,
metrics" show up in screens before anyone asks about transformers.
"Bagging vs boosting — explain the difference and when you'd
use each."
Strong answer Both are ensembles, with opposite
mechanisms. Bagging trains high-variance trees independently on bootstrap samples
and averages them — it attacks variance, parallelizes trivially, and is
robust with near-zero tuning, which is why a random forest is such a strong
default. Boosting trains weak trees sequentially, each one fitting its
predecessors' residuals — it attacks bias, wins on final accuracy, and
needs regularization plus early stopping to stay honest.
Land it Sketch Fig. 3.2 from memory —
naming what flows along the arrows, predictions versus residuals, is what separates
memorized definitions from understanding.
"Why would you pick XGBoost over deep learning here?"
The real test Vendor-agnostic judgment
— they're grading your read of the data regime, not your loyalty to a tool.
Strong answer Tabular data is heterogeneous,
non-smooth, and interaction-heavy — exactly the regime where boosted trees still
match or beat tuned neural nets (Grinsztajn et al. and successors, still
holding as of 2026). Add the engineering economics: minutes per iteration on a
CPU versus GPU-hours, plus built-in explainability via SHAP. Then show you know
the boundary — neural nets win when columns include text or images, when you need
embeddings downstream, or with TabPFN-class models on very small tables.
Land it Judgment, stated with its
exceptions, is the senior signal.
"Your positive class is 2%. Walk me through it."
The real test Whether you have an
ordered playbook for imbalance, not a bag of remembered tricks.
Strong answer In order:
Fix the metric first — PR-AUC and precision@k, because
accuracy and even ROC-AUC flatter you under extreme imbalance
Reweight the loss — scale_pos_weight or class
weights, so the rare class actually matters during training
Tune the operating threshold — set it from the business's
cost matrix, not the default 0.5
Calibrate afterwards — reweighting distorts the
probabilities, so repair them before anyone reads them as real risks
Mention SMOTE to show you know it, then explain why reweighting is usually
the cleaner route.
Land it Bonus point: compute
scale_pos_weight from the training fold only.
"SHAP vs feature importance — aren't they the same?"
Strong answer No — they differ on three axes:
Scope — gain-based importance is global and answers "what
does the model use on average"; SHAP is per-prediction and answers "why did
this customer get this score"
Sign — importance is unsigned, while SHAP tells you
whether a feature pushed the score up or down
Reliability — gain-based importance is biased toward
high-cardinality features; SHAP is consistent because it inherits fairness
axioms from Shapley values
Regulators and stakeholders need the second kind: a per-customer, signed
explanation.
Land it The caveat that earns points:
SHAP splits credit between correlated features, so interpret the tenure-vs-contract
attributions jointly.
"Design the churn scoring service."
Strong answer Two serving paths: nightly batch
scoring of the full base — cheap, and it covers the CSM dashboard — plus a
low-latency inference endpoint for event-driven rescoring. One shared
preprocessing artifact serves both training and inference so they can't skew
apart, and features are versioned in a store.
Then the lifecycle: retrain on a cadence with early stopping, gate each
candidate behind a champion/challenger check — the new model must beat the
deployed model's AUC on a frozen eval set — and monitor both input drift and
weekly realized-churn AUC.
Land it Close the loop with Module
02's lesson: the eval set is sacred and the baseline never gets deleted.
Quick reference — Trees and ensembles
decision tree
A sequence of yes/no splits. Easy to read, and on its own unreliable — small data changes give a very different tree.
bagging vs boosting
Bagging (random forest) trains many trees in parallel on samples and averages them, reducing variance. Boosting trains trees in sequence, each correcting the last one's errors, reducing bias.
XGBoost
Gradient boosting plus regularisation, clever handling of missing values, and speed. Still the default for tabular business data — it beats deep learning there.
Gini / entropy
Two ways of measuring how mixed a group is. A split is good when it makes the resulting groups purer.
The overfitting tell
Train 1.000, test 0.787. Perfect on data it has seen means it memorised rather than learned.
SHAP
Attributes a prediction to each feature, for one specific row. This is how you answer “why was this customer flagged?” — which is often a legal requirement, not a nicety.
Fix the metric first
If the model optimises the wrong number, no amount of tuning helps. Decide what “good” means before you train anything.
bootstrap sample
The training table redrawn at the same size, with replacement: some rows twice, about a third not at all. Each tree in a forest grows on its own re-draw (worked by hand).
out-of-bag score
Each training row scored only by the trees that never saw it. For the forest of 300 trees: 0.841, next to 0.852 on the test rows and a meaningless 1.000 on the training rows.
learning rate η in boosting
The share of each tree's correction the model keeps. Too big does not blow up as it did in Module 02; it overfits in fewer trees. η = 1.0 kept 5 trees and scored 0.9106; η = 0.05 kept 110 and scored 0.9272 (the sweep).
log-odds
The score a boosted model adds up, one leaf per tree, before the sigmoid turns it into a probability; 0 means 50%. CUST-9842's 110 leaves sum to 4.2165, which is 0.9855 (the walk).
stack decision
Start from XGBoost + logistic baseline + SHAP; switch the booster only when rows pass ~1M (LightGBM) or categories have thousands of values (CatBoost).
09 · RecapWhat You Can Do Now
You can implement a greedy Gini-split decision tree from scratch and explain why weighted child impurity and greedy search make it fast but unstable
You can demonstrate overfitting with a train/test gap and explain why a forest of memorizers generalizes when its errors are decorrelated
You can articulate bagging vs boosting as variance-cutting vs bias-cutting, including what flows along the arrows
You can train XGBoost the professional way: three-way split, early stopping against a validation set, and a logistic baseline it must beat to ship
You can handle class imbalance end-to-end: scale_pos_weight, PR-AUC over accuracy, threshold tuned to business costs
You can generate per-customer SHAP explanations and translate them into sentences a CSM can act on
You can defend "boosted trees over deep learning on tabular data" with benchmark evidence and its exceptions
You can pitch a churn model in margin terms: scalpel vs shotgun, save-rate ROI, and why explainability makes the play executable
You can run a tree's split contest by hand, draw a bootstrap re-draw, and explain why a forest's vote cancels mistakes a few trees make but locks in mistakes most trees make
You can trace one customer through a boosted model as a sum of leaf values, and say what the learning rate multiplies and what happens when it is too big
🧠 Flex your memory
From this module: sketch Fig. 3.2 from memory — bagging on the left,
boosting on the right — and annotate what travels along every arrow. If your boosting
arrows carry "predictions" instead of "residuals", re-read the committee story.
Reaching back to Module 02: your churn model serves a ranked list and
the CS team can call 300 accounts a week.
Which precision/recall trade from Module 02
does moving that budget to 600 change, in which direction — and where does that move
live on the ROC curve you built there?