▚ The AI Engineer's Field Manual
Module 03 · Act II — ML Foundations

Trees & Ensembles — XGBoost, the Tabular Workhorse

"Single models have blind spots; committees of decision-makers achieve mastery."

~5 hours Builds on: Module 02 Tools: xgboost · lightgbm · shap · scikit-learn Job-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.

1 THE LEAK: 340 OF 4,400 PAYING ACCOUNTS LEFT LAST MONTH 4,400 paying accounts, each worth $147 a month on average 340 gone × $147 = $50K a month 2 THE SHOTGUN: A 20% COUPON TO EVERYONE 4,400 × 20% × $147 ≈ $128K a month of margin, most of it handed to customers who were staying anyway 3 THE SCALPEL: RANK EVERY ACCOUNT BY CHURN RISK, CALL ONLY THE TOP 300 300 calls → about 165 real flight risks → about 50 saved × $147 ≈ $7.4K a month, every month offer cost at worst 300 × 20% × $147 × 3 months ≈ $26K, against $128K for the shotgun
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.
  1. 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.
  2. 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.
  3. 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:

MonthlyCharges > $80? yes · n=1,140 no · n=1,860 TenureMonths < 6? LOW RISK 6% churn · n=1,860 yes · n=310 no · n=830 HIGH RISK 71% churn · n=310 MEDIUM 28% churn · n=830 1 2 3 4
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.
  1. 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.
  2. 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.
  3. 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.
  4. 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.

1 FIVE TREES, EACH GROWN ON ITS OWN RANDOM RE-DRAW OF THE ROWS the customer table tenure ≤ 5? yes no leave stay G → stay · vote 0 charges ≤ 84? yes no stay leave G → leave · vote 1 tenure ≤ 11? yes no leave stay G → stay · vote 0 charges ≤ 130? yes no stay leave G → stay · vote 0 charges ≤ 100? yes no stay leave G → leave · vote 1 2 EACH TREE VOTES ON CUSTOMER G: 36 MONTHS IN, $110 A MONTH, STAYED 3 THE FOREST AVERAGES THE FIVE VOTES (0 + 1 + 0 + 0 + 1) ÷ 5 = 0.40 → churn risk 40%, below one half → the forest says G stays tree 2 and tree 5 said "leave" on their own. They were outvoted, not deleted: their 2 votes are still inside the 0.40.
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.
  1. 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.
  2. 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.
  3. 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:

BAGGING · random forest training set re-drawn rows random columns tree 1 tree 2 tree 3 majority vote / mean independent · trains in parallel · cuts variance BOOSTING · XGBoost training set tree 1 what #1 got wrong tree 2 remaining errors tree 3 ŷ = η·t₁ + η·t₂ + η·t₃ sequential · each tree fixes the last · cuts bias 1 2 3 4
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.
  1. 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.
  2. 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.
  3. 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.
  4. 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
StageIn the from-scratch version (sections 03–04)In the production build (section 05)What flows out
Grow one treegrow() in tree_from_scratch.py, depth 2, every threshold triedEach of XGBoost's trees, max_depth=5; tree_method="hist" bins the thresholds firstA nested if/else that ends in a leaf value
Score a splitgini(), weighted by bucket size, inside best_split()The regularized gain in section 06: a gradient and a curvature per row, minus a tax per leafThe one (feature, threshold) pair that purifies most
Make the trees differBootstrap rows and random feature subsets inside RandomForestClassifier(n_estimators=300) in overfit_demo.pysubsample=0.9, colsample_bytree=0.9: each tree sees 90% of the rows and 90% of the columnsTrees whose mistakes do not line up
Decide what each tree learnsForest: every tree learns the labelsBoosting: every tree learns the residuals left by the trees before it, scaled by learning_rate=0.05What travels along the arrows in Fig. 3.2: labels on the left, residuals on the right
Combine the treesThe 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 stopA fixed count: n_estimators=300n_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 classNothing: plain accuracy on a 20% churn ratescale_pos_weight=spw, computed from the training fold onlyA model that pays for every churner it misses
Explain a predictionjson.dumps(grow(...)): read the if/else yourselfshap.TreeExplainer(model) inside churn_report()Three signed drivers per customer, in JSON a CSM can read
Judge the modelt.score() on the training rows and on the test rowsroc_auc_score and average_precision_score on the untouched test set, against a logistic baselineNumbers 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
logit = 0.045 * (X[:, 1] - 80) - 0.10 * (X[:, 0] - 12)
y = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
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)
for t in np.unique(X[:, f]):
left = X[:, f] <= t
if left.sum() in (0, y.size):
child = w * gini(y[left]) + (1 - w) * gini(y[~left])
if parent - child > best[2]:keep this split only if its drop in impurity beats the best drop seen so far
return {"leaf": True, "p_churn": round(float(y.mean()), 2), "n": int(y.size)}
"then": grow(X[m], y[m], depth - 1),
Check your answers
rng = np.random.default_rng(42)make a random-number generator with a fixed seed, so every run produces the same 400 customers
logit = 0.045 * (X[:, 1] - 80) - 0.10 * (X[:, 0] - 12)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] <= ta 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
child = w * gini(y[left]) + (1 - w) * gini(y[~left])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
return {"leaf": True, "p_churn": round(float(y.mean()), 2), "n": int(y.size)}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
  1. Bring in json, to print the finished tree neatly, and numpy for the arithmetic.
  2. Create a random-number generator with seed 42, so every run produces the same 400 customers and therefore the same tree.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. Skip thresholds that send every row to one side. A split must actually split.
  9. 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.
  10. If the drop from parent impurity to child impurity beats the best drop so far, remember this feature, threshold, and gain.
  11. 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.
  12. 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.
  13. Print the tree as indented JSON. That is the nested if/else in the output block below.
tree_from_scratch.pyruns offline
# 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))
outputrepresentative run
{
  "if": "tenure_months <= 33.0",
  "then": {
    "if": "monthly_charges <= 85.6",
    "then": {
      "leaf": true,
      "p_churn": 0.18,
      "n": 98
    },
    "else": {
      "leaf": true,
      "p_churn": 0.8,
      "n": 92
    }
  },
  "else": {
    "if": "monthly_charges <= 128.8",
    "then": {
      "leaf": true,
      "p_churn": 0.02,
      "n": 177
    },
    "else": {
      "leaf": true,
      "p_churn": 0.3,
      "n": 33
    }
  }
}

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.

  1. A — tenure 2 months, $120 a month — churned
  2. B — tenure 3 months, $95 a month — churned
  3. C — tenure 5 months, $130 a month — churned
  4. D — tenure 8 months, $60 a month — stayed
  5. E — tenure 14 months, $70 a month — stayed
  6. F — tenure 20 months, $140 a month — churned
  7. G — tenure 36 months, $110 a month — stayed
  8. 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, C3 churned, 0 stayed. Gini = 1 − 1.0000 − 0.0000 = 0.0000. A pure bucket.
tenure ≤ 5, right: D, E, F, G, H1 churned, 4 stayed. p = 0.2. Gini = 1 − 0.0400 − 0.6400 = 0.3200.
tenure ≤ 5, weighted total3/8 × 0.0000 + 5/8 × 0.3200 = 0.2000. Drop = 0.5000 − 0.2000 = 0.3000.
charges ≤ 70, left: D, E0 churned, 2 stayed. Gini = 0.0000. Also pure, but only two customers.
charges ≤ 70, right: A, B, C, F, G, H4 churned, 2 stayed. p = 0.6667. Gini = 1 − 0.4444 − 0.1111 = 0.4444.
charges ≤ 70, weighted total2/8 × 0.0000 + 6/8 × 0.4444 = 0.3333. Drop = 0.5000 − 0.3333 = 0.1667.
Winnertenure ≤ 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.

A B C D E F G H · 4 churned, 4 stayed Gini = 1 − 0.5² − 0.5² = 0.5000 tenure ≤ 5 months? 1 yes · 3 of 8 no · 5 of 8 A B C 3 churned, 0 stayed: pure Gini = 1 − 1.0² − 0.0² = 0.0000 2 D E F G H 1 churned (F), 4 stayed Gini = 1 − 0.2² − 0.8² = 0.3200 3 4 weighted: 3/8 × 0.0000 + 5/8 × 0.3200 = 0.2000 → drop = 0.5000 − 0.2000 = 0.3000 runner-up, charges ≤ $70: 2/8 × 0.0000 + 6/8 × 0.4444 = 0.3333 → drop only 0.1667 F, the one churner left on the "no" side, is what the next question on that side has to catch
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.
  1. 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.
  2. 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.
  3. 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.
  4. 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.
CustomerTenure (months)Monthly chargesChurned?
A2$120Yes
B3$95Yes
C5$130Yes
D8$60No
E14$70No
F20$140Yes
G36$110No
H48$125No
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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
QuestionLeft bucketRight bucketGini leftGini rightWeightedDrop
tenure ≤ 2AB C D E F G H0.00000.48980.42860.0714
tenure ≤ 3A BC D E F G H0.00000.44440.33330.1667
tenure ≤ 5A B CD E F G H0.00000.32000.20000.3000
tenure ≤ 8A B C DE F G H0.37500.37500.37500.1250
tenure ≤ 14A B C D EF G H0.48000.44440.46670.0333
tenure ≤ 20A B C D E FG H0.44440.00000.33330.1667
tenure ≤ 36A B C D E F GH0.48980.00000.42860.0714
charges ≤ 60DA B C E F G H0.00000.48980.42860.0714
charges ≤ 70D EA B C F G H0.00000.44440.33330.1667
charges ≤ 95B D EA C F G H0.44440.48000.46670.0333
charges ≤ 110B D E GA C F H0.37500.37500.37500.1250
charges ≤ 120A B D E GC F H0.48000.44440.46670.0333
charges ≤ 125A B D E G HC F0.44440.00000.33330.1667
charges ≤ 130A B C D E G HF0.48980.00000.42860.0714

Fig. 3.2d draws the drop column as bars, one strip per column.

TENURE COLUMN: 7 QUESTIONS CHARGES COLUMN: 7 QUESTIONS tenure ≤ 2 0.0714 tenure ≤ 3 0.1667 2 tenure ≤ 5 0.3000 1 tenure ≤ 8 0.1250 tenure ≤ 14 0.0333 tenure ≤ 20 0.1667 tenure ≤ 36 0.0714 tenure ≤ 48 skipped: all eight go left 3 charges ≤ 60 0.0714 charges ≤ 70 0.1667 charges ≤ 95 0.0333 charges ≤ 110 0.1250 charges ≤ 120 0.0333 charges ≤ 125 0.1667 charges ≤ 130 0.0714 charges ≤ 140 skipped: all eight go left each bar is a drop in Gini: 0.5000 − (share left × Gini left + share right × Gini right) longest bar wins: tenure ≤ 5, a drop of 0.3000, nearly twice any other question
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.
  1. 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.
  2. 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.
  3. 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.

  1. 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.
  2. 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.
  3. Nothing left to ask. Every bucket is pure, so no question can lower any Gini. best_split() returns no feature, and grow() writes leaves.
  4. 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.

THE EIGHT CUSTOMERS, NO DEPTH LIMIT tenure ≤ 5? yes no A B C 3 of 3 churned · 1.0 charges ≤ $125? 1 yes no D E G H 0 of 4 churned · 0.0 F alone 1 of 1 · 1.0 2 every bucket is pure, so all 8 customers it grew from are answered right: training accuracy 1.000 new customer I 30 months · $135 a month 3 30 > 5 → no · then $135 > $125 → no verdict: churn, rate 1.0, from one customer SAME RULE, 1,400 TRAINING CUSTOMERS 231 leaves, 15 questions deep 4 94 hold 1 customer 63 hold 2–3 74 hold 4+ training accuracy 1.000: every leaf is pure 600 NEW CUSTOMERS: SHARE ANSWERED RIGHT 55 landed in a one-customer leaf (9.2%) 0.364, worse than a coin 5 the other 545 landed in bigger leaves 0.829 coin flip 0.5 right-hand numbers: deep_tree_leaves.py
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.
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

  1. Draw eight times. rng.integers(0, 8, 8) rolls an eight-sided die eight times: E, C, D, B, H, F, F, A.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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 eightTree 2's re-draw
Who is in the tableA to H, once eachA, B, C, D, E, H once; F twice; G not at all
Churned4 of 85 of 8
Gini of the whole table0.50000.4688
Drop for tenure ≤ 50.30000.1688
Drop for charges ≤ 700.16670.2604
First question the tree askstenure ≤ 5charges ≤ 70

Fig. 3.2f draws the draws, the tally, and the two questions scored on the new table.

1 EIGHT DRAWS FROM THE HAT, EACH SLIP PUT BACK E C D B H F F A draw 1 draw 2 draw 3 draw 4 draw 5 draw 6 draw 7 draw 8 tree 2's re-draw, seed 12 rng.integers(0, 8, 8) 2 THE TALLY: HOW MANY TIMES EACH CUSTOMER IS IN TREE 2'S TABLE A B C D E F G left out 3 H F drawn twice: counts twice G never drawn: out of bag filled = churned · outline = stayed whole table: 5 churned of 8, p = 0.625 → Gini 1 − 0.625² − 0.375² = 0.4688 4 THE SAME TWO QUESTIONS, SCORED ON TREE 2'S TABLE tenure ≤ 5 (won on the original eight) left A B C: Gini 0 · right D E F F H: Gini 0.4800 5/8 × 0.4800 = 0.3000 → drop 0.1688 charges ≤ 70 (wins on tree 2's table) left D E: Gini 0 · right A B C F F H: Gini 0.2778 6/8 × 0.2778 = 0.2083 → drop 0.2604 one duplicate (F) and one gap (G) moved the first question from tenure to price
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.
  1. 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.
  2. 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.
  3. 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.
  4. 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.
TreeRe-draw (left out)Question it grewG's answerG's bucketChurn rateVote
1E C H H A B B B (D, F, G)tenure ≤ 5no: 36 > 5E, H, H0 of 3 = 0.0000stay
2E C D B H F F A (G)charges ≤ 70no: $110 > $70A, B, C, F, F, H5 of 6 = 0.8333leave
3B H C G G A D E (F)tenure ≤ 5no: 36 > 5D, E, G, G, H0 of 5 = 0.0000stay
4D A F C C D C D (B, E, G, H)charges ≤ 60no: $110 > $60A, C, C, C, F5 of 5 = 1.0000leave
5G D F H B C E B (A)tenure ≤ 5no: 36 > 5D, E, F, G, H1 of 5 = 0.2000stay
  1. Collect the five answers. 0.0000, 0.8333, 0.0000, 1.0000 and 0.2000.
  2. 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.
  3. 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.
  4. 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.

1 FIVE RE-DRAWS, FIVE ONE-QUESTION TREES, ONE CUSTOMER: G, 36 MONTHS, $110, STAYED tree 1 · out: D F G tenure ≤ 5? yes no 1.0000 0.0000 36 > 5 → no E H H: 0 of 3 stay · vote 0 tree 2 · out: G charges ≤ 70? yes no 0.0000 0.8333 $110 > $70 → no A B C F F H: 5 of 6 leave · vote 1 tree 3 · out: F tenure ≤ 5? yes no 1.0000 0.0000 36 > 5 → no D E G G H: 0 of 5 stay · vote 0 tree 4 · out: B E G H charges ≤ 60? yes no 0.0000 1.0000 $110 > $60 → no A C C C F: 5 of 5 leave · vote 1 tree 5 · out: A tenure ≤ 5? yes no 1.0000 0.2000 36 > 5 → no D E F G H: 1 of 5 stay · vote 0 2 THE FOREST'S ANSWER FOR G votes: (0 + 1 + 0 + 1 + 0) ÷ 5 = 0.40 → below one half → stay, and G did stay scikit-learn averages the bucket rates instead: (0 + 0.8333 + 0 + 1.0000 + 0.2000) ÷ 5 = 0.4067 3 REPEAT WITH 30,000 RE-DRAWS: SHARE OF FORESTS WHOSE MAJORITY VOTE IS RIGHT 0.892 0.991 1.000 1.000 0.798 0.943 0.999 1.000 0.430 0.368 0.223 0.077 4 trees: 1 5 25 101 1 5 25 101 1 5 25 101 G (stayed) H (stayed) F (churned)
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.
  1. 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.
  2. 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.
  3. 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%.
  4. 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
  1. Bring in numpy and three scikit-learn pieces: RandomForestClassifier, train_test_split, and DecisionTreeClassifier.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
overfit_demo.pyruns offline
# pip install "scikit-learn>=1.6" "numpy>=1.26"
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

rng = np.random.default_rng(7)
n = 2000
X = np.column_stack([
    rng.integers(1, 72, n).astype(float),   # tenure
    rng.uniform(20, 150, n),                # monthly charges
    rng.poisson(2.2, n).astype(float),      # support tickets
    rng.poisson(12, n).astype(float),       # logins / month
])
logit = (0.04 * (X[:, 1] - 80) - 0.08 * (X[:, 0] - 12)
         + 0.50 * X[:, 2] - 0.06 * X[:, 3] - 1.0)
y = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)

X_tr, X_te, y_tr, y_te = train_test_split(
    X, y, test_size=0.3, random_state=0, stratify=y)

print("depth   train    test")
for depth in [2, 4, 8, None]:
    t = DecisionTreeClassifier(max_depth=depth, random_state=0).fit(X_tr, y_tr)
    print(f"{str(depth):>5}   {t.score(X_tr, y_tr):.3f}   {t.score(X_te, y_te):.3f}")

# The fix, previewed: 300 decorrelated trees, votes averaged
rf = RandomForestClassifier(n_estimators=300, random_state=0).fit(X_tr, y_tr)
print(f"\nforest  {rf.score(X_tr, y_tr):.3f}   {rf.score(X_te, y_te):.3f}")
Failure mode

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.

1.00 0.90 0.80 0.70 0.60 1 DEPTH 2 · honest 0.847 0.830 one tree, max_depth = 2 2 NO DEPTH LIMIT · memorises 1.000 0.787 one tree, max_depth = None gap 0.213: memorised noise 3 FOREST OF 300 · best test 1.000 0.852 300 trees, votes averaged accuracy = share of customers classified correctly dashed outline = score on the rows the model trained on · filled = score on 600 rows it never saw
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.
  1. 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.
  2. 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.
  3. 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.
1.00 0.90 0.80 0.70 1 2 4 8 12 single tree max_depth → accuracy train test sweet spot ≈ depth 4 the overfitting gap 1 2 3
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.
  1. 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.
  2. 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.
  3. 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 rowsleaf {A, B} = (0.25 + 0.25) / 2 = +0.2500; leaf {C, D} = (0.25 − 0.75) / 2 = −0.2500
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 0A +0.2500, B +0.2500, C +0.2500, D −0.7500. The churners are under-predicted; the stayer is over-predicted.
Round 1 predictionA and B: 0.7500 + 0.5 × 0.2500 = 0.8750. C and D: 0.7500 + 0.5 × (−0.2500) = 0.6250.
Residuals after round 1A +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.
Tree 2 leaf valuesleaf {A, B, D} = (0.1250 + 0.1250 − 0.6250) / 3 = −0.1250; leaf {C} = +0.3750.
Round 2 predictionA 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 truthD, 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.

1 ROUND 0: everyone starts at 0.7500 1.0 0.5 0.0 +0.2500 A +0.2500 B +0.2500 C −0.7500 D predictions: 0.7500, 0.7500, 0.7500, 0.7500 size of all leftovers added up: 1.5000 2 ROUND 1: + 0.5 × tree 1's leaf 1.0 0.5 0.0 +0.1250 A +0.1250 B +0.3750 C −0.6250 D predictions: 0.8750, 0.8750, 0.6250, 0.6250 size of all leftovers added up: 1.2500 3 ROUND 2: + 0.5 × tree 2's leaf 1.0 0.5 0.0 +0.1875 A +0.1875 B +0.1875 C −0.5625 D predictions: 0.8125, 0.8125, 0.8125, 0.5625 size of all leftovers added up: 1.1250 the label: 1 churned, 0 stayed the running prediction after this round the leftover the next tree must fix D's leftover shrinks 0.7500 → 0.6250 → 0.5625 and is now the largest. The only tree that helps next is one with a leaf holding D alone.
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.
  1. 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.
  2. 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.
  3. 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.

1 THE FOREST: 300 TREES VOTE AT ONCE 1,400 training customers tree 1 tree 2 … tree 300 average of 300 votes error that differs from tree to tree → averaged to ≈ 0 error every tree makes the same way → stays: the floor SCOREBOARD · section 04 · 600 test customers one tree, unlimited depth: train 1.000 · test 0.787 forest of 300, no tuning: train 1.000 · test 0.852 ← best 2 BOOSTING: A QUEUE, EACH TREE FED THE LAST ONE'S LEFTOVERS tree 1 leftovers tree 2 leftovers tree 3 … D's leftover in Fig. 3.3b: 0.7500 → 0.6250 → 0.5625, smaller each round each correction × learning rate 0.05, so no single tree can dominate early stopping: stop when the validation score has not improved for 50 rounds without the stopping rule: a leaf for D, then a leaf for everyone, and the training score walks to 1.000 one small step at a time SCOREBOARD · section 05 · 2,400 untouched test customers logistic regression baseline: ROC-AUC 0.8932 XGBoost: ROC-AUC 0.9272 · stopped itself at tree 109 of 2,000 3 WHAT THEY AGREE ON a test set neither has touched decides; if both barely beat 0.8932, the problem is the columns, not the model
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.
  1. 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.
  2. 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.
  3. 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.

1 12,000 GENERATED CUSTOMERS, CUT INTO THREE SLICES BEFORE ANYTHING IS FIT train · 7,680 rows (64%) val · 1,920 test · 2,400 the preprocessor and every tree are fit here, and only here early stopping watches this touched once, at the end 2 INSIDE EVERY SLICE, ABOUT ONE CUSTOMER IN FIVE CHURNS churners 20.6% stayers 79.4% scale_pos_weight = stayers ÷ churners = 0.794 ÷ 0.206 ≈ 3.85, so every churner counts about four times in the loss
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%.
  1. 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.
  2. 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.

  1. 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
    1. Fix the random seed so every run builds the same customers.
    2. Draw the five number columns: tenure, charges, tickets, logins and feature adoption.
    3. Draw the three category columns (contract, tech support, payment method) with the stated odds.
    4. 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.

    terminalactual output
    (12000, 8)
       TenureMonths  MonthlyCharges  SupportTickets  LoginFrequency  FeatureAdoption
    0             7           79.21               1              12             64.5
    1            55           35.45               5              11             17.8
    2            47           93.99               0              13             31.2
  2. 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
    1. Build a churn score from the columns; each “only when” term is a number multiplied by a True/False condition.
    2. Turn the score into a probability with the logistic S-curve.
    3. Roll a dice per customer: churn if the dice number is below their probability.
    4. 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.

    terminalactual output
    churn rate 20.6%
    ContractType
    Month-to-Month    0.298
    One-Year          0.093
    Two-Year          0.096
  3. 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
    1. 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.
    2. Make a preprocessor: scale the numbers, one-hot the categories.
    3. Fit the preprocessor on the training rows only, then transform all three slices.
    4. 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
  4. 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
    1. Compute the ratio of stayers to churners in the training rows, so the rare class is not drowned out.
    2. Create the classifier: slow learning rate, trees at most 5 questions deep, each tree sees 90% of rows and columns.
    3. Fit with the validation slice as a referee; stop after 50 trees in a row bring no improvement.
    4. 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
  5. 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
    1. Build a tree explainer from the fitted model.
    2. Compute each feature's push for every test customer.
    3. Average the absolute pushes per feature.
    4. 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.

    terminalactual output
    ...
    global drivers (mean |SHAP|):
      MonthlyCharges                 1.055
      TenureMonths                   0.924
      ContractType_Month-to-Month    0.622
      TechSupport_No                 0.499
      SupportTickets                 0.492
  6. Chunk 6 — answer one customer in plain words

    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
    1. Turn the customer dictionary into a one-row table and apply the saved preprocessor.
    2. Ask the model for the churn probability, and the explainer for per-feature pushes.
    3. Keep the three biggest pushes by size.
    4. 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.

    terminalactual output
    ...
    {
      "customer_id": "CUST-9842",
      "churn_probability": 0.985,
      "risk_level": "CRITICAL",
      "action": "CSM call within 24h + targeted retention offer",
      "top_drivers": [
        {
          "feature": "TenureMonths",
          "direction": "towards churn",
          "weight": 1.33
        },
        {
          "feature": "MonthlyCharges",
    ...

The whole program

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
  1. 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.
  2. Name the columns: NUM_COLS holds the five numeric features, CAT_COLS the three categorical ones (contract type, tech support, payment method).
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.
  9. 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.
  10. Compute spw, stayers divided by churners, from the training fold only. It comes to about 4.
  11. 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.
  12. Fit it with the validation slice as eval_set, then predict churn probabilities for the test rows.
  13. 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.
  14. 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.
  15. 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))
outputrepresentative run
churn rate 20.6%  (train 7680 / val 1920 / test 2400)
stopped at tree 109 of 2000
logistic  ROC-AUC 0.8932
xgboost   ROC-AUC 0.9272   PR-AUC 0.8112

global drivers (mean |SHAP|):
  MonthlyCharges                 1.055
  TenureMonths                   0.924
  ContractType_Month-to-Month    0.622
  TechSupport_No                 0.499
  SupportTickets                 0.492

{
  "customer_id": "CUST-9842",
  "churn_probability": 0.985,
  "risk_level": "CRITICAL",
  "action": "CSM call within 24h + targeted retention offer",
  "top_drivers": [
    {
      "feature": "TenureMonths",
      "direction": "towards churn",
      "weight": 1.33
    },
    {
      "feature": "MonthlyCharges",
      "direction": "towards churn",
      "weight": 1.01
    },
    {
      "feature": "SupportTickets",
      "direction": "towards churn",
      "weight": 0.69
    }
  ]
}

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.

ROC-AUC on the 1,920 validation customers (higher is better) 0 50 100 150 200 2,000 = the ceiling trees built so far → best: tree 109 stopped: tree 159 50 rounds with no improvement 1,840 trees never built 1 2 3
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.
  1. 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.
  2. 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.
  3. 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
model = xgb.XGBClassifier(
    n_estimators=2000,1
    early_stopping_rounds=50,2
    learning_rate=0.05,3
    max_depth=5,4
    subsample=0.9, colsample_bytree=0.9,5
    scale_pos_weight=spw,6
    eval_metric="auc",7 tree_method="hist", random_state=42,
)
model.fit(Xt_tr, y_tr, eval_set=[(Xt_va, y_va)],8 verbose=False)
  1. 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.
  2. 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."
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.

base value −1.35 (avg customer, p ≈ 0.21) Contract = M2M +0.78 Tenure = 3 mo +0.66 Tickets = 5 +0.55 Logins = 2 / mo +0.37 TechSupport = No +0.26 Adoption = 9% +0.21 Charges = $62 −0.23 f(x) = +1.25 → p(churn) = 0.78 −2 −1 0 +1 +2 log-odds score → right = more churn risk 1 2 3 4
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.
  1. 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.
  2. 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.
  3. 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.
  4. 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.

mean |SHAP| over the 2,400 test customers, in log-odds units MonthlyCharges 1.055 TenureMonths 0.924 ContractType = Month-to-Month 0.622 TechSupport = No 0.499 SupportTickets 0.492 0 0.5 1.0 1 2
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.
  1. 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.
  2. 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.
CustomerTenureMonthly chargesSupport ticketsContractSupport planChurned?Model says
#602364 months$22.770Two-yearYesNo0.0070
#1079222 months$76.011Month-to-monthNoYes0.4512
#147635 months$82.423Month-to-monthNoNo0.5701
CUST-98423 months$118.505Month-to-monthNoNot yet known0.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.

  1. 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.
  2. η = 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.
  3. η = 0.5, the exercise's choice. A and B move to 0.8750, and C and D to 0.6250.
  4. η = 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 addsProbability after tree 1η = 0.5: tree 1 addsProbability after tree 1
#6023−0.09350.4767−0.93450.2820
#10792+0.00130.5003+0.01300.5033
#1476+0.00130.5003+0.01300.5033
CUST-9842+0.08720.5218+0.87240.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 same letter, η, in the two modules
Module 02: gradient descentThis module: gradient boosting
One step changesThe weights, one number per columnEvery customer's score, by adding one tree
The updatew ← w − η × slopescore ← score + η × the tree's correction
The step is fitted toHow fast the loss changes as each weight changesEach training customer's leftover: label minus current probability
A typical value0.005 in Module 02's gradient_descent.py0.05 in churn_engine.py; XGBoost's default is 0.3
When η is too bigThe loss climbs to infinity: 123 steps on raw cart valuesNothing blows up; the model overfits in fewer trees
Units of the columnsMatter: unscaled columns shrink the safe ηDo not matter: a tree only compares values with cut-offs
How η is chosenThe largest value whose loss still falls smoothlyA 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 keptTrees builtValidation AUCTest AUC
1.05550.90490.9106
0.59590.91000.9237
0.327770.91390.9213
0.146960.91440.9239
0.051101600.91710.9272
0.015646140.91690.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.

1 SAME TREE 1, TWO LEARNING RATES: CUST-9842 η = 0.05 +0.0872 → probability 0.5218 η = 0.5 +0.8724 → probability 0.7052 0 0.25 0.5 0.75 1.0 log-odds after tree 1 (0 is the starting 50%) same tree, same leaf: +0.8724 is ten times +0.0872 η multiplies the tree's output, not its questions 2 THE SWEEP: TREES KEPT AND TEST AUC trees kept (log scale) test AUC η 1.0 5 0.9106 η 0.5 9 0.9237 η 0.3 27 0.9213 η 0.1 46 0.9239 η 0.05 110 0.9272 η 0.01 564 0.9267 3 η = 1.0, NO EARLY STOPPING: NOTHING EXPLODES log-loss (lower is better) 0 0.2 0.4 0.6 0.8 1 10 100 300 trees built (log scale) 4 training: 0.4457 at tree 1 → 0.0053 at tree 300 validation: lowest 0.3711 at tree 5 → 0.7089 Module 02, η too big: loss → infinity in 123 steps
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.
  1. 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.
  2. 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.
  3. 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.
  4. 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.

  1. Start. Every customer begins at log-odds 0.0000, and σ(0) = 1 ÷ (1 + 1) = 0.5000.
  2. 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.
  3. Trees 2 and 3. Leaves worth +0.0917 and +0.0886. Log-odds 0.1790, then 0.2676; probability 0.5446, then 0.5665.
  4. Trees 4 to 10. Seven more leaves. Log-odds 0.7589; probability 0.6811.
  5. 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.
  6. 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 draws the running total, tree by tree.

running log-odds (left axis) · the same score as a probability (right edge) 0 1 2 3 4 5 0.500 0.731 0.881 0.953 0.982 0.993 0 25 50 75 100 125 150 trees added so far 1 tree 1: +0.0872 → 0.5218 tree 2: +0.0917 → 0.5446 tree 3: +0.0886 → 0.5665 after 10 trees: 0.7589 → 0.6811 2 tree 110, last kept: 4.2165 → 0.9855 3 built, not kept: 4.7976 → 0.9918 4
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.
  1. The start. Before any tree, every customer sits at log-odds 0, probability 0.500, set by XGBoost's base_score of 0.5.
  2. 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.
  3. 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.
  4. 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
CustomerSum of 110 leaves (log-odds)σ of that sum (probability)What happened
#6023−4.94890.0070Stayed
#10792−0.19570.4512Churned
#1476+0.28210.5701Stayed
CUST-9842+4.21650.9855Not 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.
CustomerLabelForest: tree 2 learnsBoosting: probability after tree 1Boosting: tree 2 learns
#60230 (stayed)0, if its re-draw picked #60230.47670 − 0.4767 = −0.4767
#107921 (churned)1, if picked0.50031 − 0.5003 = +0.4997
#14760 (stayed)0, if picked0.50030 − 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 grownIndependently, in any order, on any number of coresOne after another; tree 2 needs tree 1's leftovers
What each tree learnsThe label: who churnedThe leftover: label minus current probability
How deep each tree goesNo limit: it memorises its re-drawAt most 5 questions: a small correction
How trees combineThe average of 300 answersThe sum of 110 leaf values, then the sigmoid
What combining removesMistakes that differ between trees (variance)Mistakes the trees so far share (bias)
What stops itA fixed tree count; more trees only settle the averageEarly stopping; without it, it keeps fitting leftovers until it memorises
Training AUC1.00000.9524
Test AUC (logistic baseline 0.8932)0.91690.9272
CUST-9842257 of 300 trees say churn → 0.8567110 leaves sum to 4.2165 → 0.9855

Fig. 3.4j puts the two combining rules next to each other, with CUST-9842's numbers.

1 FOREST: EVERY TREE LEARNS THE LABEL tree 2's targets: #6023 → 0 · #10792 → 1 · #1476 → 0 (for whichever rows its own re-draw picked) CUST-9842: 257 of 300 trees vote churn (filled) average: 257 ÷ 300 = 0.8567 training AUC 1.0000 · test AUC 0.9169 2 BOOSTING: TREE 2 LEARNS WHAT TREE 1 LEFT OVER #6023, stayed · after tree 1: 0.4767 0 1 leftover −0.4767 #10792, churned · after tree 1: 0.5003 0 1 leftover +0.4997, counted 3.84× #1476, stayed · after tree 1: 0.5003 0 1 leftover −0.5003 CUST-9842: 110 small leaves add up to 4.2165 σ(4.2165) = 0.9855 training AUC 0.9524 · test AUC 0.9272 3 WHAT EACH WAY OF COMBINING FIXES forest, average of independent answers: cancels mistakes that differ between trees (variance) boosting, sum of corrections: removes mistakes the trees so far share (bias), until early stopping
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.
  1. 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.
  2. 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).
  3. 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.

small · under 10K rows mid · 10K to a few million huge · 10M rows and up rows in the table → columns hold text or images columns hold dollars, counts, categories deep learning only when the columns are perceptual, or you need embeddings downstream cost: GPU hours plus weeks of tuning 4 logistic regression always first, as the baseline cost: seconds TabPFN: worth a try under 10K rows 1 XGBoost the tabular default cost: minutes on a laptop SaaSify: 12,000 rows, 8 columns 2 LightGBM leaf-wise growth, 2 to 10× faster cost: minutes, even at 10M+ rows 3
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.
  1. 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.
  2. 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.
  3. 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.
  4. 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)
OptionChoose whenAvoid whenTypical cost
Logistic regressionAlways, as the baseline: fast, calibrated-ish probabilities, auditable coefficientsInteractions dominate and you can't hand-craft them allSeconds to train
XGBoostThe tabular default: strongest regularization story (level-wise growth, L1/L2, early stopping), robust on small-to-mid dataData so large that training time dominates iteration speedMinutes on a laptop
LightGBMLarge 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 limitsMinutes, even at 10M+ rows
Deep learning on tablesHuge data plus multimodal columns (free text, images), or you need learned embeddings downstreamMost business tables — GBDTs match or beat it with 100× less tuningGPU 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)
LayerWe useAlternativesWhy this oneSwitch when
Boosting libraryXGBoost 3.x (tree_method="hist")LightGBM 4.x, CatBoost, scikit-learn HistGradientBoostingThe 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.
BaselineLogistic regression (scikit-learn 1.9)A single decision tree, a random forestA 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 splitsTrain 64% / validation 16% / test 20%5-fold cross-validation, time-based splitGives 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.
TuningHand-picked settings plus early stoppingGrid search, OptunaTwo 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.
ExplanationsSHAP 0.52 (TreeExplainer)XGBoost feature_importances_, permutation importance, LIMESigned 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.
ServingA Python function over the fitted objectsXGBoost saved as JSON, ONNX Runtime, TreeliteZero 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.

1 PURE BUCKET A, B, C A A B B C C 0 of 9 pairs disagree Gini = 0 ÷ 9 = 0.0000 2 MIXED BUCKET D, E, F, G, H (only F churned) D D E E F F G G H H 25 ordered pairs 8 pairs disagree: F with a stayer, in either order Gini = 8 ÷ 25 = 0.3200 same as 1 − 0.2² − 0.8² = 1 − 0.04 − 0.64 = 0.32 shaded = the two draws have different labels · a draw may pick the same customer twice
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.
  1. 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.
  2. 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.

variance of the averaged vote = ρσ² + (1 − ρ)σ²/n, with σ² = 1 and ρ = 0.3 1.0000 1 tree 0.3700 10 trees 0.3070 100 trees 0.3023 300 trees ← floor ρσ² = 0.30 the error all trees share 1 2
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.
  1. 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.
  2. 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.

This one formula explains the Brain Power answer above and is worth being able to reproduce in an interview.

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!
1 100 CUSTOMERS, 5 OF THEM (RED) ABOUT TO CHURN 2 A MODEL THAT SAYS "NO CHURN" TO ALL 100 right on 95, wrong on 5 → accuracy 95% churners caught: 0 of 5 → recall 0% the 95% is the base rate, not the model. A ranking metric (ROC-AUC, PR-AUC) asks whether the 5 red dots are scored above the 95 hollow ones, which a constant model cannot do at SaaSify the split is 20.6 / 79.4, so "nobody churns" scores 79.4%
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.
  1. 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.
  2. 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).

300 calls the top of the ranked list ≈ 165 real flight risks 300 × 55% precision ≈ 50 saved 165 × 30% save rate ≈ $7.4K a month, kept 50 × $147, and it recurs 1 return: $7.4K a month × 18 months of remaining lifetime ≈ $130K per monthly cohort of saves cost at worst: 300 offers × 20% × $147 × 3 months ≈ $26K $130K against $26K ≈ 5×, versus the $128K-a-month shotgun in Fig. 3.0b 2
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.
  1. 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.
  2. 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?