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

Predictive Analytics — Regression, Classification & Gradient Descent

"Data is raw noise until you fit a signal to it."

~6 hours Builds on: Module 01 Tools: scikit-learn · pandas · numpy Job-spec line it unlocks: "Classical ML (scikit-learn) + ML fundamentals"

01 · The hookThe $800K Marketing Black Hole

Two questions cover most business prediction: “how much?” and “which one?” This page builds both from scratch, and shows the one mechanism that trains almost every model you will ever use.

Field report · Client memo

"We're spending $800K per quarter on marketing, and I have NO idea which customers will actually buy. We blast the same email to 2 million users. Our conversion rate is 1.8%. That means 98.2% of our budget is WASTED. I need a model that predicts WHO will buy and HOW MUCH they'll spend — by next sprint."

— Elena Torres, CMO of "CartGenius"

CartGenius is a mid-size e-commerce retailer selling electronics and home goods to 2 million registered users. Their marketing strategy is spray-and-pray: the same promotional email to every single user, every campaign. The numbers are brutal — $800K a quarter buys a 1.8% conversion rate, while competitor SmartShop runs predictive targeting and converts at 12%. That gap is not a creative problem or a copywriting problem. It's a targeting problem, and targeting problems are prediction problems.

Elena needs two models. First, a conversion classifier: for each visitor, the probability that they'll purchase — not a yes/no guess, an actual number between 0 and 1 she can rank users by and spend against.

That per-user probability is called a propensity score, and it's the load-bearing artifact of this whole module.

Second, a spend predictor: for likely buyers, a continuous dollar estimate of how much they'll spend, so the $200-cart customer gets the premium treatment and the $12-cart customer doesn't get a courier-delivered gift box.

Your mission: build both — logistic regression for the classifier, regularized linear regression for the spend predictor — inside a production-grade scikit-learn pipeline that survives missing data, unseen categories, and a real-time JSON inference path. Along the way you'll implement the training algorithm itself from scratch, because gradient descent is the engine under every model in this course, all the way up to the LLMs in Act IV.

You already know this

You've been doing gradient descent for nine years — on latency dashboards. Training a model is an optimization loop against a single scalar metric, exactly like performance tuning:

The ML → SWE dictionary for this module
ML conceptYou already ship this
Loss functionThe p95 latency graph — one number that tells you how wrong the system is right now
GradientThe profiler flame graph — which knob moves that number the most, and in which direction
Learning rateCanary rollout step size — too aggressive and you take prod down, too timid and the migration takes a quarter
OverfittingHardcoding until the test suite passes — green CI, broken prod
RegularizationThe lint/complexity budget that blocks the clever 400-character one-liner
Train / test splitNever benchmarking on the box you tuned on

Before the first objection, here is the difference drawn. The left half of Fig. 2.0b is the if statement as CartGenius runs it today; the right half is what Elena asked for.

1 THE IF STATEMENT SORTS INTO TWO PILES 2,000,000 users on the list if cart_value > 100 and is_returning two cutoffs, both guessed 2 YES pile → send offer all of them look the same NO pile → nothing buyers hide in here too today: the same email to all 2,000,000 → 1.8% buy 36,000 people; $800K a quarter, 98.2% of it wasted a yes/no rule cannot say which yes to fund first 3 THE MODEL SCORES EVERY USER, THEN SORTS probability of buying, highest first 0.98 0.83 0.71 0.40 0.12 0.02 ← the $800K runs out here the cut moves when the economics change 0.83 = "83% likely to buy": a number you can sort by spend down the list until the $800K is gone seven features × seven weights, fitted, not guessed
Fig. 2.0b — The if statement and the model, side by side. The if statement splits 2 million users into two piles it cannot order, so the $800K goes to everyone and 1.8% buy. The model gives every user a probability, sorts the list, and lets Elena spend from the top until the budget is gone. The six scores on the right are made up to show the sort; 2 million, 1.8% and $800K are Elena's numbers.
  1. The guessed cutoffs. The if statement has two features and two numbers, 100 and "returning", and somebody chose those numbers from experience. Nothing checks them against what buyers actually did. Logistic regression keeps the same shape, a few features and a cutoff, but the weights are fitted to the logs, and the fitting loop in section 03 is what replaces the guessing.
  2. The two piles. A yes/no rule puts every user in one of two boxes. Inside the YES pile a $200 cart and a $101 cart look identical, so there is no way to send the premium offer to the better prospect first, and no way to shrink the pile when the budget shrinks. Real buyers sit in the NO pile too, and the if statement cannot see them.
  3. The sorted list. The model outputs a number between 0 and 1 for every user. Sort the list, contact from the top, stop when the $800K is spent: that is the whole marketing plan. When finance changes what a contact costs, the dashed line moves and the list stays; the lab in section 07 sets that line with money.

"I have shipped nine years of if statements. if cart_value > 100 and is_returning: send_offer(). Why is that not the model?"

— a backend engineer, reading the hook

It is a model, and it is the left half of Fig. 2.0b. Marker 1: it has two features and two cutoffs you guessed. Marker 2: it outputs a yes or a no, two piles. Logistic regression is the same idea with the numbers chosen by data instead of by you: seven features, a weight on each, and one cutoff on the combined score. The fitting loop in section 03 is what replaces the guessing.

The output is the real difference, and it is marker 3 in Fig. 2.0b. Your rule says yes or no. The model says 0.83, and Elena can sort two million users by that number and spend down the list until the $800K runs out. A yes-or-no rule cannot tell her which of the yeses to fund first, and it cannot move the cutoff when the economics change.

The honest downside: the fitted model needs labelled history, goes stale as behaviour shifts, and is harder to explain in a code review than one line. When you have two features and the two cutoffs are obvious, write the if statement. You will want the model when the third feature arrives and nobody can guess its threshold.

02 · The intuitionA Line, a Foggy Mountain, and a Dimmer Switch

Elena's memo gave us two questions and one budget: which of the 2 million users will buy, and how much each will spend, with $800K a quarter riding on the answers. We have CartGenius's own logs: minutes on site, pages viewed, cart value, and what each person actually spent. The first thing we need is a way to turn a column of minutes into a prediction of spend. That is a line, and it is where this section starts.

Linear regression: the best-fit line

Plot every CartGenius customer's session duration against their total spend and you'll see a fuzzy upward trend: people who browse longer tend to spend more.

Linear regression commits to the simplest possible story about that trend — a straight line, ŷ = w·x + b — and then asks: of all possible lines, which one is least wrong?

"Wrong" is measured by the residuals: the vertical gaps between each real data point and the line's prediction for it. Square each gap (so overshoots and undershoots can't cancel out), average them, and you get the mean squared error (MSE).

The best-fit line is the one that makes that average as small as possible.

session minutes → total spend ($) ŷ = w·x + b residual = y − ŷ
Fig. 2.1 — Linear regression chooses w and b to minimize the average of the squared dashed gaps (residuals) between the data and the line.

Gradient descent: the blindfolded hiker

We now have a line, and Fig. 2.1 shows that some lines fit CartGenius's points better than others. Nobody is going to try a million lines by hand. We need a procedure that finds the best w and b on its own. That procedure is the hiker below, and it is the same loop that trains every model in this course.

But how does the algorithm find the winning w and b? Picture yourself blindfolded on a foggy mountain, where your position is the current (w, b) and your altitude is the MSE. Your goal is the lowest valley. You can't see — but you can feel the slope under your boots. That felt slope is the gradient: the direction of steepest ascent. Strategy: step in the opposite direction, downhill. Your stride length is the learning rate (η). Too big a stride and you leap clean over the valley and land higher on the far wall; too small and you shuffle for a week. Repeat until the ground feels flat — flat ground means zero gradient means you've converged. Seen from above, the error surface is a bowl of nested contour rings, and the hiker's trail cuts across them toward the center:

each ring = constant MSE start: random (w, b) big early strides steps shrink as slope flattens minimum error w → b ↑
Fig. 2.2 — Gradient descent seen from above: each step moves perpendicular to the local contour (straight downhill), and the steps shrink automatically as the gradient flattens near the minimum.
🧠 Brain power

Before reading on: the step size η multiplies the felt slope. What happens if η is 10× too large? Not "slightly slower convergence" — reason it out on the bowl in Fig. 2.2. And what does the elongated shape of those contours (a valley, not a round bowl) do to the hiker's path?

Reveal the answer

Each oversized step crosses the valley floor and lands higher on the opposite wall, where the slope is steeper, so the next step is even bigger. The error doesn't just fail to shrink — it compounds, doubling-and-worse each iteration until the numbers overflow to inf.

Divergence, not slow convergence. The elongated valley makes it worse: the safe step size is set by the steepest direction, so in the shallow direction that same η crawls — which is why the path zigzags across the valley instead of gliding down it. You will produce this exact failure, on purpose, in section 04.

Measure the error.

Feel the slope.

Step downhill.

Repeat until the ground is flat.

Measure the error: add up the squared gaps in Fig. 2.1. Feel the slope: work out which small change to w and b would make that total smaller. Step downhill: make that change. Flat: the total has stopped shrinking, so the line is as good as this ruler can make it.

Logistic regression: the S-curve dimmer switch

The line answers Elena's second question, how much. Her first question, which one, needs a yes or a no, and a line will happily predict minus thirty dollars of buying. We need the same machinery to output a probability between 0 and 1 instead. That is one extra squashing step, and it is the whole of this part.

Linear regression happily outputs −$30 or $5,000 — fine for spend, nonsense for "will they buy?". A probability must live in [0, 1]. Logistic regression keeps the linear machinery — compute a score z = w·x + b — but feeds that score through the sigmoid, an S-shaped squashing function.

Think of z as raw voltage and the sigmoid as a dimmer switch: crank the voltage strongly negative and the lamp is fully off (p ≈ 0), strongly positive and it's fully on (p ≈ 1), and near zero it glides smoothly through every brightness in between.

No cliff edges, which means it's differentiable, which means the same blindfolded hiker can train it.

z = w·x + b (linear score) P(buy) −6 −4 −2 0 2 4 6 0.0 0.5 1.0 threshold p = 0.5 — a dial YOU set, not a law z = −6 → p ≈ 0.002 (won't buy) z = +6 → p ≈ 0.998 (will buy)
Fig. 2.3 — The sigmoid σ(z) squashes any real-valued score into a probability. The 0.5 threshold is only a default: where you cut is a business decision (the lab makes it a profit-maximizing one).
🧠 Brain power

Before reading on: a teammate proposes skipping logistic regression entirely — "just fit linear regression on spend, and if predicted spend > $50, call them a buyer." What breaks?

Reveal the answer

The output isn't a probability, so there's nothing to rank or budget against. A prediction of −$30 or $500 answers "how much" (badly), not "how likely." Elena needs "this user is 83% likely to convert" so spend can follow probability — top decile gets the premium offer, and the cutoff can move as economics change.

A hard $50 rule gives one frozen, uncalibrated boundary, and squared-error training lets far-away outliers drag that boundary around even when their classification was never in doubt.

The sigmoid + log-loss combo (section 06) fixes both: outputs live in [0, 1], and confident-but-wrong predictions are punished hardest.

Regularization: the leash on an overexcited puppy

With more CartGenius columns the model gets more weights, and more weights means more ways to memorise last quarter's noise instead of learning next quarter's customers. Before we build anything we need a leash. It is the last idea in this section, and it comes back as a dial you can turn in the lab.

Give a flexible model enough features and it behaves like an overexcited puppy — chasing every squirrel-shaped fleck of noise in the training data. It looks brilliant in training and faceplants on new users: overfitting.

Regularization is the leash: alongside "fit the data," the loss gains a second term that says "…while keeping the weights small." The two classic leashes differ in geometry, and the geometry is the whole story.

Give the weights a fixed "budget region" they must stay inside while the loss contours expand outward from their unconstrained optimum until first contact:

w₁ w₂ loss contours corner hit → w₁ = 0 L1 (Lasso) — diamond budget w₁ w₂ flank hit → both weights shrink, neither is 0 L2 (Ridge) — circular budget
Fig. 2.4 — Regularization as a weight budget. Expanding loss contours meet the L1 diamond at a corner, where a coordinate is exactly zero (automatic feature selection); they meet the L2 circle on its smooth flank, so every weight shrinks but none dies.

In leash terms, there are three options:

Elena's team gets a bonus from either. A smaller, calmer model is also a more explainable model.

03 · Build it yourselfGradient Descent in Under 30 Lines

Everything in section 02 was a picture. Now we make it run on CartGenius-shaped data: 400 sessions, minutes against spend, and a loop of under thirty lines that finds the line by itself. Watch the loss fall from 6,555 to 82.7 in the output, and know what each of those numbers means before moving on.

You have met every idea in the file below, but none of the numpy calls. That is fine. The step-by-step list above the code names what each call does, and the five lines inside the for loop are the only ones that carry the lesson. Section 06 derives the two gradient formulas if you want to see where they come from.

Before sklearn hands you .fit(), earn it. Here is the entire training algorithm — the same loop that, scaled up about a trillion-fold, trains GPT — fitting a spend line to synthetic session data. Two gradient formulas and a subtraction, that's the whole trick (derivations in section 06):

Step-by-step: what gradient_descent.py does, in plain English
  1. Bring in numpy and create a random number generator seeded with 42, so every run produces the same "random" data and the printed trace matches yours.
  2. Manufacture 400 fake sessions. minutes comes from an exponential distribution (many short sessions, a few long ones). spend is built from the truth we hope to recover, 6.5 × minutes + 12, plus noise with a spread of 9.
  3. Start the line at w = 0 and b = 0, which is a flat line along the floor, and set the learning rate eta to 0.005. n is the row count, used in the averages below.
  4. Loop 4,001 times. Each pass through the loop is one step of the hiker.
  5. Forward pass: y_hat is what the current line predicts for every session, all 400 at once.
  6. Residuals: err is prediction minus truth for every row. Positive means the line sits too high for that row, negative means too low.
  7. The slope along w: multiply each residual by its minutes value and sum (that is what @ does with two one-dimensional arrays), then scale by 2/n. This is the formula section 06 derives.
  8. The slope along b: the same sum without the multiply, because b shifts every prediction by the same amount.
  9. Move both weights opposite their slope, scaled by eta. The minus sign is the entire "descent".
  10. Every 800 steps, print the step number, the current mean squared error and the current w and b, so you can watch the altitude fall.
  11. After the loop, print the learned line next to the truth it was supposed to find.
gradient_descent.pyruns offline
# pip install "numpy>=2,<3"          # verified on numpy 2.5, Aug 2026
import numpy as np

rng = np.random.default_rng(42)

# Ground truth we hope to recover: spend = 6.5 × minutes + 12 + noise
minutes = rng.exponential(scale=8.0, size=400)
spend = 6.5 * minutes + 12.0 + rng.normal(0.0, 9.0, size=400)

w, b = 0.0, 0.0        # drop the hiker anywhere on the mountain
eta = 0.005            # stride length — tuned; see what 0.01 does in section 04
n = len(minutes)

for step in range(4001):
    y_hat = w * minutes + b               # forward pass: the current line's guesses
    err = y_hat - spend                   # residuals: how wrong, and in which direction
    grad_w = (2.0 / n) * (err @ minutes)  # ∂MSE/∂w — slope felt underfoot
    grad_b = (2.0 / n) * err.sum()        # ∂MSE/∂b
    w -= eta * grad_w                     # step OPPOSITE the gradient: downhill
    b -= eta * grad_b
    if step % 800 == 0:
        print(f"step {step:4d}   MSE={np.mean(err**2):9.1f}   w={w:6.3f}   b={b:6.3f}")

print(f"\nlearned: spend = {w:.2f} × minutes + {b:.2f}   (truth: 6.5x + 12)")
terminalactual output
step    0   MSE=   6555.0   w= 8.774   b= 0.630
step  800   MSE=     82.7   w= 6.636   b=10.297
step 1600   MSE=     82.7   w= 6.622   b=10.514
step 2400   MSE=     82.7   w= 6.622   b=10.519
step 3200   MSE=     82.7   w= 6.622   b=10.519
step 4000   MSE=     82.7   w= 6.622   b=10.519

learned: spend = 6.62 × minutes + 10.52   (truth: 6.5x + 12)

Here is that printed trace as a picture, with the steps the printout skips filled in.

1 ALTITUDE: STEP 1 IS A CLIFF MSE step → 0 1 2 6,555 at step 0 a line flat on the floor 399 after one step: 94% of the error gone 141 one step removed 94% of the error: steepest ground where the miss is biggest 2 ZOOMED IN: DOWN TO THE NOISE FLOOR MSE (0 to 450) step (not to scale) → 1 2 10 100 400 800 399 141 126 101 84 82.7 noise floor 81 = 9² nothing left to learn 82.7 ≈ 81: this line has learned everything learnable 3 THE TWO KNOBS: w JUMPS, b CREEPS b w → 0 5 10 0 6 12 step 0 step 1 w 8.77 b creeps up 4.3 → 9.0 → 10.5 learned 6.62, 10.52 truth 6.5, 12 w: steep axis, one jump b: shallow axis, 800 small steps
Fig. 2.4b — The printed trace as a picture. Panel 1: the first step removes 94% of the error. Panel 2: the rest of the descent settles on the noise floor of 81. Panel 3: the slope w is found in one jump, the intercept b in hundreds of small steps. Steps 1, 2, 10, 100 and 400 were measured by rerunning gradient_descent.py; the printed trace shows every 800th step.
  1. The cliff. At step 0 the line lies flat on the floor, every prediction is 0, and the average squared miss is 6,555. The slope there is enormous, so the very first stride is long: after one step the error is 399, which is 94% of the error gone. That is the same plunge the hand calculation in the exercise below produces, 98.6% on two rows.
  2. The floor. The data was made as 6.5 × minutes + 12 plus noise with a spread of 9. Noise cannot be predicted, and its average squared size is 9² = 81, so no line can score below 81 on this data. An error of 82.7 means the line has learned everything learnable. When the number stops moving, the ground is flat.
  3. w jumps, b creeps. Every minutes value multiplies into the slope along w, and minutes average about 8, so that axis is steep and w is nearly right after one step: 8.77, then 6.98. The intercept b has no such multiplier; its axis is shallow, and b takes 800 steps to reach 10.5. One learning rate serving two axes of different steepness is the seed of the explosion in section 04.

Read the trace like a hiker's altimeter, with Fig. 2.4b open. MSE plunges from 6,555 to 83, and that plunge is marker 1 in Fig. 2.4b: the first step alone takes it to 399. The 83 is the noise floor, marker 2 in Fig. 2.4b: we injected noise with variance 9² = 81, so 82.7 means the line has learned everything learnable, and the final MSE stops moving because the ground is flat.

The recovered 6.62x + 10.52 is the true 6.5x + 12 seen through 400 noisy samples; marker 3 in Fig. 2.4b shows w arriving in one jump and b creeping in over hundreds of steps. Notice what you did not write: no matrix inversion, no solver library. Measure error → feel slope → step downhill → repeat. That loop is the single most transferable idea in this entire course.

BE the gradient step

Your turn to play the loop. The code above took 4,001 steps on 400 rows. Take one step on two rows, by hand. The inputs are below, and the two gradient formulas are the two lines from the loop written out in full. Compute the four numbers, then the error before and after.

  1. Two sessions: 2 minutes with $25 spend, and 4 minutes with $39 spend. (The line through both points is spend = 7 × minutes + 11.)
  2. Start: w = 0 and b = 0, so every prediction is 0.
  3. Learning rate eta = 0.05. Row count n = 2.
  4. err = prediction − spend, one per row.
  5. grad_w = (2/n) × Σ (err × minutes).   grad_b = (2/n) × Σ err.
  6. w ← w − eta × grad_w.   b ← b − eta × grad_b.

Write down err for both rows, then grad_w, grad_b, the new w and the new b, and the mean squared error before and after the step. Then answer two questions. Is the new w closer to the true 7, or past it? And what would eta = 0.5 have done to the same step?

Check your answer

Residuals first. Both predictions are 0, so err = 0 − 25 = −25 for the first row and 0 − 39 = −39 for the second. Both are negative: the line is below every point.

The slopes: grad_w = (2/2) × ((−25 × 2) + (−39 × 4)) = (−50) + (−156) = −206. grad_b = (2/2) × (−25 + −39) = −64. Both slopes are negative, which means the error falls as the weights rise, so the step goes up.

The step: w ← 0 − 0.05 × (−206) = 10.3, and b ← 0 − 0.05 × (−64) = 3.2. New predictions: 10.3 × 2 + 3.2 = 23.8 and 10.3 × 4 + 3.2 = 44.4. New residuals: −1.2 and 5.4.

The error: before, MSE = (625 + 1521) / 2 = 1073.0. After, MSE = (1.44 + 29.16) / 2 = 15.3. One step removed 98.6% of the error. That is the plunge you saw between step 0 and step 800 in the printed trace.

Now look at w. It went from 0 to 10.3, which is past the true 7. That is the overshoot in Fig. 2.2: the first stride is long because the slope is steep. Take a second step and the residuals (−1.2, 5.4) give grad_w = (2/2) × (−2.4 + 21.6) = 19.2, positive this time, so w falls to 10.3 − 0.96 = 9.34. The hiker zigzags in toward 7.

With eta = 0.5 the same slopes give w = 103 and b = 32. Predictions become 238 and 444, residuals 213 and 405, and MSE = 104,697. One step, and the error is a hundred times worse than where it started. That is section 04 in miniature.

Notice the cause: grad_w carries a × minutes inside it, so larger feature values make steeper slopes, and a stride that is safe for small values is fatal for large ones.

04 · Watch it breakOne Unscaled Feature Nukes the Descent

The loop worked on one feature. Elena's data has many, and they arrive on wildly different scales: page views from 0 to 15, cart values from 0 to 300. Feed both to the same loop and it explodes. This section makes it explode on purpose, so that you recognise the failure the night it happens for real.

Now add a second feature the way real product data arrives: page_views ranges 0–15, cart_value ranges 0–300. Same loop, two weights:

Step-by-step: what watch_it_diverge.py does, in plain English
  1. Seed a random generator and fix n = 500 rows.
  2. Make two features on very different scales. page_views comes from a Poisson distribution (counts around 5, rarely above 15). cart_value is uniform between 0 and 300. Build y from both, plus a constant and noise.
  3. Define fit(X, y, eta, steps). It starts with one zero weight per column and b = 0.
  4. Inside the loop, compute every row's residual with one matrix multiply: X @ w + b - y.
  5. Check whether any residual has become infinite or not-a-number. If so, return at once with the step count and an infinite MSE. This is the tripwire that reports "diverged at step 123" instead of printing 4,000 lines of garbage.
  6. Update every weight at once: X.T @ err is section 03's residual-times-feature sum, done for all columns in one line. Update b as before.
  7. If the loop runs to the end, return the step count, the final MSE and the weights.
  8. Stack the two raw columns side by side into a 500 × 2 matrix and fit. Print the result: infinite MSE after 123 steps.
  9. Standardize: subtract each column's mean and divide by its standard deviation, so both columns now have mean 0 and spread 1. That single line is the whole fix.
  10. Fit again on the standardized matrix and print. Same loop, same eta: MSE 25 after all 4,000 steps, which is the noise floor, because the noise was drawn with spread 5 and 5² = 25.
watch_it_diverge.pyruns offline
# pip install "numpy>=2,<3"          # verified on numpy 2.5, Aug 2026
import numpy as np

rng = np.random.default_rng(7)
n = 500

page_views = rng.poisson(5, n).astype(float)   # range ~0–15
cart_value = rng.uniform(0, 300, n)            # range ~0–300 ← 30× the scale
y = 3.0 * page_views + 0.05 * cart_value + 10 + rng.normal(0, 5, n)

def fit(X, y, eta=0.005, steps=4000):
    w = np.zeros(X.shape[1]); b = 0.0
    for i in range(steps):
        err = X @ w + b - y
        if not np.isfinite(err).all():          # bail out once numbers overflow
            return i, float("inf"), w
        w -= eta * (2 / len(y)) * (X.T @ err)   # same update rule, vectorized
        b -= eta * (2 / len(y)) * err.sum()
    return steps, float(np.mean(err ** 2)), w

X_raw = np.column_stack([page_views, cart_value])
steps, mse, w = fit(X_raw, y)
print(f"raw features    : MSE={mse} after {steps} steps")

X_std = (X_raw - X_raw.mean(axis=0)) / X_raw.std(axis=0)   # the one-line fix
steps, mse, w = fit(X_std, y)
print(f"standardized    : MSE={mse:.2f} after {steps} steps, w={np.round(w, 2)}")

# raw features    : MSE=inf after 123 steps      ← numeric blow-up, overflow warnings
# standardized    : MSE=25.03 after 4000 steps, w=[6.97 4.25]

Before reading the failure box, look at what the two runs did to the loss bowl. Fig. 2.4c repeats Fig. 2.2 on the left and shows the canyon the raw cart values dig on the right.

1 FIG. 2.2 AGAIN: ONE FEATURE, A BOWL start minimum b ↑ w → one feature (minutes): the same η = 0.005 walks in and stops at the bottom (section 03) each ring is one value of the loss, as in Fig. 2.2 2 TWO RAW FEATURES: A CANYON, NOT A BOWL the slot: rings squeezed start step 1: across, and higher step 2: miss × 305 step 3: higher still step 4: miss × 305 again step 123: infinity 3 ↑ steep axis: w for cart_value, mean(x²) ≈ 30,600 → shallow axis: w for page_views, values 0–12 0.005 × 61,000 ≈ 306: the miss grows 305× per step
Fig. 2.4c — Fig. 2.2 again, then stretched. With one feature the loss rings are nearly round and the walker of gradient_descent.py steps in to the centre. Add cart_value in raw dollars and the rings squeeze into a slot: the same η = 0.005 now crosses the slot in one stride and lands higher on the far wall, then higher again, until step 123 prints infinity. Growth per step (305× in the miss, 93,000× in the error) measured by rerunning watch_it_diverge.py.
  1. The bowl. One feature, minutes, gives loss rings that are only mildly oval. A stride of 0.005 times the slope is short compared with the width of every ring, so each step lands inside a smaller ring, and the steps shrink as the slope flattens. This is the picture from section 02, repeated here so that it sits next to its failure.
  2. The slot. The steepness of the bowl along a weight's axis grows with the mean of that feature's squared values. cart_value runs 0 to 300, so its mean(x²) is about 30,600; page_views runs 0 to 12. The rings are therefore squeezed hard along the cart_value axis and left wide along page_views: a canyon, not a bowl. Standardising the columns undoes the squeeze, and Fig. 2.4d draws that.
  3. The overshoot. The same η = 0.005 that was short in panel 1 is now 306 times the safe size along cart_value, because 0.005 × 61,000 ≈ 306. Each step therefore lands about 305 times farther from the bottom than it started, on the opposite wall. The miss grows 305×, the squared error 93,000×: from 1,167 at step 0 to 87 million at step 1, and the computer gives up with infinity at step 123.
Failure mode

The exact learning rate that trained section 03's model makes this one overflow to infinity in 123 steps, with numpy spraying RuntimeWarning: overflow on the way down. Why: the curvature of the error bowl along each weight's axis scales with that feature's squared values. For cart_value, mean(x²) ≈ 30,000 — so the bowl is a canyon roughly 1,000× steeper in that direction than along page_views. That canyon is marker 2 in Fig. 2.4c: Fig. 2.2's ellipses, stretched into a razor-thin slot.

A stride that's safe on the shallow axis overshoots the steep wall, lands higher, overshoots harder: marker 3 in Fig. 2.4c, where each step multiplies the miss by about 305 and the squared error by about 93,000. One standardization line — subtract the mean, divide by the standard deviation — makes every axis comparable, the canyon becomes a bowl (Fig. 2.4d, below), and the same η converges to the noise floor (5² = 25 ✓).

Even section 03 was secretly living on this edge: rerun gradient_descent.py with η = 0.01 and it detonates too, because exponential session times have mean(x²) = 128, putting the stability ceiling near η ≈ 0.008.

The lesson, and it's a big one: feature scaling isn't data-prep hygiene, it's a numerical stability requirement of gradient-based optimization. This is why StandardScaler appears in every serious sklearn pipeline, why neural nets normalize activations between layers (Module 04), and why "my loss went to NaN" is the most-asked question in every deep learning forum. You've now caused it and cured it in 35 lines.

"Scaling is a workaround. If the step was too big, why not just lower the learning rate and leave the data alone?"

— a performance engineer, looking at the overflow warnings

You can, and it stops the overflow. Divide eta by a thousand and the steep cart-value axis becomes safe. But the same eta now applies to the page-views axis, which was already shallow, and there every step is a thousand times too short. The hiker stops falling off the wall and starts shuffling. The scaled run reaches the noise floor in 420 steps; this one needs about 1.7 million: that is the shallow page-views axis of Fig. 2.4c, marker 2, crawled at a stride sized for the steep one.

The rule from section 06 is that the safe stride is set by the steepest direction and the speed is set by the shallowest. One learning rate cannot serve both when the curvatures differ by 1,000×. Standardization makes the curvatures comparable, so one stride is both safe and fast everywhere. That is why it is a numerical requirement and not tidiness. Fig. 2.4d, just below, draws the two columns before and after: the safe stride goes from 0.00003 to 1.0.

The downside you should know about: standardization needs a mean and a spread, and those must come from training rows only, or the test set leaks into the model. It also changes the units of every coefficient, so the +1.02 you will read in section 05 is per standard deviation of cart value, not per dollar. Section 05 solves the first problem with a Pipeline; the interview radar covers the second.

Here is what that one line does to the two columns.

1 BEFORE: BOTH COLUMNS IN RAW UNITS, SAME SCALE 0 100 200 300 0 150 300 page_views (units) → cart_value ($) ← this row: 7 views, $261 cart page_views 0–12: a sliver 12 units wide cart_value 0–300: the whole height page_views: mean 5.1, spread 2.2 cart_value: mean 151.5, spread 87.7 the loss bowl's steepness follows these units: 300 tall and 12 wide is the slot of Fig. 2.4c 2 AFTER: z = (x − mean) ÷ spread, BOTH COLUMNS −2 +2 +2 −2 scaled page_views → scaled cart_value ↑ 3 same row: (7 − 5.1) ÷ 2.2 = +0.9 (page_views) and (261 − 151.5) ÷ 87.7 = +1.2 (cart_value) now mean 0, spread 1 on both axes: a round cloud safe stride: before η < 0.00003, after η < 1.0
Fig. 2.4d — Standardising the two columns of watch_it_diverge.py. Left: both columns drawn in their raw units on the same scale; page_views is a sliver 12 units wide beside a cart_value range of 300. Right: after subtracting each column's mean and dividing by its spread, both run over about the same range and the loss bowl is round again. 30 of the 500 rows are drawn; the means (5.1 and 151.5), spreads (2.2 and 87.7) and safe strides were computed from all 500.
  1. Before. The loss bowl's steepness along each axis follows the units of that column. cart_value spans 300 units and page_views 12, so one axis of the data is 25 times longer than the other and the bowl is squeezed into the slot of Fig. 2.4c. The safe stride for that shape is η below 0.00003; the code used 0.005, about 150 times too big.
  2. After. Subtract the column's mean and divide by its spread: page_views becomes (x − 5.1) ÷ 2.2 and cart_value becomes (x − 151.5) ÷ 87.7. Both columns now have mean 0 and spread 1, the cloud is round, and the safe stride is η below 1.0, so 0.005 is comfortably small in every direction. This is the one-line fix in the code.
  3. One row. The highlighted visitor had 7 page views and a $261 cart; after scaling that is +0.9 spreads above the page-view mean and +1.2 spreads from the cart mean. The arithmetic is the same for every row and for every future row at serving time, which is why the mean and spread must be stored with the model. Section 05's StandardScaler stores exactly those two numbers per column, learned from training rows only.

Questions you might be asking now

The bubble and the two pictures above pack a lot into a few lines. If any of it did not land, open the question that matches yours. Every answer uses the same three CartGenius visitors, small enough to check with a pencil.

The three visitors every answer below uses. Their spend was made from spend = 4 × page views + 0.2 × cart value + 1, so the right answer is known exactly.
VisitorPage viewsCart valueSpend
A2$90$27
B4$110$39
C3$250$63
"Why not just lower the learning rate and leave the data alone?" What is that objection really saying, and why is it not enough?

A smaller learning rate does stop the explosion. It does not change the shape of the bowl. The stride that is now safe for cart value is far too short for page views. On the three visitors that costs 13,574 steps; scaling needs 2.

The performance engineer's argument has three steps, and each one is true on its own:

  1. The step was too big. The run overflowed because each stride landed higher on the far wall of the bowl.
  2. The learning rate sets the step. The update is w ← w − η × slope, so a smaller η (eta) makes every stride shorter.
  3. So shrink η and keep the data. No preprocessing code, and no statistics to store.

The missing fact: there is only one η for every direction at once. The same number multiplies the slope along cart value and the slope along page views. When those two directions curve very differently, no single number suits both.

Picture one hiker with one fixed stride, in a canyon with steep walls and a gentle floor. The stride must be short enough not to fly off the walls. That same short stride is then painfully small for walking along the floor.

The two fixes side by side, measured by scaling_by_hand.py (the three visitors) and lr_sweep.py (the 500 rows of watch_it_diverge.py)
Keep raw columns, shrink ηScale the columns, keep a normal η
Shape of the loss bowlA canyon: the steepest direction curves about 509,000 times more sharply than the flattestNearly round: the steepest and flattest directions differ by 1.26 times
Largest safe η (eta)0.0000360.9
Cart-value weightZigzags for about 10 steps, then parks near 0.27 while the others catch upWithin 2% of its true value at step 2
Page-view weightCrawls: 1% of the way after 100 steps, 13% after 1,000Within 2% of its true value at step 2
Steps until the average miss is under $1 (three visitors)13,574, at η = 0.000032, at η = 0.5
Steps to the noise floor (500 rows)About 276,000 at η = 0.00003; about 1.7 million at η = 0.0000051 at η = 0.5; 420 at section 03's η = 0.005
The priceNothing to store, but paid in training time on every runA mean and a spread per column, stored and applied to every future row

Here is the crawl, drawn. Each weight is shown as a share of the way to its true value.

RAW COLUMNS, η = 0.00003 % of the way to the true weight 0% 100% 200% 1 10 100 1,000 10,000 steps (each tick is 10× the last) true value (100%) 1 w for cart value: parks near 0.27 w for page views crawls: 13% of the way at step 1,000 2 average miss under $1 only at step 13,574 the stride is sized for the steep cart-value wall SCALED COLUMNS, η = 0.5 0% 100% 200% 1 10 100 1,000 10,000 steps, same scale as the left w for page views: 150% at step 1 w for cart value: 103% at step 1 3 both within 2% of the true weight at step 2 steps 3 to 10,000: nothing left to learn average miss under $1 at step 2 a round bowl: one stride fits every direction
Fig. 2.4e — The three visitors trained two ways, with each weight drawn as a share of the way to its true value. Left: raw columns at the largest round-number safe learning rate. Right: scaled columns at η = 0.5. Both panels use the same step axis, so the empty right-hand panel is the point. Values from rerunning scaling_by_hand.py.
  1. The cart-value weight. Its direction is the steep wall. The first stride takes it to 0.45, more than double the true 0.2. It zigzags, then parks near 0.27 by step 10. It is not at 0.2 yet because page views and b are still wrong, and it is compensating for them.
  2. The page-view weight. Its direction is the gentle floor. The stride that is safe for cart value moves it 1% of the way in 100 steps, 13% in 1,000 and 74% in 10,000. The average miss drops under $1 only at step 13,574. This is the shuffle the bubble described.
  3. Scaled columns. Both directions now curve about the same, so η = 0.5 is safe for both. Step 1 overshoots page views to 150%. Step 2 lands both weights within 2% of their true values: 3.27 and 14.24 per typical distance, which are 4 and 0.2 in dollars. The average miss is already 20 cents.

On three rows, 13,574 steps pass in a blink. On CartGenius's real data every step reads every row, so the same ratio means 6,787 times the work, on every training run, forever. Scaling is paid once per row, and it is one line of code.

Shrinking η changes the length of the stride. Scaling changes the shape of the ground. Only the ground fix makes one stride right in every direction.

What are the "mean" and the "standard deviation" in the scaling formula, and how do I work them out by hand?

The mean is the column's average. The standard deviation is the typical distance of a value from that average. Scaling rewrites every value as "this many typical distances above or below the average".

The formula from Fig. 2.4d is: scaled value = (original value − mean) ÷ standard deviation. It has three ingredients:

  • Original value. The number as it arrived: visitor A's 2 page views, or A's $90 cart.
  • Mean. The average of the whole column. It is worked out once, from the training rows.
  • Standard deviation. How far a value typically sits from that average, written σ (sigma). It is also worked out once, from the training rows.

Here are the five steps for the page-views column, 2, 4 and 3.

  1. Find the average. (2 + 4 + 3) ÷ 3 = 3.0.
  2. Measure each distance from it. A: 2 − 3 = −1. B: 4 − 3 = +1. C: 3 − 3 = 0.
  3. Square each distance. (−1)² = 1, (+1)² = 1, 0² = 0. Without squaring, −1 and +1 add up to 0, as if nobody were away from the average.
  4. Average the squares. (1 + 1 + 0) ÷ 3 = 0.667. This middle number is called the variance, and it is in "squared page views".
  5. Take the square root. √0.667 = 0.816. The root undoes the squaring and puts the answer back in page views. That is the standard deviation, σ (sigma).

Now plug each visitor in. A: (2 − 3) ÷ 0.816 = −1.22. B: (4 − 3) ÷ 0.816 = +1.22. C: (3 − 3) ÷ 0.816 = 0.

The same five steps for the cart-value column, $90, $110 and $250
StepWorkingResult
A · average(90 + 110 + 250) ÷ 3$150
B · distances90 − 150, 110 − 150, 250 − 150−60, −40, +100
C · squares(−60)², (−40)², 100²3,600, 1,600, 10,000
D · variance(3,600 + 1,600 + 10,000) ÷ 35,066.7
E · standard deviation√5,066.7$71.2
Scaled values−60 ÷ 71.2, −40 ÷ 71.2, +100 ÷ 71.2−0.84, −0.56, +1.40
1 PAGE VIEWS: MEAN 3, TYPICAL DISTANCE 0.816 1 5 mean 3 A: −1 B: +1 A: 2 B: 4 C: 3, on the mean one typical distance either side of the mean: 0.816 2 CART VALUE: MEAN $150, TYPICAL DISTANCE $71.2 $50 $300 mean $150 A: −60 C: +100 B: −40 A: $90 B: $110 C: $250 one typical distance either side of the mean: $71.2 3 AFTER SCALING: BOTH COLUMNS ON ONE RULER page views cart value A −1.22 C 0 B +1.22 A −0.84 B −0.56 C +1.40 −2 −1 0 +1 +2 0 is each column's own average; 1 is one typical distance from it
Fig. 2.4f — Scaling the three visitors by hand. Row 1: page views, each visitor's distance from the average of 3, and the typical distance of 0.816. Row 2: cart value, average $150, typical distance $71.2. Row 3: both columns after each distance is divided by its column's typical distance. Values from rerunning scaling_by_hand.py.
  1. Page views. The dots sit at 2, 4 and 3, and the average is 3. A is one page view below it, B one above, C exactly on it. Squared, those distances are 1, 1 and 0. Their average is 0.667, and its square root, 0.816, is the bracket.
  2. Cart value. The same five steps with bigger numbers: distances −60, −40 and +100, squares 3,600, 1,600 and 10,000, average 5,066.7, square root $71.2. C's $250 cart sits far from the other two, and that one far value makes most of the spread.
  3. One ruler. Each distance divided by its column's typical distance. Page views become −1.22, +1.22 and 0; carts become −0.84, −0.56 and +1.40. A 1 now means the same thing in both columns: one typical distance from that column's own average.

Two practical notes. First, StandardScaler and numpy's .std() divide by the count, 3, as step D does. pandas' .std() divides by 2 unless you pass ddof=0, so a scaler hand-written in pandas gives slightly different numbers.

Second, the mean and standard deviation are learned from the training rows only, and then stored. The scaler in section 05 keeps five of each, one pair per numeric column (marker 2 in Fig. 2.5b). If you want the idea built from scratch, Module 01b's café example starts from a coffee that is an 8 on most days.

Scaled value = (value − column average) ÷ typical distance from that average. Both numbers come from the training rows, once, and are stored with the model.

Show me one gradient step on those three visitors, before and after scaling.

Raw columns: the cart-value slope is 56 times the page-view slope, and one step at η = 0.005 predicts $6,744 for visitor A, who spent $27. Scaled columns: the slopes are 9.80 and 29.22, and one step at η = 0.5 cuts the error from 2,073 to 2.95.

Start where section 03 started. Every weight is 0, so every prediction is $0. The misses are 0 − 27 = −27, 0 − 39 = −39 and 0 − 63 = −63.

The mean squared error is (729 + 1,521 + 3,969) ÷ 3 = 2,073. That starting point is the same for raw and scaled columns, because a prediction of $0 does not care about units.

Now the slopes, with section 03's formula: slope = (2 ÷ n) × the sum of (miss × feature value), where n = 3 is the number of visitors.

The three starting slopes, raw and scaled. The scaled column is worked with the unrounded scaled values from Fig. 2.4f.
Slope forRaw columnsScaled columns
Page views(2 ÷ 3) × (−27 × 2 − 39 × 4 − 63 × 3) = (2 ÷ 3) × (−399) = −266(2 ÷ 3) × (−27 × −1.22 − 39 × 1.22 − 63 × 0) = −9.80
Cart value(2 ÷ 3) × (−27 × 90 − 39 × 110 − 63 × 250) = (2 ÷ 3) × (−22,470) = −14,980(2 ÷ 3) × (−27 × −0.84 − 39 × −0.56 − 63 × 1.40) = −29.22
b(2 ÷ 3) × (−27 − 39 − 63) = −86−86: b multiplies no feature, so scaling does not touch it
Cart slope ÷ page-view slope56 times3 times

Why the raw slopes differ by 56 times: every miss is multiplied by the feature value, and cart values are about 50 times bigger than page views. The slope is huge because the unit is small, not because cart value matters more.

Why the scaled slopes differ by only 3 times: both columns now use one ruler, so a slope reflects how much its column explains. Cart value earns the bigger one because it really does move spend more: 14.24 per typical distance, against 3.27 for page views.

1 RAW COLUMNS: ONE STEP AT η = 0.005 starting slopes, bars to scale page views −266 cart value −14,980: 56× bigger new weights: page views 0 − 0.005 × (−266) = 1.33 cart value 0 − 0.005 × (−14,980) = 74.9 visitor A's new prediction: 2 1.33 × 2 + 74.9 × 90 + 0.43 = $6,744 true spend: $27 MSE: 2,073 → 153.6 million → overflow by step 6 3 SCALED COLUMNS: ONE STEP AT η = 0.5 starting slopes, own scale (513× shorter) page views −9.80 cart value −29.22: 3× bigger new weights: page views 0 − 0.5 × (−9.80) = 4.90 cart value 0 − 0.5 × (−29.22) = 14.61; b = 43 visitor A's new prediction: 4.90 × (−1.22) + 14.61 × (−0.84) + 43 ≈ $24.7 true spend: $27 MSE: 2,073 → 2.95 → 0.04 at step 2 same start, same formula; only the units the slopes are measured in changed
Fig. 2.4g — One gradient step on the three visitors. Left: raw columns, where the cart-value slope dwarfs the page-view slope and one ordinary step flies off the wall. Right: scaled columns, where the two slopes are comparable and one step lands near the bottom. Each panel's bars use their own scale. Values from rerunning scaling_by_hand.py.
  1. The lopsided slopes. Every miss is multiplied by the feature value before it is added up. Carts are measured in dollars, in the hundreds; page views in single digits. So the cart-value slope, −14,980, is 56 times the page-view slope, −266, before the model has learned anything.
  2. The step off the wall. η = 0.005 is harmless for the page-view weight: it moves to 1.33. The same η moves the cart-value weight to 74.9, which is 374 times the true 0.2. Visitor A's $90 cart alone now contributes $6,741, and the error jumps from 2,073 to 153.6 million.
  3. The balanced slopes. After scaling, −9.80 and −29.22 are of the same size. A far bigger η, 0.5, now moves both weights near their true values in one step, and b jumps straight to 43, the average spend. Visitor A is predicted at about $24.7 against a true $27, and step 2 brings the error to 0.04.

Look at the right panel once more. Step 1 overshoots the page-view weight to 4.90 against a true 3.27, and step 2 pulls it back to 3.22. That small zigzag is harmless, because the bowl is round.

Scaling also does not change the answer. The scaled model settles at 3.27 per typical distance of page views, 14.24 per typical distance of cart value, and b = 43. Divide each weight by its column's typical distance: 3.27 ÷ 0.816 = $4.00 per page view, and 14.24 ÷ 71.2 = $0.20 per cart dollar.

Those are exactly the 4 and 0.2 the spend was made from. The intercept comes back too: 43 − 4 × 3 − 0.2 × 150 = 1. Scaling changed the path to the bottom of the bowl, not the bottom.

Raw slopes are sized by each column's units. Scaled slopes are sized by how much each column matters. Only the second is a fair basis for one shared step size.

So how does anyone choose the learning rate? Is there a formula for the right one?

There is a ceiling you can compute: η must stay below 2 ÷ the steepest bend of the loss bowl. In practice nobody computes it. People try a handful of values, each three to ten times smaller than the last, and keep the largest one whose loss falls smoothly.

The ceiling is the stability rule from section 06. On the 500 scaled rows of watch_it_diverge.py every direction bends by about 2, so the ceiling is about 1 (0.998, measured). On the same rows unscaled, the cart-value direction bends so sharply that the ceiling is 0.0000326.

A real model has thousands or millions of weights, and nobody works out its bends. Instead they run a short sweep: the same training, several times, with different learning rates. Here is one, on the scaled columns, from lr_sweep.py.

A learning-rate sweep on the scaled columns of watch_it_diverge.py. Every run starts at MSE 1,167; the noise floor is 25.03.
η (eta)What the loss didSteps to reach the floor
1.5Climbed from the first step: 4,589, then 18,276Never: blew up by step 10
1.1Climbed more slowly: 1,668, 2,390, then 43,604 at step 10Never: blew up by step 38
0.9Fell, zigzagging across the valley on the way down19
0.5Dropped straight onto the floor1
0.3Fell fast: 208, 54, 305
0.05Fell steadily40
0.005, section 03's choiceFell slowly: still 958 at step 10420
0.0005Barely moved: 1,144 at step 10, 959 at step 100About 4,200

There are three loss-curve shapes to learn to recognise, and Fig. 2.4h draws five of the runs:

  • The loss climbs. η is too big. Stop the run; nothing good happens later.
  • The loss falls, then flattens within tens of steps. η is about right.
  • The loss slides down a long, gentle slope. η is safe but too small. You pay for it in training time.
FIVE LEARNING RATES ON THE SAME SCALED 500 ROWS MSE 0 1,000 2,000 1 10 100 1,000 4,000 steps, log scale (each tick is 10× the last) 1.1 0.5 0.05 0.005 0.0005 1 η = 1.1: climbs from step 1, overflow by step 38 η = 0.5: on the floor after 1 step 2 η = 0.05: on the floor after 40 steps η = 0.005: 420 steps (section 03 used it) 3 η = 0.0005: about 4,200 steps, safe but slow every run starts at MSE 1,167; every run that works ends on the noise floor, MSE 25
Fig. 2.4h — A learning-rate sweep drawn as loss curves. Too big climbs; about right drops and flattens within tens of steps; too small slides down the same slope ten times later for every ten-times-smaller η. Step 0, where every run is at 1,167, cannot sit on a log axis, so the curves start at step 1. Values from rerunning lr_sweep.py.
  1. Too big. At η = 1.1 each stride is longer than the valley is wide, so each landing is higher than the last. The loss is 1,668 after one step and 2,390 after two, already off this chart. When the loss climbs in the first handful of steps, stop the run and divide η by three.
  2. About right. At η = 0.05 the loss drops by more than half in 5 steps and sits on the floor by step 40. η = 0.5 is even faster here, one step, because on these almost uncorrelated columns every direction bends by almost exactly the same amount. Real data is rarely that neat.
  3. Too small. η = 0.005 and η = 0.0005 draw the same curve, the second one ten times further right. Nothing is wrong with the answer they reach; you simply wait ten times longer for it. Section 03's 0.005 was safe, and about 100 times slower than it needed to be.

The working rule: keep the largest η whose loss still falls smoothly, then go one notch smaller for safety. On this data that is 0.5 or 0.3.

A popular rule of thumb says "use 0.01 or 0.001". That number means nothing until the columns are scaled. On these raw columns even 0.0001 blows up, because the ceiling is 0.0000326.

Two honest limits. First, the clean ceiling formula only holds for a single bowl-shaped loss like squared error. The neural networks of Module 04 have no single bowl, so there the sweep is the method, not the formula.

Second, section 05 never asks you for a learning rate at all. LogisticRegression's default solver, lbfgs, chooses the length of every step itself: it tries a step, and shortens it if the loss did not fall enough.

Try a few values, each three to ten times apart. Throw out any whose loss climbs. Keep the largest one that falls smoothly, and scale the columns first so that a sensible value exists.

Wait. Is the scaled data the same thing as the loss function?

No. Scaling rewrites the input columns once, before training starts. The loss function is a score, recomputed at every step from the predictions. Scaling decides the shape of the bowl; the loss is the height at any point on it.

The two get confused because this section fixes the loss bowl by changing the data. They are still different parts of the machine, used at different times, with different inputs and outputs.

Scaling and the loss function, side by side
Scaling (StandardScaler)Loss function (mean squared error)
What it isArithmetic on each input column: (value − mean) ÷ spreadA formula that turns the current predictions into one number: how wrong they are
When it runsLearned once from the training rows, then applied to every row, including each live visitorAt every step of training: 4,001 times in section 03's loop
What goes inOne column of raw valuesThe predictions and the true answers
What comes outThe same column rewritten, one number per rowOne number for the whole dataset
On the three visitorsPage views 2, 4, 3 become −1.22, +1.22, 0Misses −27, −39, −63 give (729 + 1,521 + 3,969) ÷ 3 = 2,073
In the hiker storyRedrawing the map so that north–south and east–west use the same unitThe altimeter reading at the hiker's current spot
In this module's codeX_std = (X_raw - X_raw.mean(axis=0)) / X_raw.std(axis=0) in watch_it_diverge.py; StandardScaler() in section 05np.mean(err**2) in gradient_descent.py; log-loss, computed inside LogisticRegression

Where each one sits in training is easiest to see as a picture. Scaling happens before the loop. The loss is one of the four things that happen inside it.

raw columns views 2, 4, 3 cart 90, 110, 250 1 StandardScaler runs once, first (x − mean) ÷ spread means 3 and 150 spreads 0.816, 71.2 scaled columns −1.22, +1.22, 0 −0.84, −0.56, +1.40 predict $0, $0, $0 2 loss (MSE) 2,073 slopes −9.80, −29.22 step w ← w − η × slope repeat every step the training loop: thousands of times 3 same start either way: predictions $0, loss 2,073 same lowest loss either way: 0, the same line scaling changes only how steep the ground is scaling sits outside the loop and runs once; the loss sits inside and runs every step
Fig. 2.4i — Where scaling and the loss function live. Scaling is a one-time rewrite of the inputs on the way in. The loss is one of four stations inside the training loop, shown here at step 0 for the three scaled visitors. Values from rerunning scaling_by_hand.py.
  1. Scaling. The scaler reads the training columns once and stores two numbers per column: means 3 and 150, spreads 0.816 and 71.2. Every row that ever reaches the model, in training or in production, is rewritten with those same stored numbers. It never looks at a prediction.
  2. The loss. Inside the loop, the loss compares the current predictions with the true spend and returns one number: 2,073 at step 0. The slopes are worked out from it, the weights step downhill, and the loss is computed again on the next lap. It never changes an input column.
  3. What scaling did to the loss. With every weight at 0, every prediction is $0 whether the columns are scaled or not, so both runs start at 2,073. The same line fits both, so both have a lowest loss of 0. Scaling changed only how steep the ground is between those two heights, which is the canyon and the bowl of Fig. 2.4c.

So the fireside chat below is between the loss function and the optimizer, and scaling is not a speaker in it. Scaling is the groundwork both of them rely on: it is why the optimizer's single step size works.

Scaling prepares the inputs, once. The loss scores the predictions, every step. One shapes the bowl; the other reads the height.

Before the two of them argue, look at what each one actually does. The left half of the picture is the loss function's whole job. The right half is the optimizer's. Every line in the chat below points at a number in this picture.

1 THE LOSS FUNCTION IS A RULER session minutes → spend ($) line A line B gap 4 gap 1 gap 2 gap 6 loss(A) = (4² + 1² + 2² + 6²) ÷ 4 = 14.25 loss(B) = (1² + 1² + 1² + 0²) ÷ 4 = 0.75 ← lower: B wins one number per line. The ruler scores; it never moves a line. 2 THE OPTIMIZER WALKS DOWNHILL the line's slope w → (every w is a different line) loss A loss 14.25 step 1 step 2 B: loss 0.75 flat → stop 3 A STEP TOO BIG FLIES ACROSS THE VALLEY the line's slope w → loss A jump 1: lands higher jump 2: higher again → loss ∞ bottom: never reached
Fig. 2.2b — The two jobs, side by side. The loss function scores any line with one number (panel 1). The optimizer changes the line one step downhill at a time until the score stops falling (panel 2), unless its steps are too big (panel 3).
  1. The ruler. Take a candidate line. Measure the vertical gap from every point to it. Square each gap so that a gap of 6 hurts far more than a gap of 1, and so that gaps above and below the line both count as positive. Average them. That single number is the loss of that line. Line A scores 14.25, line B scores 0.75, so B is better. Without this number, "better line" has no meaning at all.
  2. The walker. Every possible line has a loss, so you can draw loss against the line's slope, and it forms a bowl. The optimizer stands on the bowl at line A, feels which way is downhill, and takes one step. Then another. Line A becomes line B. When the ground is flat, it stops. It never decides what "better" means; it only walks toward whatever the ruler calls lower.
  3. The overshoot. Same bowl, bottom-right panel. If the step is too big, the walker jumps clean across the valley and lands on the far wall, higher than it started. The next step is bigger still. The loss grows instead of shrinking, and after enough steps the computer prints infinity. Section 04 made this happen on purpose. The cure was not a different ruler; it was a smaller step, or reshaping the bowl so one step size is safe in every direction.
Fireside chat

Tonight's talk: The Loss Function and The Optimizer argue over the question, "Who's more important?"

The Loss Function
The Optimizer

Look at the left half of Fig. 2.2b. Two lines, four points. Which line is better? You cannot answer until someone defines "better". I am that definition: square each gap, average them, one number per line. Line A scores 14.25. Line B scores 0.75. Before I exist there is no wrong line. There are only lines.

the loss function is the ruler. It turns a whole line into one score, and lower means better. Without a ruler, the word "wrong" has no meaning.

A ruler does not move anything. Look at the right half. You are the bowl. I am the dot that walks down it. Each step, I ask which way is downhill and I go that way. Two steps, and line A has become line B. Everyone else on this page describes. I act.

the optimizer is the only part that changes the line. It reads the slope of the loss and nudges the weights downhill, over and over, until the slope is flat.

You also fell off the bowl in section 04. Same ruler, same points, but your step was too big. Marker 3: from line A you jumped clean across the valley and landed higher than you started. Then higher again. The score went to infinity, and I did not put a single wrong number on that page. You did.

a step that is too large overshoots the bottom and lands on the far wall. Each overshoot is worse than the last, so the loss grows instead of shrinking. That is what "diverged" means.

Because the bowl you gave me was not a bowl. It was a canyon, a thousand times steeper in one direction than in the other. A step that is safe on the gentle side is a leap on the steep side. Standardising the features reshaped you into a round bowl. Nobody touched me.

when one feature has much bigger values than another, the loss surface is stretched into a canyon. No single step size suits both directions. Scaling the features makes the surface round, so one step size works everywhere.

Now the case where I am wrong and you are perfect. Suppose I measure the wrong thing: squared dollars of spend, when the question was "will they buy?". You will walk downhill flawlessly and arrive at a perfect answer to the wrong question. Optimise the wrong ruler and you get a flawless wrong line.

the optimizer cannot tell whether the loss measures the right thing. If the ruler is wrong, the result is confidently wrong, and nothing in the walk will reveal it.

And the right ruler with the wrong step size gives you infinity, which nobody can read. A perfect definition of good that no one can reach is a poem.

both parts have to be right. A good loss with a bad optimizer never arrives; a good optimizer with a bad loss arrives at the wrong place.

The leash is mine as well. Regularisation is not a setting on you. It is an extra term I add to the score: a penalty for big weights. Add it and the bowl changes shape, and you walk down whatever bowl I draw. You have never had an opinion of your own.

regularisation means adding a penalty for large weights to the loss. That reshapes the bowl, so the optimizer's path changes even though the optimizer itself did not.

Whose knob is C, then? In scikit-learn it is one over your penalty, upside down, and people spend afternoons turning it the wrong way. That is your side of the house. And for a plain squared loss with a squared penalty, I am not even needed. The bottom of that bowl has an algebra answer, and scikit-learn finds it in one call.

C is the inverse of the penalty strength, so a bigger C means less regularisation. For ridge regression the best weights can be computed directly, with no walking at all.

Try the algebra answer with a billion weights.

direct formulas stop being practical when there are enormous numbers of weights. Then walking downhill is the only way to find the bottom.

That is my point. In Module 04 there will be a billion weights and I will still be the only thing moving them. In logistic regression scikit-learn calls me lbfgs and the reader never sees me, but I am there. You are still one number.

every model that learns has an optimizer inside it, even when the library hides it. lbfgs is the one scikit-learn uses by default for logistic regression.

One number is all anyone ever reads. We'll revisit this the day the loss prints NaN and they page us both.

neither wins. A loss of NaN means the walk blew up, and you cannot tell whose fault it was without looking at both.

05 · The industry toolPipelines: How Models Survive Contact With Production

You have built the mechanism and broken it once. Production adds what the toy loop ignored: missing values, text columns, the scaling fix applied without leaking test data, and a threshold Elena can defend in a meeting. scikit-learn's Pipeline packages all of it as one object, and that object is what ships.

Your from-scratch loop taught the mechanism. Production adds requirements the loop doesn't cover: missing values (users close tabs mid-session, tracking pixels fail), categorical features (referral source, device type), unseen categories at inference time, and — most treacherous — data leakage: if you compute imputation medians or scaling statistics on the full dataset before splitting, your test set has quietly contaminated training, and your offline metrics flatter you. The industry answer is scikit-learn's Pipeline + ColumnTransformer pattern: one object owns preprocessing and model, learns its statistics only inside whatever data it's fit on (so cross-validation stays honest, fold by fold), and serializes as a single deployable artifact.

1 · Raw visitor logs numeric + categorical columns, 5% NaNs raw DataFrame 2 · ColumnTransformer numeric → impute(median) → scale · categorical → one-hot clean feature matrix 3 · Model + cross-validation LogisticRegression / Ridge · 5-fold stratified CV fitted pipeline 4 · Evaluation on untouched holdout ROC-AUC · confusion matrix · MAE · R² metrics pass → ship 5 · Real-time JSON inference handler visitor payload → probability → marketing action
Fig. 2.5 — One Pipeline object owns preprocessing and model. Every statistic it learns, it learns inside the training data it was given — no leakage — and inference applies the identical transform automatically.

Now the same five stages a second time, with this module's actual files and calls in the boxes. The middle column is what sections 03 and 04 gave you; the next column is what cartgenius_pipeline.py replaces it with. If a stage in Fig. 2.5 feels abstract, find its row here.

Fig. 2.5 again, concretely: each stage as it exists in this module's code
StageIn the from-scratch loop (sections 03–04)In cartgenius_pipeline.py (this section)What flows out
Raw dataminutes = rng.exponential(...): one numpy column, no gapsgenerate_ecommerce_data(): a DataFrame with seven feature columns, two of them 5% NaN, two of them textA table of 3,000 rows
SplitNone. The loop trained and scored on the same 400 rowstrain_test_split(X, y, test_size=0.20, stratify=y)2,400 rows to learn from and 600 the model never sees
ImputeNone: the fake data had no missing valuesSimpleImputer(strategy="median"), first step of the numeric branchNo NaNs; medians learned from training rows only
Scale(X_raw - X_raw.mean(axis=0)) / X_raw.std(axis=0) in watch_it_diverge.py, by handStandardScaler(), second step of the numeric branchEvery numeric column with mean 0 and spread 1
Encode categoriesNone: numeric features onlyOneHotEncoder(handle_unknown="ignore"), the categorical branchOne 0/1 column per referral source and device type; an unseen value becomes all zeros
FitThe 4,001-step loop: w -= eta * grad_wpipeline.fit(X_train, y_train) with LogisticRegression(C=1.0, max_iter=1000) or Ridge(alpha=1.0)One object holding every statistic and every weight
ValidateWatch the printed MSE stop movingcross_val_score(..., cv=StratifiedKFold(5), scoring="roc_auc")Five AUC numbers, reported as mean ± spread
Score the holdoutNonepredict_proba(X_test)[:, 1], then roc_auc_score and confusion_matrixAn AUC of 0.80 and a 2 × 2 table of counts
Explainprint(w, b): two numbers.coef_[0] matched to get_feature_names_out()A signed weight per feature, sorted by size
ServeNonepredict_customer_value(visitor_json, clf, reg)JSON: buy probability, predicted spend, marketing action

Split before you touch anything.

Fit on the training rows only.

Score on what it never saw.

Ship the one object that did all three.

Split: the train_test_split row of the table above cuts the 3,000 rows into 2,400 and 600 before any statistic is computed. Fit: stages 2 and 3 of Fig. 2.5, where the medians, means, spreads, category lists and weights are all written from the 2,400. Score: stage 4, the 600 rows the pipeline never saw. One object: the box-in-box of Fig. 2.5b, the single thing joblib ships.

Before the data engineer objects, open the object. Fig. 2.5b is the fitted pipeline with every number fit() wrote into it.

pipeline: the ONE object that fit() filled in and predict_proba() replays fit(X_train, y_train): 2,400 rows write every number below predict_proba(row): replays them, learns nothing preprocessor: ColumnTransformer num: PageViews, SessionMinutes, CartValue, DaysSince, IsReturning 1 SimpleImputer(median) learned 5 medians: PageViews 5 · SessionMinutes 5.5 · CartValue 147 DaysSinceLastVisit 44 · IsReturning 0 2 StandardScaler learned 5 means and 5 spreads: CartValue 148.75 ± 83.75 · SessionMinutes 7.79 ± 7.73 PageViews 5.01 ± 2.23 · DaysSince 44.15 ± 25.86 IsReturning 0.39 ± 0.49 cat: ReferralSource, DeviceType 3 OneHotEncoder learned two lists: Affiliate, Direct, Email, Facebook, Google (5 columns) Desktop, Mobile, Tablet (3 columns) an unseen value → all zeros because handle_unknown="ignore" 13 clean numbers per row: 5 scaled + 8 one-hot 4 classifier: LogisticRegression(C=1.0) learned 13 weights and 1 intercept (−0.43): CartValue +1.02 · DaysSinceLastVisit −0.58 · SessionMinutes +0.58 · Email +0.43 · IsReturning +0.41 PageViews +0.24 · Direct −0.30 · Mobile −0.26 · Google −0.21 · Affiliate −0.17 · Facebook −0.14 Tablet −0.08 · Desktop −0.06 · then z = intercept + Σ weight × scaled value, and σ(z) = probability joblib.dump(pipeline) ships all of it as one file; nothing here is recomputed at serving time
Fig. 2.5b — The fitted Pipeline, opened up. Every number inside was written once by fit() on the 2,400 training rows and is replayed unchanged by predict_proba(); nothing is recomputed from the rows being scored. Values read off the fitted object by rerunning cartgenius_pipeline.py.
  1. The imputer. For each of the five numeric columns it stored the training median: 147 for CartValue, 5.5 for SessionMinutes. A blank CartValue in a new visitor's JSON becomes 147, the same number in training, in cross-validation and in serving. Compute that median on the whole frame first and the 600 holdout rows have already leaked into it.
  2. The scaler. It stored a mean and a spread per column and applies (x − mean) ÷ spread, the fix from section 04, using the stored numbers and never the new row's. That is why the weight on CartValue in marker 4 is per 83.75 dollars of cart, one spread, and not per dollar.
  3. The encoder. It stored the five referral sources and three device types seen in training and makes one 0/1 column for each: eight columns. A source it never saw, say "TikTok", becomes all zeros instead of a crash, because of handle_unknown="ignore".
  4. The classifier. Thirteen weights and an intercept, learned from the 13 columns the two branches produce. A visitor's score is the intercept plus each weight times its scaled value, and the sigmoid turns that score into the probability. Fig. 2.5c does that sum for one real visitor.

"I would rather clean the frame in pandas, where I can see it. Why does preprocessing have to live inside the model object?"

— a data engineer, who has been burned by black boxes

Cleaning in pandas first works until the first cross-validation. Fill the medians on the whole frame, then split, and every fold's test rows have already told the imputer something about themselves. The scores can come out too good, and nothing warns you. Inside the pipeline, fit() sees only the rows it was handed, so each fold learns its own medians and the scored rows stay clean. Those medians are marker 1 in Fig. 2.5b: $147 for CartValue, 5.5 for SessionMinutes, written from the 2,400 training rows and nowhere else.

The second win shows up at serving time. The JSON handler in cartgenius_pipeline.py does no preprocessing at all. It builds a one-row frame and calls predict_proba; the pipeline replays the exact medians, means and category lists it learned in training (markers 1, 2 and 3 in Fig. 2.5b). Preprocess in pandas and you maintain that logic twice, once for training and once for serving, and the two copies drift apart.

The downside is real. A pipeline is harder to inspect: the transformed matrix has no column names until you call get_feature_names_out, the inner steps hide behind named_steps, and a bug in the numeric branch shows up as a wrong score rather than a wrong column. Keep pandas for looking. Move every transform that learns a statistic into the pipeline.

Questions you might be asking now

The bubble above leans on three ideas this page has not yet slowed down for: a test set, leakage, and what really happens to a messy row. Each answer uses this section's own 3,000 visitors and the same 80/20 split, and every number comes from rerunning split_and_leak.py or messy_visitor.py.

Why hold back a test set at all? Why not train and score on all 3,000 rows?

Because a score on rows the model has already studied measures memory, not skill. The 600 held-back rows stand in for next week's visitors, whom no model has seen.

Picture a teacher who hands out 50 practice questions with the answer key, then sets the same 50 questions as the final exam. A perfect score proves the student remembers 50 answers. It says nothing about question 51.

A model can do exactly the same thing, and it is better at remembering than any student. So the data is cut in two before anything is learned from it.

The exam, translated into this section's code
In the examIn CartGenius
Practice questions with the answer keyThe 2,400 training visitors, with their Purchased column
Studyingpipeline.fit(X_train, y_train)
The sealed final exam, with new questionsThe 600 held-back visitors
Marking the examroc_auc_score(y_test, ...) on the predictions for those 600
Question 51Next week's real visitor

The split does more than give one honest number. Compare the score on studied rows with the score on new rows, and it tells you what kind of wrong a model is. Here are three models on the same split:

Three models, one split, measured by split_and_leak.py. Accuracy counts right answers at a 0.5 cutoff; AUC scores the ranking, where 0.5 is a coin flip.
ModelTrain accuracyTest accuracyTrain AUCTest AUCWhat it means
Logistic regression, this section's pipeline0.7540.7420.8100.802Healthy: the two scores agree
Decision tree with no depth limit1.0000.6431.0000.616Overfitting: it memorised the practice set
Logistic regression on DeviceType only0.6280.6280.5190.523Underfitting: it learned almost nothing
ONE SPLIT, THREE MODELS: STUDIED ROWS vs NEW ROWS training rows: 2,400, studied held-back rows: 600, new AUC 0 0.5 1.0 0.810 0.802 1.000 0.616 0.519 0.523 coin flip 1 logistic regression healthy: 0.810 vs 0.802 2 tree, no depth limit memorised: 1.000 vs 0.616 3 DeviceType only learned nothing: 0.52, 0.52
Fig. 2.5i — What the held-back rows reveal. Each pair of bars is one model's AUC on the rows it studied (dashed) and on rows it never saw (solid). The gap between the two bars, and their height against the coin-flip line, is the whole diagnosis. Values from rerunning split_and_leak.py.
  1. Healthy. 0.810 on studied rows, 0.802 on new ones. The model learned rules that carry over to people it has not met. This is the pipeline from this section, and the small gap is why its holdout AUC can be trusted as a forecast for next week.
  2. Memorised. The tree grew 561 leaves for 2,400 rows, about four visitors per leaf, so it can recite every practice answer: 1.000. On new visitors it scores 0.616, far below the plain model. Without the test set, this would look like the best model on the page.
  3. Learned nothing. DeviceType alone barely separates buyers from non-buyers, so both bars sit near the coin-flip line. Its accuracy, 0.628 on both halves, is exactly what answering "nobody buys" scores. Equal and low on both halves is the signature of a model too simple for the problem.

Read the three rows as a rule you can apply to any model. Train and test close together and both good: healthy. Train far above test: overfitting, so shorten the leash of section 02 or give the model less freedom. Both low and equal: underfitting, so give it better features or more flexibility.

Module 03 grows decision trees properly, with limits that stop exactly the memorising in marker 2.

A score on studied rows measures memory. Only rows the model never saw measure skill, and the gap between the two scores names the problem.

What does data leakage actually look like, with real numbers?

Leakage is any information the model could not have at prediction time reaching it during training. Fitting the imputer on all 3,000 rows is the textbook case; here it moved the median by 88 cents and the score not at all. A column recorded after the purchase is the dangerous case: a perfect, useless AUC of 1.000.

Leaks come from two places, and they behave very differently:

  • From the test rows. Statistics that clean the training data were computed with the held-back rows included. The exam helped write the answer key.
  • From the future. A feature is filled in only after the thing you are predicting has happened. The model learns to read the answer instead of the signs.

Leak A: the imputer and scaler fitted before the split

The mistake is one line in the wrong place: make_preprocessor().fit(X) on all 3,000 rows, then split. The 600 test rows now help set the median that fills the blanks and the mean and spread that scale the training rows.

Measured on this data, the CartValue median moves from $147.00 to $147.88, the mean from $148.75 to $149.22, and the spread from $83.75 to $84.18. The holdout AUC is 0.8018 both ways, identical to four decimal places.

So on 3,000 well-behaved rows this leak is too small to see. It is still a bug. The test set's only job is to be a dress rehearsal for production, where next week's rows do not exist yet. Once test rows have shaped the preprocessing, the rehearsal no longer matches the show, and nothing tells you by how much.

Leak B: a column from the future

SpendAmount is written when a visitor pays. Add it as a feature for "will they buy?" and the model learns one rule: spend above $0 means bought. The held-back rows score an accuracy of 0.997 and an AUC of 1.000.

In production the model has to decide whom to email before anyone has paid. At that moment SpendAmount is empty for every visitor, so the one column the model relies on tells it nothing.

The test set cannot catch this leak, because the leaked column sits in the test rows too. Only one question catches it: would I really have this number at the moment of the decision?

Three versions of the buyer model, measured by split_and_leak.py
VersionWhat reached training that should not haveHoldout AUCIn production
The pipeline, fitted on the training rowsNothing0.8018About 0.80, as tested
Leak A: imputer and scaler fitted on all 3,000 rowsThe 600 test rows, through the median, the mean and the spread0.8018Close to the test score here, but the test no longer proves it
Leak B: SpendAmount as a featureThe answer itself, recorded after the purchase1.000Useless: the column is empty when the decision is made
1 LEAK A: WHO SETS THE MEDIAN 2,400 training rows 600 test clean: median of the 2,400 = $147.00 leaky: median of all 3,000 = $147.88 mean $148.75 → $149.22, spread $83.75 → $84.18 holdout AUC: 0.8018 → 0.8018 too small to see here, but the rehearsal is broken 2 LEAK B: A COLUMN FROM THE FUTURE arrives browses: views, cart decide: email? pays SpendAmount written 3 model trained with it: test AUC 1.000, accuracy 0.997 at decision time nobody has paid, so the column is empty the test rows carry the leaked column too, so the test cannot catch it; only "would I know this yet?" can
Fig. 2.5j — The two kinds of leak. Left: the median that fills blank carts, computed with and without the 600 test rows. Right: one visit in time order, and the column that is only written after the moment the model must decide. Values from rerunning split_and_leak.py.
  1. Leak from the test rows. The clean median uses only the 2,400 training rows. The leaky one also counts the 600 exam rows, and moves by 88 cents. On this data the score does not move, but the test has quietly stopped being an honest rehearsal.
  2. The moment of decision. The model is used at the blue dot: the visitor has browsed, and CartGenius must decide whether to email them. Everything to the left of that dot exists. Everything to the right has not happened yet.
  3. Leak from the future. SpendAmount is written at the red dot, after the purchase. Training on it carries the answer back in time, the dashed arrow, and the model scores a perfect 1.000. At the blue dot the column does not exist, so the perfect model is useless exactly where it is needed.

Anything the model learns from must exist, for real, at the moment it will make the prediction. Fit every statistic on the training rows, and question every column that is filled in later.

Walk one messy visitor through the pipeline: a blank cart value and a referral source it has never seen.

The fitted pipeline fills the blank with the stored median, scales with the stored means and spreads, turns the unknown source into zeros, and answers 0.548. A cleaning script rewritten for serving crashes on the same visitor, twice.

The live visitor, as the website sends it
FieldValueWhat is wrong with it
PageViews6Nothing
SessionMinutes12.5Nothing
CartValuenullThe tracking pixel failed
DaysSinceLastVisit10Nothing
ReferralSource"TikTok"A campaign launched after training; none of the 2,400 training visitors came from it
DeviceType"Mobile"Nothing
IsReturning0Nothing

Fig. 2.5k follows this visitor through both versions. The top row is the fitted pipeline from Fig. 2.5b, replaying what it stored. The bottom row is what happens when the cleaning code exists twice.

THE FITTED PIPELINE: EVERY NUMBER WAS STORED AT fit() live visitor PageViews 6 Minutes 12.5 CartValue null Days 10 Referral TikTok Device Mobile Returning 0 1 imputer CartValue: null → stored median $147.005 4 other columns pass unchanged 2 scaler (x − mean) ÷ spread views +0.44 minutes +0.61 cart −0.02 days −1.32 returning −0.80 3 encoder ReferralSource TikTok → 0 0 0 0 0 not one of the 5 DeviceType Mobile → 0 1 0 4 classifier z = +0.19 σ(0.19) = 0.548 0.548 ≥ 0.40 WARM LEAD 5 THE HAND-WRITTEN SERVING COPY: RECOMPUTES FROM ONE ROW fillna(row median) CartValue still NaN get_dummies(row) adds …_TikTok lacks 7 columns predict_proba(row) CRASH 1: the feature names should match patch them → CRASH 2: Input X contains NaN each crash is one statistic the training copy knew and the serving copy recomputed: the median, and the list of categories. The pipeline stores both, so neither can drift.
Fig. 2.5k — One messy visitor, two ways. Top: the fitted pipeline replays the numbers fit() stored, so the blank and the unknown source both pass through. Bottom: a serving copy of the cleaning code recomputes from the one row it has, and crashes twice. Every number from rerunning messy_visitor.py.
  1. The imputer. The blank CartValue becomes $147.005, the median of the 2,400 training carts, stored at fit time (marker 1 of Fig. 2.5b). The other four numeric fields pass through unchanged.
  2. The scaler. Each value minus its stored mean, divided by its stored spread. Page views (6 − 5.01) ÷ 2.23 = +0.44; minutes (12.5 − 7.79) ÷ 7.73 = +0.61; the filled cart (147.005 − 148.75) ÷ 83.75 = −0.02; days (10 − 44.15) ÷ 25.86 = −1.32; returning (0 − 0.39) ÷ 0.49 = −0.80.
  3. The encoder. The stored list of sources has five names, and TikTok is not one of them. So all five referral columns are 0, and handle_unknown="ignore" is what makes that a row of zeros instead of an error. Mobile is on the device list, so its column is 1.
  4. The classifier. The intercept and the six non-zero terms add up to +0.19. The sigmoid turns that into 0.548, and the handler files the visitor as a warm lead, because 0.548 is at least 0.40.
  5. The serving copy. It recomputes what the pipeline stored. The median of one blank value is still blank, and get_dummies builds columns out of this row's own values. The model refuses the column names first; after they are patched, it refuses the NaN.
The classifier's sum for this visitor (marker 4), rounded to two decimals. Weights from Fig. 2.5b.
TermWeight × scaled valueAdds
Intercept−0.43−0.43
PageViews+0.24 × +0.44+0.11
SessionMinutes+0.58 × +0.61+0.35
CartValue (the filled blank)+1.02 × −0.02−0.02
DaysSinceLastVisit−0.58 × −1.32+0.77
IsReturning+0.41 × −0.80−0.33
DeviceType_Mobile−0.26 × 1−0.26
Five referral columns, TikTokeach weight × 00
Score z, then σ(z)the sum above+0.19 → 0.548

Notice what the blank cart cost: almost nothing. Filling it with the median puts this visitor at the average cart, so that term adds −0.02, as if cart value said nothing either way.

Now the honest part about "ignore". Five zeros mean "none of the sources I know", so TikTok gets no referral weight at all. The same visitor arriving from Google scores 0.495, because Google's learned weight is −0.21; from Email, 0.651.

So the pipeline did not crash, but it also knows nothing about TikTok. In production, count how many live visitors land in all-zero referral columns, and retrain once that share stops being small.

The hand-written version, run for real

You have not met get_dummies or reindex before. The step-by-step list names what each one does, and only the two CRASH lines of the output carry the lesson.

Step-by-step: what messy_visitor.py does, in plain English
  1. Import numpy and pandas, LogisticRegression, the splitter and Pipeline, and reuse the data generator, the two column lists and the preprocessor from cartgenius_pipeline.py.
  2. Rebuild the same 3,000 visitors and the same 80/20 split as section 05. Keep only the training half; the underscores throw away the test half, which this script does not use.
  3. Build the messy visitor as a one-row DataFrame. CartValue is np.nan, numpy's "not a number", which is how pandas stores a blank. ReferralSource is "TikTok".
  4. BROKEN, training copy: fill blanks with the training medians, turn the two text columns into 0/1 columns with get_dummies, scale the numeric columns with the training mean and spread, and fit a model. This copy is correct on its own.
  5. BROKEN, serving copy, written separately: fill blanks with the median of the frame it is handed, which is one row whose blank has no median. Then get_dummies builds columns from this row's own values, so only ReferralSource_TikTok and DeviceType_Mobile appear. Scale with the stored mean and spread.
  6. Print which columns the live row gained and how many training columns it lacks.
  7. Try to score the row as it is, and print the first line of the error. Then patch the columns with reindex, which reorders them to match training and fills the missing ones with 0, try again, and print that error too.
  8. FIX: chain make_preprocessor() and the same LogisticRegression into one Pipeline and fit it on the training rows. Every median, mean, spread and category list is stored inside it now.
  9. Reach into the fitted preprocessor for the stored CartValue median and print it.
  10. Transform the messy visitor with the stored numbers and print all 13 columns the classifier will see, next to their names.
  11. Print the buy probability from predict_proba.
messy_visitor.pyruns offline
# pip install "scikit-learn>=1.9,<2" "pandas>=3,<4" "numpy>=2,<3"   # verified Sep 2026
# Prereq: cartgenius_pipeline.py (section 05) saved in the same folder.
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline

from cartgenius_pipeline import CAT_COLS, NUM_COLS, generate_ecommerce_data, make_preprocessor

df = generate_ecommerce_data(n_samples=3000)
X, y = df.drop(columns=["Purchased", "SpendAmount"]), df["Purchased"]
X_train, _, y_train, _ = train_test_split(X, y, test_size=0.20, random_state=42, stratify=y)

# One live visitor: the cart value failed to record, and the ad platform is new
visitor = pd.DataFrame([{"PageViews": 6, "SessionMinutes": 12.5, "CartValue": np.nan,
                         "DaysSinceLastVisit": 10, "ReferralSource": "TikTok",
                         "DeviceType": "Mobile", "IsReturning": 0}])

# BROKEN: the cleaning is written twice, once for training and later again for serving
train = X_train.fillna(X_train[NUM_COLS].median())
train = pd.get_dummies(train, columns=CAT_COLS, dtype=float)
mean, spread = train[NUM_COLS].mean(), train[NUM_COLS].std(ddof=0)
train[NUM_COLS] = (train[NUM_COLS] - mean) / spread
model = LogisticRegression(max_iter=1000).fit(train, y_train)

live = visitor.fillna(visitor[NUM_COLS].median())          # serving copy: the median of ONE row
live = pd.get_dummies(live, columns=CAT_COLS, dtype=float)  # columns come from this row's values
live[NUM_COLS] = (live[NUM_COLS] - mean) / spread
print("live row adds", sorted(set(live.columns) - set(train.columns)),
      "and lacks", len(set(train.columns) - set(live.columns)), "training columns")
for attempt in (live, live.reindex(columns=train.columns, fill_value=0.0)):
    try:
        model.predict_proba(attempt)
    except ValueError as err:
        print("CRASH:", str(err).splitlines()[0])

# FIX: one Pipeline stores every statistic at fit time and replays it at predict time
pipeline = Pipeline([("preprocessor", make_preprocessor()),
                     ("classifier", LogisticRegression(C=1.0, max_iter=1000, random_state=42))])
pipeline.fit(X_train, y_train)
prep = pipeline.named_steps["preprocessor"]
print("stored CartValue median:", round(prep.named_transformers_["num"].named_steps["imputer"].statistics_[2], 3))
for name, value in zip(prep.get_feature_names_out(), prep.transform(visitor)[0]):
    print(f"  {name:32s} {value:+.3f}")
print(f"P(buy) = {pipeline.predict_proba(visitor)[0, 1]:.3f}")
terminalactual output
live row adds ['ReferralSource_TikTok'] and lacks 7 training columns
CRASH: The feature names should match those that were passed during fit.
CRASH: Input X contains NaN.
stored CartValue median: 147.005
  num__PageViews                   +0.443
  num__SessionMinutes              +0.610
  num__CartValue                   -0.021
  num__DaysSinceLastVisit          -1.321
  num__IsReturning                 -0.801
  cat__ReferralSource_Affiliate    +0.000
  cat__ReferralSource_Direct       +0.000
  cat__ReferralSource_Email        +0.000
  cat__ReferralSource_Facebook     +0.000
  cat__ReferralSource_Google       +0.000
  cat__DeviceType_Desktop          +0.000
  cat__DeviceType_Mobile           +1.000
  cat__DeviceType_Tablet           +0.000
P(buy) = 0.548

Read the output from the top. Line 1: the serving copy's get_dummies made a column the model never saw, ReferralSource_TikTok, and left out 7 it expects: all five known sources, Desktop and Tablet.

Lines 2 and 3 are the two crashes. The first is about column names. Patching the names only uncovers the second: the blank that a one-row median could not fill. Each crash is one number the training copy knew and the serving copy did not, the category list and the median.

The rest is the pipeline's view of the same visitor. CartValue −0.021 is the stored $147.005, scaled. The five referral columns are all +0.000, which is TikTok. DeviceType_Mobile is 1. P(buy) = 0.548 is the probability the handler acts on.

Everything the pipeline needs at serving time was written into it at fit time. The live row supplies only its own values, so a blank or a brand-new category cannot break it.

You have not been taught any of the scikit-learn calls below yet. That is on purpose. Guess first, then check. Every call is explained in the answers, in the step-by-step list above the code, and in the four notes that follow the output.

Sharpen your pencil

Below are twelve lines lifted from cartgenius_pipeline.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.

("imputer", SimpleImputer(strategy="median")),fill every missing number in a column with that column's middle value, learned from training rows only
("scaler", StandardScaler()),
("cat", OneHotEncoder(handle_unknown="ignore"), CAT_COLS),
ColumnTransformer(transformers=[("num", ...), ("cat", ...)])
Pipeline([("preprocessor", make_preprocessor()), ("classifier", LogisticRegression(C=1.0, max_iter=1000, random_state=42))])chain the preprocessing and the model into one object, so that fit and predict run both, in order
train_test_split(X, y, test_size=0.20, random_state=42, stratify=y)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
cross_val_score(pipeline, X_train, y_train, cv=cv, scoring="roc_auc")
pipeline.fit(X_train, y_train)learn the medians, the means and spreads, the category lists and the weights, all from the training rows
proba = pipeline.predict_proba(X_test)[:, 1]
coefs = pipeline.named_steps["classifier"].coef_[0]
predicted_spend = float(reg.predict(row)[0]) if p_buy >= 0.40 else 0.0
Check your answers
("imputer", SimpleImputer(strategy="median")),fill every missing number in a column with that column's middle value, learned from training rows only
("scaler", StandardScaler()),subtract each column's mean and divide by its spread, the section 04 fix, with the mean and spread learned at fit time and reused at predict time
("cat", OneHotEncoder(handle_unknown="ignore"), CAT_COLS),turn each text category into its own 0/1 column; a category never seen in training becomes a row of zeros instead of an error
ColumnTransformer(transformers=[("num", ...), ("cat", ...)])send the numeric columns through one recipe and the text columns through another, then glue the results side by side into one matrix
Pipeline([("preprocessor", make_preprocessor()), ("classifier", LogisticRegression(C=1.0, max_iter=1000, random_state=42))])chain the preprocessing and the model into one object, so that fit and predict run both, in order
train_test_split(X, y, test_size=0.20, random_state=42, stratify=y)hold back 20% of the rows that the model will never see; stratify keeps the buyer rate identical in both halves
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)a recipe for cutting the training rows into five slices, each with the same buyer rate, after shuffling
cross_val_score(pipeline, X_train, y_train, cv=cv, scoring="roc_auc")train five times, each time on four slices, and score on the fifth; the whole pipeline is refit each time, so no slice leaks into another. Returns five AUC numbers
pipeline.fit(X_train, y_train)learn the medians, the means and spreads, the category lists and the weights, all from the training rows
proba = pipeline.predict_proba(X_test)[:, 1]one probability per holdout row; the array has two columns and column 1 is the "will buy" probability, the propensity score
coefs = pipeline.named_steps["classifier"].coef_[0]reach inside the pipeline by step name for the fitted model and take its weights, one per column of the transformed matrix
predicted_spend = float(reg.predict(row)[0]) if p_buy >= 0.40 else 0.0only ask the spend model when the buy probability clears 0.40; otherwise predict zero spend and skip the call

Do not worry if you got half of these. If you guessed that the pipeline learns things at fit and replays them at predict, you already have the idea that the rest of this section defends. The exact class names are what the step-by-step list is for.

Here is the full CartGenius engine — both of Elena's models plus the inference handler, verified end-to-end on the current stack:

Build it in chunks

We build cartgenius_pipeline.py in six chunks. Each one runs on its own; the whole file comes at the end.

  1. Chunk 1 — make 3,000 fake visitors, with holes in the data

    Every model needs rows to learn from, so the data comes first. Real logs have gaps (a browser closes mid-session), so we punch about 5% holes in two columns on purpose. Nothing is predicted yet; there is no purchase column.

    Step-by-step: what chunk 1 does, in plain English
    1. Make a random-number generator with a fixed seed, so every run gives the same visitors.
    2. Draw page views, session minutes, cart value and days since last visit for 3,000 people.
    3. Pick a referral source and a device type for each person, with the stated odds.
    4. Choose about 5% of rows at random for each of two columns and overwrite those cells with NaN (the standard 'missing' marker).
    5. Return everything as one table (a DataFrame).
    cartgenius_pipeline.py — chunk 1runs offline
    def generate_ecommerce_data(n_samples: int = 3000, seed: int = 42) -> pd.DataFrame:
        """Synthetic visitor logs shaped like real business data: mixed types, NaNs."""
        rng = np.random.default_rng(seed)
    
        page_views = rng.poisson(lam=5, size=n_samples)
        session_minutes = np.round(rng.exponential(scale=8, size=n_samples), 1)
        cart_value = np.round(rng.uniform(0, 300, size=n_samples), 2)
        days_since_last_visit = rng.integers(0, 90, size=n_samples)
        referral_source = rng.choice(
            ["Google", "Facebook", "Direct", "Email", "Affiliate"],
            size=n_samples, p=[0.30, 0.20, 0.25, 0.15, 0.10])
        device_type = rng.choice(["Mobile", "Desktop", "Tablet"],
                                 size=n_samples, p=[0.55, 0.35, 0.10])
        is_returning = rng.choice([0, 1], size=n_samples, p=[0.60, 0.40])
    
        # 5% missing values: browsers close mid-session, tracking pixels fail (MCAR)
        missing_cart = rng.random(n_samples) < 0.05
        missing_sess = rng.random(n_samples) < 0.05
        cart_with_na = cart_value.astype(float).copy()
        sess_with_na = session_minutes.astype(float).copy()
        cart_with_na[missing_cart] = np.nan
        sess_with_na[missing_sess] = np.nan
        # (returns a DataFrame of the seven feature columns)

    np.random.default_rng(seed) — a repeatable random-number source. np.nan — the 'missing' marker.

    Run python3 chunk1_features.py. You should see the table shape and the two missing counts.

    terminalactual output
    (3000, 7)
    Missing CartValue: 139, missing SessionMinutes: 140
  2. Chunk 2 — decide who buys, and how much the buyers spend

    Chunk 1 has behaviour but no answer. This chunk invents the hidden rule (more page views, longer sessions and a bigger cart make a purchase likelier) and then rolls a dice per visitor. The model in later chunks has to rediscover that rule from the results.

    Step-by-step: what chunk 2 does, in plain English
    1. Combine the features into one score (the logit): each behaviour adds or subtracts a little.
    2. Squash the score into a 0-to-1 probability with the S-shaped logistic function.
    3. Roll a dice for each visitor: buy if the dice number is below their probability.
    4. For buyers only, make the spend depend on cart size and session time, plus random lognormal noise; non-buyers spend 0.
    5. Change the last line of the function: the returned table now also holds Purchased and SpendAmount.
    cartgenius_pipeline.py — chunk 2runs offline
        # Purchase probability: a logistic function of behavior — the "truth" our
        # classifier must rediscover from noisy samples of it
        logit = (0.15 * page_views + 0.08 * session_minutes + 0.012 * cart_value
                 - 0.025 * days_since_last_visit + 0.8 * is_returning
                 + 0.5 * (referral_source == "Email") - 0.3 * (device_type == "Mobile") - 3.0)
        purchase_prob = 1 / (1 + np.exp(-logit))
        purchased = (rng.random(n_samples) < purchase_prob).astype(int)
    
        # Spend for purchasers: driven by cart size + session time, lognormal noise on top
        spend = np.where(purchased == 1,
                         np.round(0.5 * cart_value + 3.0 * session_minutes
                                  + rng.lognormal(mean=3.2, sigma=0.6, size=n_samples), 2), 0.0)
        # ...and the return now adds:
        #   "Purchased": purchased, "SpendAmount": spend

    np.where(condition, a, b) — pick a value per row. A comparison like rng.random(n) < p makes a True/False per row; .astype(int) turns that into 1/0.

    Run python3 chunk2_label.py. The purchase rate should land near 37%, and the spend summary should show buyers only.

    terminalactual output
    Records: 3000, purchase rate: 37.20%
    Missing CartValue: 139, missing SessionMinutes: 140
    count    1116.00
    mean      156.13
    std        50.27
    min        21.62
    25%       125.24
    50%       156.06
    75%       186.26
    max       347.71
  3. Chunk 3 — clean the data inside a Pipeline and grade a purchase classifier honestly

    Now the model can be trained, but the data still has holes and text columns. The preprocessor fixes both, and bundling it with the model in one Pipeline means cross-validation re-learns the fix inside every fold, so the test rows never leak into training.

    Step-by-step: what chunk 3 does, in plain English
    1. make_preprocessor: fill numeric holes with the median, scale numbers to comparable size, and turn each text category into 0/1 columns.
    2. Split off 20% of the rows that the model will never see during fitting (same purchase rate in both halves).
    3. Chain preprocessor and logistic regression into one Pipeline object.
    4. Run 5-fold cross-validation on the training 80% and print the mean and spread of ROC-AUC (a 0.5-to-1.0 ranking score).
    5. Fit once on the full training 80%, then score the untouched 20%: AUC, confusion matrix, per-class report.
    cartgenius_pipeline.py — chunk 3runs offline
    def make_preprocessor() -> ColumnTransformer:
        return ColumnTransformer(transformers=[
            ("num", Pipeline([
                ("imputer", SimpleImputer(strategy="median")),   # median: immune to $4,000 outlier carts
                ("scaler", StandardScaler()),                    # section 04 showed why this is non-optional
            ]), NUM_COLS),
            # handle_unknown="ignore": prod WILL see referral sources training never did
            ("cat", OneHotEncoder(handle_unknown="ignore"), CAT_COLS),
        ])
    
    def build_conversion_classifier(df: pd.DataFrame) -> Pipeline:
        X = df.drop(columns=["Purchased", "SpendAmount"])
        y = df["Purchased"]
    
        # NOTE (Aug 2026): penalty="l2" is deprecated since sklearn 1.8 — L2 is the
        # default; C sets its strength, and l1_ratio>0 buys Lasso-style sparsity.
        pipeline = Pipeline([
            ("preprocessor", make_preprocessor()),
            ("classifier", LogisticRegression(C=1.0, max_iter=1000, random_state=42)),
        ])
    
        X_train, X_test, y_train, y_test = train_test_split(
            X, y, test_size=0.20, random_state=42, stratify=y)
    
        # CV re-fits imputer+scaler inside every fold — leakage-free by construction
        cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
        cv_scores = cross_val_score(pipeline, X_train, y_train, cv=cv, scoring="roc_auc")
        print(f"  5-fold CV ROC-AUC: {cv_scores.mean():.4f} ± {cv_scores.std():.4f}")
    
        pipeline.fit(X_train, y_train)
        proba = pipeline.predict_proba(X_test)[:, 1]
        pred = pipeline.predict(X_test)
        print(f"  Holdout ROC-AUC:   {roc_auc_score(y_test, proba):.4f}")
        print(f"  Confusion matrix:\n{confusion_matrix(y_test, pred)}")
        print(classification_report(y_test, pred))
        return pipeline

    Pipeline — preprocessing plus model as one object. ColumnTransformer — different treatment per column group. cross_val_score — repeated train/test splits.

    Run python3 chunk3_classifier.py. Expect a CV AUC near 0.81 and a holdout AUC near 0.80.

    terminalactual output
    Records: 3000, purchase rate: 37.20%
      5-fold CV ROC-AUC: 0.8059 ± 0.0110
      Holdout ROC-AUC:   0.8018
      Confusion matrix:
    [[316  61]
     [ 94 129]]
  4. Chunk 4 — ask the model why: rank features by coefficient

    A score alone won't convince Elena's team. A logistic regression has one number per feature, and reading them tells you what pushes a visitor toward buying. These lines go inside the function from chunk 3, just before return pipeline.

    Step-by-step: what chunk 4 does, in plain English
    1. Read the numeric column names, then the one-hot names the encoder made from the text columns.
    2. Fetch the classifier's coefficients from the fitted pipeline.
    3. Pair names with numbers and sort by size, ignoring sign.
    4. Print the top eight, saying whether each raises or lowers the odds of a purchase.
    cartgenius_pipeline.py — chunk 4runs offline
        # Coefficients = the "why" Elena's team will ask for
        feature_names = (NUM_COLS + list(pipeline.named_steps["preprocessor"]
                         .named_transformers_["cat"].get_feature_names_out(CAT_COLS)))
        coefs = pipeline.named_steps["classifier"].coef_[0]
        ranked = sorted(zip(feature_names, coefs), key=lambda t: abs(t[1]), reverse=True)
        for feat, coef in ranked[:8]:
            direction = "raises" if coef > 0 else "lowers"
            print(f"    {feat:>25s}: {coef:+.4f}  ({direction} purchase log-odds)")

    named_steps[...] — pull one fitted stage out of a Pipeline. get_feature_names_out — names of the columns the encoder made.

    Run python3 chunk4_coefficients.py. Eight lines appear after the report; the largest is CartValue.

    terminalactual output
    ...
                        CartValue: +1.0194  (raises purchase log-odds)
               DaysSinceLastVisit: -0.5793  (lowers purchase log-odds)
                   SessionMinutes: +0.5784  (raises purchase log-odds)
             ReferralSource_Email: +0.4309  (raises purchase log-odds)
                      IsReturning: +0.4077  (raises purchase log-odds)
            ReferralSource_Direct: -0.3048  (lowers purchase log-odds)
                DeviceType_Mobile: -0.2582  (lowers purchase log-odds)
                        PageViews: +0.2433  (raises purchase log-odds)
  5. Chunk 5 — a second model: how many dollars will a buyer spend?

    The classifier says who will buy; the business also wants to know how much. Spend only exists for buyers, so this model trains on buyers alone. It reuses the same preprocessor from chunk 3, which is the point of writing it as a function.

    Step-by-step: what chunk 5 does, in plain English
    1. Keep only the rows where Purchased == 1.
    2. Drop the two answer columns from the inputs; the target is SpendAmount.
    3. Chain the same preprocessor with Ridge, a linear model with a leash that stops coefficients getting wild.
    4. Split, fit, predict, and report the average miss in dollars (MAE) and R², the share of variation explained.
    cartgenius_pipeline.py — chunk 5runs offline
    def build_spend_predictor(df: pd.DataFrame) -> Pipeline:
        buyers = df[df["Purchased"] == 1]
        X = buyers.drop(columns=["Purchased", "SpendAmount"])
        y = buyers["SpendAmount"]
    
        pipeline = Pipeline([
            ("preprocessor", make_preprocessor()),
            ("regressor", Ridge(alpha=1.0)),   # the elastic leash from Fig. 2.4
        ])
        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=42)
        pipeline.fit(X_train, y_train)
        y_pred = pipeline.predict(X_test)
        print(f"  Spend predictor — MAE: ${mean_absolute_error(y_test, y_pred):.2f}, "
              f"R²: {r2_score(y_test, y_pred):.4f}")
        return pipeline

    Ridge(alpha=1.0) — linear regression with a penalty on large coefficients. mean_absolute_error — the average size of a miss.

    Run python3 chunk5_spend.py. One new line appears at the end: MAE about $17 and R² about 0.77.

    terminalactual output
    ...
      Spend predictor — MAE: $16.95, R²: 0.7711
  6. Chunk 6 — wrap both models in a function that answers one JSON request

    In production a visitor arrives as JSON, possibly with fields missing. This last chunk turns that JSON into a one-row table, asks the classifier, asks the spend model only for warm leads, and returns a marketing action. Chunk 6 is the finished file.

    Step-by-step: what chunk 6 does, in plain English
    1. Parse the JSON text into a dictionary.
    2. Build a one-row DataFrame; absent fields become None, which the imputer fills.
    3. Ask the classifier for the purchase probability.
    4. Ask the spend model only if that probability is at least 0.40, otherwise spend is 0.
    5. Pick one of three actions from two cut-offs (0.40 and 0.70) and return everything as JSON.
    cartgenius_pipeline.py — chunk 6runs offline
    def predict_customer_value(visitor_json: str, clf: Pipeline, reg: Pipeline) -> str:
        """JSON visitor payload in → purchase probability + spend + action out."""
        visitor = json.loads(visitor_json)
        row = pd.DataFrame([{
            "PageViews": visitor["PageViews"],
            "SessionMinutes": visitor.get("SessionMinutes"),   # may be None — imputer handles it
            "CartValue": visitor.get("CartValue"),
            "DaysSinceLastVisit": visitor["DaysSinceLastVisit"],
            "ReferralSource": visitor["ReferralSource"],
            "DeviceType": visitor["DeviceType"],
            "IsReturning": visitor["IsReturning"],
        }])
        p_buy = float(clf.predict_proba(row)[0, 1])
        predicted_spend = float(reg.predict(row)[0]) if p_buy >= 0.40 else 0.0
        if p_buy >= 0.70:
            action = "HIGH VALUE — premium offer with free shipping"
        elif p_buy >= 0.40:
            action = "WARM LEAD — personalized recommendations"
        else:
            action = "COLD VISITOR — retargeting audience only"
        return json.dumps({
            "visitor_id": visitor.get("VisitorID", "UNKNOWN"),
            "purchase_probability": round(p_buy, 4),
            "predicted_spend": round(max(predicted_spend, 0), 2),
            "marketing_action": action}, indent=2)
    
    
    if __name__ == "__main__":
        data = generate_ecommerce_data(n_samples=3000)
        print(f"Records: {len(data)}, purchase rate: {data['Purchased'].mean():.2%}")
        print(f"Missing CartValue: {data['CartValue'].isna().sum()}, "
              f"missing SessionMinutes: {data['SessionMinutes'].isna().sum()}")
        clf = build_conversion_classifier(data)
        reg = build_spend_predictor(data)
        payload = json.dumps({
            "VisitorID": "VIS-7721", "PageViews": 12, "SessionMinutes": 22.5,
            "CartValue": 189.99, "DaysSinceLastVisit": 2, "ReferralSource": "Email",
            "DeviceType": "Desktop", "IsReturning": 1})
        print(predict_customer_value(payload, clf, reg))

    json.loads / json.dumps — text to dictionary and back. dict.get(key) — returns None instead of crashing when a key is absent.

    Run python3 chunk6_handler.py. The last lines are a JSON answer for visitor VIS-7721.

    terminalactual output
    ...
    {
      "visitor_id": "VIS-7721",
      "purchase_probability": 0.9772,
      "predicted_spend": 195.25,
      "marketing_action": "HIGH VALUE \u2014 premium offer with free shipping"
    }

The whole program

The file below is the finished program. Its chunk comments mark where each rung landed: lines 3–47 are chunk 1; lines 48–68 are chunk 2; lines 69–112 are chunk 3; lines 113–124 are chunk 4; lines 125–145 are chunk 5; lines 146–187 are chunk 6.

Step-by-step: what cartgenius_pipeline.py does, in plain English
  1. Import json for the inference handler, numpy and pandas for data, and from scikit-learn the ColumnTransformer, the imputer, the two models, six metrics, the splitting tools, Pipeline and the two preprocessors.
  2. Name the five numeric columns and the two categorical columns once, at the top. Every later function reads these two lists.
  3. generate_ecommerce_data: draw 3,000 fake visitors with realistic shapes (Poisson page views, exponential session minutes, uniform cart values, weighted referral and device choices).
  4. Blank out 5% of cart values and 5% of session minutes at random, replacing them with NaN, so the pipeline has to cope with missing data the way production does.
  5. Compute a hidden "true" purchase score as a weighted sum of the features minus 3, push it through the sigmoid, and flip a biased coin per visitor. The classifier's job is to rediscover these weights from the coin flips.
  6. For purchasers only, build a spend amount from cart value and session minutes plus lognormal noise; non-purchasers spend 0. Return everything as one DataFrame.
  7. make_preprocessor: a ColumnTransformer with two branches. The numeric branch imputes the median and then standardizes. The categorical branch one-hot encodes with handle_unknown="ignore", so an unseen referral source becomes all zeros instead of a crash.
  8. build_conversion_classifier: separate the features from the Purchased label, and chain the preprocessor and a LogisticRegression into one Pipeline.
  9. Split 80/20 with stratify=y, so both halves have the same 37% purchase rate.
  10. Cross-validate on the training 80% only: five stratified folds, with the whole pipeline refit inside each fold, so the imputer and scaler never see the fold being scored. Print the mean and spread of ROC-AUC.
  11. Fit once on all training rows, then score the untouched 20%: probabilities for AUC, hard labels for the confusion matrix and the classification report.
  12. Recover the feature names (the five numeric names plus the one-hot names from the encoder), pair each with its coefficient, sort by size, and print the top eight with the direction of the effect.
  13. build_spend_predictor: keep buyers only, chain the same preprocessor with Ridge(alpha=1.0), split, fit, and report MAE in dollars and R².
  14. predict_customer_value: parse one visitor's JSON into a one-row DataFrame (missing fields become None, which the imputer handles), ask the classifier for the buy probability, ask the spend model only if that probability is at least 0.40, pick a marketing action from two cutoffs, and return JSON.
  15. The main block: generate the data, report the missing counts, build both models, and run one sample visitor through the handler.
cartgenius_pipeline.pyruns offline
# pip install "scikit-learn>=1.9,<2" "pandas>=3,<4" "numpy>=2,<3"   # verified Aug 2026
"""CartGenius predictive engine: conversion classifier + spend predictor."""
# ── chunk 1: fake visitors with holes ──
import json

import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression, Ridge
from sklearn.metrics import (classification_report, confusion_matrix,
                             mean_absolute_error, r2_score, roc_auc_score)
from sklearn.model_selection import (StratifiedKFold, cross_val_score,
                                     train_test_split)
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

NUM_COLS = ["PageViews", "SessionMinutes", "CartValue", "DaysSinceLastVisit", "IsReturning"]
CAT_COLS = ["ReferralSource", "DeviceType"]


# =====================================================================
# 1. SYNTHETIC E-COMMERCE DATA GENERATOR
# =====================================================================
def generate_ecommerce_data(n_samples: int = 3000, seed: int = 42) -> pd.DataFrame:
    """Synthetic visitor logs shaped like real business data: mixed types, NaNs."""
    rng = np.random.default_rng(seed)

    page_views = rng.poisson(lam=5, size=n_samples)
    session_minutes = np.round(rng.exponential(scale=8, size=n_samples), 1)
    cart_value = np.round(rng.uniform(0, 300, size=n_samples), 2)
    days_since_last_visit = rng.integers(0, 90, size=n_samples)
    referral_source = rng.choice(
        ["Google", "Facebook", "Direct", "Email", "Affiliate"],
        size=n_samples, p=[0.30, 0.20, 0.25, 0.15, 0.10])
    device_type = rng.choice(["Mobile", "Desktop", "Tablet"],
                             size=n_samples, p=[0.55, 0.35, 0.10])
    is_returning = rng.choice([0, 1], size=n_samples, p=[0.60, 0.40])

    # 5% missing values: browsers close mid-session, tracking pixels fail (MCAR)
    missing_cart = rng.random(n_samples) < 0.05
    missing_sess = rng.random(n_samples) < 0.05
    cart_with_na = cart_value.astype(float).copy()
    sess_with_na = session_minutes.astype(float).copy()
    cart_with_na[missing_cart] = np.nan
    sess_with_na[missing_sess] = np.nan

    # ── chunk 2: who buys, and how much they spend ──
    # Purchase probability: a logistic function of behavior — the "truth" our
    # classifier must rediscover from noisy samples of it
    logit = (0.15 * page_views + 0.08 * session_minutes + 0.012 * cart_value
             - 0.025 * days_since_last_visit + 0.8 * is_returning
             + 0.5 * (referral_source == "Email") - 0.3 * (device_type == "Mobile") - 3.0)
    purchase_prob = 1 / (1 + np.exp(-logit))
    purchased = (rng.random(n_samples) < purchase_prob).astype(int)

    # Spend for purchasers: driven by cart size + session time, lognormal noise on top
    spend = np.where(purchased == 1,
                     np.round(0.5 * cart_value + 3.0 * session_minutes
                              + rng.lognormal(mean=3.2, sigma=0.6, size=n_samples), 2), 0.0)

    return pd.DataFrame({
        "PageViews": page_views, "SessionMinutes": sess_with_na, "CartValue": cart_with_na,
        "DaysSinceLastVisit": days_since_last_visit, "ReferralSource": referral_source,
        "DeviceType": device_type, "IsReturning": is_returning,
        "Purchased": purchased, "SpendAmount": spend})


# ── chunk 3: clean the data in a Pipeline and grade the classifier ──
# =====================================================================
# 2. SHARED PREPROCESSING — the production pattern
# =====================================================================
def make_preprocessor() -> ColumnTransformer:
    return ColumnTransformer(transformers=[
        ("num", Pipeline([
            ("imputer", SimpleImputer(strategy="median")),   # median: immune to $4,000 outlier carts
            ("scaler", StandardScaler()),                    # section 04 showed why this is non-optional
        ]), NUM_COLS),
        # handle_unknown="ignore": prod WILL see referral sources training never did
        ("cat", OneHotEncoder(handle_unknown="ignore"), CAT_COLS),
    ])


# =====================================================================
# 3. CONVERSION CLASSIFIER (logistic regression)
# =====================================================================
def build_conversion_classifier(df: pd.DataFrame) -> Pipeline:
    X = df.drop(columns=["Purchased", "SpendAmount"])
    y = df["Purchased"]

    # NOTE (Aug 2026): penalty="l2" is deprecated since sklearn 1.8 — L2 is the
    # default; C sets its strength, and l1_ratio>0 buys Lasso-style sparsity.
    pipeline = Pipeline([
        ("preprocessor", make_preprocessor()),
        ("classifier", LogisticRegression(C=1.0, max_iter=1000, random_state=42)),
    ])

    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.20, random_state=42, stratify=y)

    # CV re-fits imputer+scaler inside every fold — leakage-free by construction
    cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
    cv_scores = cross_val_score(pipeline, X_train, y_train, cv=cv, scoring="roc_auc")
    print(f"  5-fold CV ROC-AUC: {cv_scores.mean():.4f} ± {cv_scores.std():.4f}")

    pipeline.fit(X_train, y_train)
    proba = pipeline.predict_proba(X_test)[:, 1]
    pred = pipeline.predict(X_test)
    print(f"  Holdout ROC-AUC:   {roc_auc_score(y_test, proba):.4f}")
    print(f"  Confusion matrix:\n{confusion_matrix(y_test, pred)}")
    print(classification_report(y_test, pred))

    # ── chunk 4: rank the features by coefficient ──
    # Coefficients = the "why" Elena's team will ask for
    feature_names = (NUM_COLS + list(pipeline.named_steps["preprocessor"]
                     .named_transformers_["cat"].get_feature_names_out(CAT_COLS)))
    coefs = pipeline.named_steps["classifier"].coef_[0]
    ranked = sorted(zip(feature_names, coefs), key=lambda t: abs(t[1]), reverse=True)
    for feat, coef in ranked[:8]:
        direction = "raises" if coef > 0 else "lowers"
        print(f"    {feat:>25s}: {coef:+.4f}  ({direction} purchase log-odds)")
    return pipeline


# ── chunk 5: the spend predictor ──
# =====================================================================
# 4. SPEND PREDICTOR (Ridge regression — buyers only)
# =====================================================================
def build_spend_predictor(df: pd.DataFrame) -> Pipeline:
    buyers = df[df["Purchased"] == 1]
    X = buyers.drop(columns=["Purchased", "SpendAmount"])
    y = buyers["SpendAmount"]

    pipeline = Pipeline([
        ("preprocessor", make_preprocessor()),
        ("regressor", Ridge(alpha=1.0)),   # the elastic leash from Fig. 2.4
    ])
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=42)
    pipeline.fit(X_train, y_train)
    y_pred = pipeline.predict(X_test)
    print(f"  Spend predictor — MAE: ${mean_absolute_error(y_test, y_pred):.2f}, "
          f"R²: {r2_score(y_test, y_pred):.4f}")
    return pipeline


# ── chunk 6: the JSON handler and the main block ──
# =====================================================================
# 5. REAL-TIME INFERENCE HANDLER
# =====================================================================
def predict_customer_value(visitor_json: str, clf: Pipeline, reg: Pipeline) -> str:
    """JSON visitor payload in → purchase probability + spend + action out."""
    visitor = json.loads(visitor_json)
    row = pd.DataFrame([{
        "PageViews": visitor["PageViews"],
        "SessionMinutes": visitor.get("SessionMinutes"),   # may be None — imputer handles it
        "CartValue": visitor.get("CartValue"),
        "DaysSinceLastVisit": visitor["DaysSinceLastVisit"],
        "ReferralSource": visitor["ReferralSource"],
        "DeviceType": visitor["DeviceType"],
        "IsReturning": visitor["IsReturning"],
    }])
    p_buy = float(clf.predict_proba(row)[0, 1])
    predicted_spend = float(reg.predict(row)[0]) if p_buy >= 0.40 else 0.0
    if p_buy >= 0.70:
        action = "HIGH VALUE — premium offer with free shipping"
    elif p_buy >= 0.40:
        action = "WARM LEAD — personalized recommendations"
    else:
        action = "COLD VISITOR — retargeting audience only"
    return json.dumps({
        "visitor_id": visitor.get("VisitorID", "UNKNOWN"),
        "purchase_probability": round(p_buy, 4),
        "predicted_spend": round(max(predicted_spend, 0), 2),
        "marketing_action": action}, indent=2)


if __name__ == "__main__":
    data = generate_ecommerce_data(n_samples=3000)
    print(f"Records: {len(data)}, purchase rate: {data['Purchased'].mean():.2%}")
    print(f"Missing CartValue: {data['CartValue'].isna().sum()}, "
          f"missing SessionMinutes: {data['SessionMinutes'].isna().sum()}")
    clf = build_conversion_classifier(data)
    reg = build_spend_predictor(data)
    payload = json.dumps({
        "VisitorID": "VIS-7721", "PageViews": 12, "SessionMinutes": 22.5,
        "CartValue": 189.99, "DaysSinceLastVisit": 2, "ReferralSource": "Email",
        "DeviceType": "Desktop", "IsReturning": 1})
    print(predict_customer_value(payload, clf, reg))
terminalactual output (abridged)
Records: 3000, purchase rate: 37.20%
Missing CartValue: 139, missing SessionMinutes: 140
  5-fold CV ROC-AUC: 0.8059 ± 0.0110
  Holdout ROC-AUC:   0.8018
  Confusion matrix:
[[316  61]
 [ 94 129]]
                    CartValue: +1.0194  (raises purchase log-odds)
           DaysSinceLastVisit: -0.5793  (lowers purchase log-odds)
               SessionMinutes: +0.5784  (raises purchase log-odds)
         ReferralSource_Email: +0.4309  (raises purchase log-odds)
                  IsReturning: +0.4077  (raises purchase log-odds)
  Spend predictor — MAE: $16.95, R²: 0.7711
{
  "visitor_id": "VIS-7721",
  "purchase_probability": 0.9772,
  "predicted_spend": 195.25,
  "marketing_action": "HIGH VALUE — premium offer with free shipping"
}

The last block of that output is one visitor. Fig. 2.5c puts VIS-7721 on the S-curve from section 02, with the sum that produced the 0.9772.

FIG. 2.3 AGAIN: WHERE VIS-7721 LANDS z = the visitor's score (the weighted sum) P(buy) −6 −4 −2 0 2 4 6 0.0 0.5 1.0 0.5: predict()'s cutoff 1 above it, 0 below 2 0.70: HIGH VALUE, premium offer 0.40: WARM / COLD line 3 1 VIS-7721: z = 3.76 → p = 0.977 3.76 VIS-7721: weight × scaled value −0.43 intercept + 1.02 × 0.49 (CartValue $190) + 0.58 × 1.90 (SessionMinutes 22.5) + 0.24 × 3.13 (PageViews 12) − 0.58 × −1.63 (DaysSinceLastVisit 2) + 0.41 × 1.25 (IsReturning 1) + 0.43 (Email) − 0.06 (Desktop) = 3.76 → σ(3.76) = 0.977 0.977 ≥ 0.70 → HIGH VALUE offer spend model called: 0.977 ≥ 0.40
Fig. 2.5c — Fig. 2.3 again, with one real visitor on it. VIS-7721's scaled values times the fitted weights add up to a score of 3.76, the sigmoid turns that into 0.977, and 0.977 clears every cutoff in the handler. Weights and scaled values read off the fitted pipeline by rerunning cartgenius_pipeline.py; the terms are rounded to two decimals.
  1. The visitor. Twelve page views, 22.5 minutes, a $190 cart, back after two days, returning, arrived from an email. Each of those becomes a scaled value, is multiplied by its weight from Fig. 2.5b, and the products sum to 3.76. The curve then reads off 0.977, which is the "purchase_probability" in the printed JSON.
  2. The 0.5 line. predict() draws this line and answers 1 above it and 0 below; that is all the confusion matrix below can see. predict_proba() gives the height of the dot itself, which is what Elena ranks by.
  3. The action lines. predict_customer_value() draws two more: 0.40, below which the visitor is only a retargeting audience, and 0.70, above which they get the premium offer. VIS-7721 at 0.977 is above both. The lab moves the money line to 0.35 once each contact and each sale has a price.

Four things worth slowing down for.

The imputer lives inside the pipeline, so its medians are computed on training folds only. Swap the order and cross-validation silently inflates your scores.

CV mean ± std is a stability report. 0.806 ± 0.011 says five differently-split models agree within a point. The holdout 0.802 landing inside that band is what "no surprise in production" looks like.

Coefficients are the interpretability payload. +1.02 on standardized CartValue means one standard deviation more cart value multiplies the odds of buying by e1.02 ≈ 2.8× — a sentence Elena's team can act on. The 1.02 × 0.49 term in Fig. 2.5c is that weight at work for one visitor.

Deprecation radar, August 2026. scikit-learn 1.8 deprecated LogisticRegression(penalty=…), with removal in 1.10. L2 is now the default, C sets the strength, and l1_ratio is how you dial in L1 or ElasticNet sparsity. Tutorials passing penalty="l2" are date-stamping themselves.

Anatomy of fit and predict_proba — the two calls to know by heart
pipeline1.fit(2X_train, y_train3)
proba = pipeline.predict_proba(4X_test5)[:, 1]6
  1. The whole pipeline, not the classifier. Calling fit on pipeline fits the imputer, the scaler, the encoder and the model, in that order, each on the output of the one before. The mistake: fitting LogisticRegression directly on a frame you cleaned by hand, then writing a second copy of the cleaning code for serving.
  2. fit learns; it does not predict. Every statistic the pipeline will ever use (five medians, five means and spreads, the category lists, the weights) is computed here and stored inside the object. The mistake: calling fit again on the test rows "to update it", which is leakage by another name.
  3. Training rows only, features and answers. X_train is the raw DataFrame with NaNs and text still in it; y_train is the 0/1 column. The mistake: passing the full X and y here, which makes every holdout number a lie.
  4. predict_proba, not predict. predict applies a 0.5 cutoff and returns 0 or 1. predict_proba returns the probability, which is the propensity score Elena ranks by. The mistake: computing ROC-AUC from predict output, which throws away the ranking that AUC measures.
  5. Raw holdout, same columns. Untransformed. The pipeline applies the stored medians, means and category lists with no refitting. The mistake: scaling X_test yourself first, which scales it twice.
  6. Column 1 is the "yes" probability. predict_proba returns two columns: column 0 is the probability of class 0, column 1 of class 1, and each row sums to one. The mistake: passing the whole array to roc_auc_score, which errors, or taking column 0 and getting an AUC of 0.20 that "looks broken".
Sharpen your pencil

The confusion matrix in the output above is four counts. Turn them into the numbers Elena will ask for, by hand, before you read the accuracy discussion that follows. scikit-learn lays the matrix out with the truth in rows and the prediction in columns.

Layout of [[316 61] [94 129]]top row: people who did not buy; bottom row: people who bought. Left column: predicted no; right column: predicted yes
The four countstrue negatives 316, false positives 61, false negatives 94, true positives 129
The formulasaccuracy = (TP + TN) / total; precision = TP / (TP + FP); recall = TP / (TP + FN)
Holdout size
Actual buyers in the holdout, and as a share
Accuracy
Accuracy of "nobody buys" on this same holdout
Precision
Recall

Work to four decimal places. Then answer in plain words: of every 100 people the model would contact at the default 0.5 cutoff, how many buy? And of every 100 real buyers, how many does it find?

Check your answers
Holdout size316 + 61 + 94 + 129 = 600, which is 20% of 3,000
Actual buyers94 + 129 = 223, and 223 / 600 = 0.3717: the same 37.2% as the full data, because the split was stratified
Accuracy(129 + 316) / 600 = 445 / 600 = 0.7417
"Nobody buys" accuracy377 / 600 = 0.6283, from getting every non-buyer right and every buyer wrong
Precision129 / (129 + 61) = 129 / 190 = 0.6789
Recall129 / (129 + 94) = 129 / 223 = 0.5785

So: of every 100 people contacted at the 0.5 cutoff, about 68 buy and 32 are wasted sends. Of every 100 real buyers, the model finds about 58 and misses 42. The model beats the lazy baseline by eleven points of accuracy, but accuracy hides that trade entirely. It is one number for two different mistakes. Fig. 2.5d, under this exercise, draws both sets of four boxes.

The ROC-AUC of 0.80 says the ranking is good. The cutoff decides where along that ranking you stop contacting people, and the lab moves it from 0.50 to 0.35, which trades some precision for more recall at $9 per contact and $24 per conversion.

On this synthetic data buyers are 37% of visitors, so "nobody buys" scores only 63%. On CartGenius's real 1.8% conversion rate it would score 98.2%, which is the trap the next brain power sets.

Here are the four counts drawn, beside the four counts of the laziest possible model on the same 600 people.

1 THE MODEL AT THE 0.5 LINE: 600 HOLDOUT VISITORS predicted NO predicted YES did not buy (377) bought (223) 316 correct no 61 wasted sends 94 missed buyers 129 found buyers accuracy = (316 + 129) ÷ 600 = 0.742 2 precision = 129 ÷ (129 + 61) = 0.679: of 100 contacted, 68 buy recall = 129 ÷ (129 + 94) = 0.578: of 100 buyers, 58 found a wasted send costs $9; a missed buyer is $24 not earned 3 "NOBODY BUYS" ON THE SAME 600 predicted NO predicted YES did not buy (377) bought (223) 377 correct no 0 wasted sends 223 missed buyers 0 found buyers accuracy = 377 ÷ 600 = 0.628: only 11 points behind recall = 0 ÷ 223 = 0: finds nobody, worth nothing on CartGenius's real 1.8% buyer rate: accuracy 0.982 ROC-AUC of this model: 0.5, a coin flip accuracy is one number for two different mistakes; AUC scores the ranking, and the lab prices each mistake
Fig. 2.5d — The four counts from the printed confusion matrix, and the same four for a model that says nobody buys. Accuracy drops only from 0.742 to 0.628 while recall drops from 0.578 to zero, and on CartGenius's real 1.8% buyer rate the do-nothing model would score 0.982. Counts from the terminal output above; every other number is computed from them.
  1. The four boxes. scikit-learn prints truth in rows and prediction in columns, so 316 non-buyers were correctly left alone, 61 non-buyers were contacted for nothing, 94 buyers were missed, and 129 buyers were found. Every metric on this page is some ratio of these four counts.
  2. What accuracy hides. 445 of 600 right is 0.742. But the two mistakes cost different money: a wasted send is $9 out, a missed buyer is $24 not earned. Precision counts the first (68 of every 100 contacted buy), recall the second (58 of every 100 buyers are found), and accuracy averages them away into one number.
  3. The lazy model. Predict "no" for everyone: 377 right, 223 missed, accuracy 0.628, recall 0, and an AUC of 0.5 because it ranks nobody above anybody. Move to CartGenius's real world, where 98.2% do not buy, and the same useless model scores 0.982. That is the trap the brain power below sets.
🧠 Brain power

Before reading on: Elena's fraud-team colleague brags that his model is "98.2% accurate." Given what you know about CartGenius's 1.8% conversion rate, what's the cheapest possible model that hits 98.2% accuracy on that distribution — and what would it be worth?

Reveal the answer

return False. On a 1.8%-positive distribution, predicting "nobody ever buys" is 98.2% accurate and 100% useless — it identifies zero buyers and would have Elena mail no one. Accuracy rewards agreeing with the majority class; it says nothing about whether the model can rank the rare positives above the negatives. That's what ROC-AUC measures: the probability that a random buyer scores above a random non-buyer. The do-nothing model gets AUC 0.5 — a coin flip — no matter how "accurate" it is.

The accuracy trap, on the record

Elena will judge the buyer model by a number. If that number is accuracy, a model that predicts "nobody buys" scores 98.2%, because 98.2% of users do not buy. This is the point where the story nearly goes wrong, so run it before believing it.

Don't take the brain-power answer on faith — run it. Rare-positive data, one lazy model, one real one:

Step-by-step: what accuracy_trap.py does, in plain English
  1. Import the pieces: a synthetic dataset maker, DummyClassifier, LogisticRegression, two metrics, a splitter, make_pipeline and the scaler.
  2. Build 10,000 rows with 12 features where about 98% of the labels are 0, using weights=[0.98], plus a little label noise. This is CartGenius-shaped imbalance.
  3. Split 70/30 with stratification, and print the real positive rate, which comes out at 2.3%.
  4. Fit the lazy model: DummyClassifier(strategy="most_frequent") always predicts the commonest class, which here is 0.
  5. Fit the real model: scale, then logistic regression, in one pipeline.
  6. For each model, compute accuracy from the hard 0/1 predictions and ROC-AUC from the class-1 probabilities, and print both side by side.
  7. Read the two lines: the same accuracy to within a tenth of a point, and an AUC of 0.500 (a coin flip) against 0.851.
accuracy_trap.pyruns offline
# pip install "scikit-learn>=1.9,<2"   # verified Aug 2026
import numpy as np
from sklearn.datasets import make_classification
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

# ~2% positives — CartGenius-shaped imbalance
X, y = make_classification(n_samples=10_000, n_features=12, weights=[0.98],
                           flip_y=0.005, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
print(f"positive rate: {y.mean():.1%}")

lazy = DummyClassifier(strategy="most_frequent").fit(X_tr, y_tr)
real = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).fit(X_tr, y_tr)

for name, model in [("always-predict-no", lazy), ("logistic regression", real)]:
    acc = accuracy_score(y_te, model.predict(X_te))
    auc = roc_auc_score(y_te, model.predict_proba(X_te)[:, 1])
    print(f"{name:>20s}:  accuracy={acc:.3f}   ROC-AUC={auc:.3f}")

# positive rate: 2.3%
#    always-predict-no:  accuracy=0.977   ROC-AUC=0.500
#  logistic regression:  accuracy=0.978   ROC-AUC=0.851

Both models are "97.8% accurate." One is a coin flip; the other separates buyers from non-buyers 85% of the time. On imbalanced problems, accuracy is a vanity metric — report ROC-AUC (or PR-AUC when positives are vanishingly rare, since ROC-AUC can still look rosy while precision is terrible), and choose your operating threshold from business costs, which is exactly what the lab does.

Decision table: which linear tool, when (Aug 2026)
OptionChoose whenAvoid whenNotes
LinearRegressionQuick baseline; few, clean, uncorrelated featuresMany/correlated features — weights swing wildlyNo leash at all; rarely shipped as-is
Ridge (L2)Default regressor; correlated features; you want every signal kept but calmedYou need feature selection or a sparse storyα tunes the leash; stable, boring, good
Lasso (L1)Wide feature sets where you suspect most are noise; interpretability is a deliverableGroups of correlated features (it picks one arbitrarily, drops the rest)Zeroed weights = free feature audit
ElasticNetWant sparsity and correlated-group stabilitySmall feature sets — needless extra knobBlend ratio + strength, both cross-validated
LogisticRegressionProbabilities to rank/budget against; µs-latency scoring; coefficients stakeholders can readStrong nonlinear feature interactions dominateIn sklearn ≥1.8: C + l1_ratio, not penalty=
Gradient-boosted treesTabular accuracy is the only KPI and interactions are gnarlyBefore you've established a linear baseline to beatModule 03 — earn the complexity first

Missing data has a taxonomy — and it changes your fix

Before the model sees a session, something has to fill the gaps left by closed tabs and failed tracking pixels. How you fill them encodes a belief about why they are missing, and a wrong belief quietly biases the buyer model. This is the last production detail before the lab.

That innocent SimpleImputer encodes an assumption about why the data is missing. Get the mechanism wrong and imputation quietly biases the model:

MCAR: CartValue the tracking pixel fails at random $212 $48 blank $150 $97 $263 $31 blank $188 $120 1 139 of 3,000 blank, no pattern fix: fill with the median, $147 MAR: gaps follow DeviceType mobile users skip the optional field blank Mobile $76 Desktop blank Mobile $140 Desktop $205 Tablet $52 Mobile $99 Desktop blank Mobile blank Mobile $183 Desktop 2 the blanks are the Mobile rows fix: fill per device + a was-missing flag MNAR: gaps because of the value high earners skip the income question blank blank blank $95K $82K $71K $64K $58K $49K $41K 3 top three are blank the median $64K guesses far too low fix: "declined" is itself a signal
Fig. 2.5e — Three columns with gaps, one per mechanism. Left: the blank CartValues of cartgenius_pipeline.py, missing at random. Middle: blanks that line up with DeviceType, something you can see. Right: blanks that line up with the missing value itself. The ten example rows in each column are made up to show the pattern; the 139 blanks and the $147 median are from the fitted pipeline.
  1. MCAR. Look down the column and the gaps land anywhere: a failed pixel does not care who the visitor was. Filling each gap with the median, $147, adds no bias, because the rows with gaps are a fair sample of all rows. This is the case in the code above, and SimpleImputer is the right tool.
  2. MAR. Cover the value column and read the device tags: nearly every gap is a Mobile row. The gap is explained by something you can see, so fill it using rows of the same device, and add a 0/1 "was missing" column so the model can learn that Mobile-with-a-gap behaves differently from Mobile-with-a-value.
  3. MNAR. The gaps are the highest incomes, so the reason for the gap is the value you cannot see. No fill computed from the visible rows can recover it; the median would guess $64K for people earning far more. Treat "declined to answer" as its own signal, and say so in the write-up.
MCAR / MAR / MNAR — the three missingness mechanisms
TypeMeaningCartGenius exampleStrategy
MCARMissing Completely At Random — no pattern at allTracking pixel randomly fails for 5% of sessionsSimple imputation (median) is fine — our case here
MARMissingness depends on observed variablesMobile users skip optional fields — missingness follows DeviceTypeImpute conditionally on the observed driver, or add a "was-missing" indicator column
MNARMissingness depends on the missing value itselfHigh-income users decline the income question because it's highHardest case: domain expertise, or model the missingness as its own signal

The stack, and why

Before the lab, here is every tool this module leaned on, what you could have picked instead, and the exact moment each switch becomes worth it. Asking “why not X?” of your own stack is half of what an interviewer is checking.

The stack, and why

The one question that decides it: how much explaining and how much accuracy do you need on a table that fits in memory?

What module 02 uses, what else you could use, and when to switch (as of October 2026)
LayerWe useAlternativesWhy this oneSwitch when
Numbers and loopsNumPy 2.5 (sections 03–04)PyTorch, JAX, plain PythonFour lines of array maths show gradient descent with nothing hidden. Weakness: it runs on one CPU core and you write every derivative yourself.You need automatic derivatives or a GPU, for example a model with more than ~100,000 parameters (module 04).
Tablespandas 3Polars, DuckDBEvery tutorial and every colleague's code uses it, and scikit-learn takes it directly. Weakness: it is single-threaded and loads the whole table into memory.The table no longer fits in RAM or a group-by takes minutes: roughly 10 million rows and up.
Model libraryscikit-learn 1.9statsmodels, XGBoost / LightGBM, PyTorchOne consistent fit / predict shape for dozens of models, plus the Pipeline tools. Weakness: no GPU, and no p-values or confidence intervals on coefficients.You must report p-values to a regulator (statsmodels), or the table has strong feature interactions (trees, module 03).
Model familyLogistic regression and RidgeGradient-boosted trees, small neural netsFast, hard to break, and each coefficient is a sentence Elena's team can read. Weakness: it only draws straight boundaries.A boosted-tree model beats it by more than ~0.02 AUC on the same holdout and nobody needs to read coefficients.
Cleaning gluePipeline + ColumnTransformerHand-written pandas functions, feature-engine, a feature store such as FeastLearns its statistics only inside each fold, so tests stay honest, and it saves as one object. Weakness: awkward when a feature needs a join with another table.Features come from several tables or live services: more than ~20 shared features across teams justifies a feature store.
ScoreROC-AUC, then a profit-based thresholdAccuracy, PR-AUC, log lossAUC compares ranking quality without picking a cut-off; the profit dial then chooses one. Weakness: it hides how well calibrated the probabilities are.Buyers are under ~5% of visitors: use PR-AUC. You need honest probabilities (not just a ranking): add log loss and a calibration check.
Saving and servingA plain Python function over the fitted Pipeline (joblib to save it)FastAPI service, ONNX Runtime, MLflow model registryZero extra moving parts while you learn. Weakness: joblib files break across library versions and only Python can read them.A non-Python service must call the model, or you need versioned rollbacks: wrap it in FastAPI and register it in MLflow.

For a table of a few thousand rows that people must trust, NumPy, pandas, scikit-learn and a Pipeline are the boring right answer; move up only when a number in the last column is crossed.

06 · Under the hoodThe Math, If You Want It

Elena's two models exist and have been scored: an AUC of 0.80 for who buys, a mean error of $16.95 for how much. Nothing below changes that code. What is left is the why behind each choice: why the error is squared, where the two gradient lines came from, why the classifier trains on log-loss rather than squared error, and what C really turns. These are the questions an interviewer asks to find out whether you understood section 03 or copied it.

Everything above works without opening these. But each one answers a "why this formula and not another?" that interviews love.

1 WHY SQUARE THE MISS 2² = 4 miss of 2 10² = 100 miss of 10 5× the miss, 25× the cost +10 and −10: unsquared → 0 squared → 200 big misses dominate, so the line must stay close to every point 2 THE SLOPE ON TWO ROWS (b held at 0) MSE ↑ 0 5 10 15 20 w, how steeply the fitted line rises → w = 0: MSE 1,073 gradient here: −206 per unit of w downhill is to the right curvature = 2² + 4² = 20 (the two minutes values, squared) 3 safe stride: η < 2 ÷ 20 = 0.1 η = 0.05 → w = 10.3: the bottom η = 0.5 → w = 103, MSE 85,945 w = 10.3: MSE 12.1
Fig. 2.5f — The two facts the derivations below rest on. Left: squaring makes a miss of 10 cost 25 times a miss of 2 and stops misses of opposite sign cancelling. Right: the error as a curve over w for the two rows of the BE-the-gradient-step exercise (2 min, $25 and 4 min, $39) with b held at 0; the slope at w = 0 is −206, the curvature is 20, and the safe stride is anything below 2 ÷ 20. Values computed from those two rows; the exercise moved b as well, which is why it landed at 15.3 rather than 12.1.
  1. Why square. A miss of +10 and a miss of −10 add to zero, so an unsquared total would call a line perfect while it is wrong twice. Squared, they add to 200. Squaring also makes big misses matter far more than small ones, 100 against 4, so the line is pulled toward every point, and it gives a smooth curve with a slope everywhere, which the walker needs.
  2. The slope. At w = 0 the curve falls at 206 units of error per unit of w. That is exactly grad_w from the exercise: (2 ÷ n) times the sum of residual times minutes. Negative means downhill is to the right, so the update w − η × (−206) moves w up. The slope is steep here because the misses, −25 and −39, are big and the minutes multiply into it.
  3. The safe stride. How sharply the curve bends is its curvature, 20, and it is the sum of the squared minutes values, 2² + 4². A stride η below 2 ÷ 20 = 0.1 always lands lower; η = 0.05 lands on the bottom in one step, η = 0.5 lands at w = 103 with an error eighty times the starting one. Replace minutes by cart values in the hundreds and the curvature is in the tens of thousands, which is the rule the derivation below states.
Mean squared error — and why we square

MSE = (1/N) · Σᵢ (yᵢ − ŷᵢ)² — average, over all N samples, of the squared gap between actual value yᵢ and prediction ŷᵢ.

Why square, not just sum the errors? An error of +10 on user A and −10 on user B would cancel to zero — the model would congratulate itself while being wrong twice. Why square, not absolute value? Two reasons: squaring punishes big misses disproportionately (an error of 10 costs 100, an error of 2 costs only 4, the two bars of Fig. 2.5f, marker 1 — the line is forced to stay close to all points), and the square is smoothly differentiable everywhere, so the gradient always exists. Absolute error (MAE) is a legitimate loss too — it optimizes the median rather than the mean and shrugs at outliers — which is exactly why we report MAE in dollars for the spend model even though we train on squared error.

The gradient descent update rule, derived

The update you implemented: w ← w − η · ∂MSE/∂w, where η is the learning rate (step size) and ∂MSE/∂w is the partial derivative — the slope (marker 2 in Fig. 2.5f) of the error surface along the w axis, i.e. "if I nudge w up a hair, how does the error move?"

For ŷ = w·x + b, chain rule on MSE = (1/N)·Σ(ŷᵢ − yᵢ)² gives:

∂MSE/∂w = (2/N) · Σᵢ (ŷᵢ − yᵢ) · xᵢ  and  ∂MSE/∂b = (2/N) · Σᵢ (ŷᵢ − yᵢ)

— which are, character for character, the lines grad_w = (2/n) * (err @ minutes) and grad_b = (2/n) * err.sum() from section 03. The minus sign in the update is the entire "descent": positive slope means uphill-to-the-right (in Fig. 2.5f the slope at w = 0 is −206, so downhill is to the right), so we step left, and vice versa.

Note the xᵢ multiplier in ∂MSE/∂w — gradients scale with feature values, and the curvature scales with xᵢ².

That is the mathematical root of section 04's explosion: mean(x²) ≈ 30,000 for cart value made its axis of the bowl ~1,000× steeper, and the stability condition η < 2/curvature was violated.

The sigmoid and log-loss — why not MSE for classification

σ(z) = 1 / (1 + e⁻ᶻ). Sanity checks: z = 0 → e⁰ = 1 → σ = 1/2 (coin flip); z → +∞ → e⁻ᶻ → 0 → σ → 1 (certain buy); z → −∞ → e⁻ᶻ → ∞ → σ → 0 (certain no-buy). Smooth, monotone, and its derivative has the gift-wrapped form σ′ = σ·(1 − σ) — cheap to compute during training.

Logistic regression trains not on MSE but on log-loss (binary cross-entropy):

L = −(1/N) · Σᵢ [ yᵢ·ln(pᵢ) + (1 − yᵢ)·ln(1 − pᵢ) ]

where pᵢ = σ(zᵢ) is the predicted probability and yᵢ ∈ {0, 1} the truth. Per sample only one term survives: if yᵢ = 1 the cost is −ln(pᵢ) — near zero when pᵢ ≈ 1, exploding toward ∞ as pᵢ → 0.

Confidently wrong is punished without bound; MSE would cap that punishment at 1.

The deeper reason: MSE wrapped around a sigmoid produces a lumpy, non-convex error surface where the hiker can get stranded in a dent, while log-loss + sigmoid is convex — one valley, so gradient descent's found minimum is the minimum.

Before you compute anything, look at what the two losses charge. Fig. 2.5g draws both curves for a visitor who did not buy.

ONE VISITOR WHO DID NOT BUY: WHAT EACH LOSS CHARGES FOR A PREDICTION p cost predicted probability of buying, p → 0 0.5 0.9 1 1 3 7 squared error p²: caps at 1 2 0.5 → 0.69 0.9 → 2.30 0.99 → 4.61 0.999 → 6.91 1 log-loss −ln(1 − p): no ceiling 3 0.5: accuracy sees no difference between 0.51 and 0.999 a visitor who did NOT buy, predicted p: p = 0.5 → log-loss 0.69, squared 0.25 p = 0.9 → 2.30, squared 0.81 p = 0.99 → 4.61, squared 0.98 p = 0.999 → 6.91, squared 1.00 p = 1.0 → infinity, squared 1 log-loss never stops charging; squared error stops at 1
Fig. 2.5g — What each loss charges a non-buyer's prediction. The red curve is log-loss, −ln(1 − p): 0.69 at p = 0.5, 2.30 at 0.9, 6.91 at 0.999 and infinite at 1. The grey curve is squared error, p², which can never charge more than 1. Values computed from the two formulas.
  1. No ceiling. For a visitor who did not buy, log-loss charges −ln(1 − p), and 1 − p shrinks toward zero as the prediction grows confident, so the charge climbs without limit: 2.30 at 0.9, 4.61 at 0.99, 6.91 at 0.999. A confident miss dominates the total, which is what the exercise below makes you feel by hand.
  2. The cap. Squared error charges p², so the worst possible miss, p = 1, costs exactly 1. It can barely tell a 0.999 miss from a 0.95 miss, so the walker has little reason to fix confident misses first. That is why logistic regression is trained on log-loss and not on squared error.
  3. The 0.5 line. Accuracy only asks which side of 0.5 a prediction falls on. Every non-buyer predicted above 0.5 is one error, whether at 0.51 or 0.999, so accuracy cannot see confidence at all. That is the metric the accuracy trap in section 05 was about.
Sharpen your pencil

Compute log-loss once by hand and the phrase "confidently wrong is punished without bound" stops being a slogan. Three visitors, three predicted probabilities, three outcomes. The logarithms you need are given, so no calculator is required.

Log-loss for one visitor−ln(p) if they bought; −ln(1 − p) if they did not. Then average over visitors
Natural logs you will needln(0.90) = −0.1054   ln(0.80) = −0.2231   ln(0.05) = −2.9957   ln(0.40) = −0.9163
Squared error for one visitor(p − y)², where y is 1 for bought and 0 for did not
Visitor A: p = 0.90, bought
Visitor B: p = 0.20, did not buy
Visitor C: p = 0.95, did not buy
Mean log-loss over A, B, C
Mean squared error over A, B, C
Accuracy at a 0.5 cutoff

Work to four decimal places. Then answer: what share of the total log-loss does visitor C carry alone? And if C's prediction had been 0.60 instead of 0.95, what changes in each of the three metrics?

Check your answers
Visitor A: p = 0.90, bought−ln(0.90) = 0.1054
Visitor B: p = 0.20, did not buy−ln(1 − 0.20) = −ln(0.80) = 0.2231
Visitor C: p = 0.95, did not buy−ln(1 − 0.95) = −ln(0.05) = 2.9957
Mean log-loss(0.1054 + 0.2231 + 2.9957) / 3 = 3.3242 / 3 = 1.1081
Mean squared error(0.01 + 0.04 + 0.9025) / 3 = 0.9525 / 3 = 0.3175
Accuracy at 0.5A right, B right, C wrong: 2 / 3 = 0.6667

Visitor C carries 2.9957 / 3.3242 = 90.1% of the total. One confident miss costs 28 times what the confident hit on A cost.

Now move C to 0.60. The log-loss term becomes −ln(0.40) = 0.9163, and the mean falls from 1.1081 to (0.1054 + 0.2231 + 0.9163) / 3 = 0.4149. The squared term falls from 0.9025 to 0.36, and the mean from 0.3175 to 0.1367. Accuracy does not move at all: 0.60 is still above the cutoff, so C is still wrong, and the score stays at 0.6667.

That is the whole argument for the loss. Accuracy cannot see the difference between a 0.95 miss and a 0.60 miss. Squared error sees a 2.5× difference and then stops: no miss can ever cost more than 1. Log-loss sees a 3.3× difference and keeps going.

At p = 0.999 the same miss costs 6.9078, and at p = 1.0 it costs infinity. The optimizer follows the slope of this surface, the red curve of Fig. 2.5g (marker 1), so it spends its effort on the confident misses first. That is exactly the behaviour you want from a model whose probabilities have to be trusted.

Regularization penalties — and sklearn's upside-down C

Ridge minimizes MSE + λ·Σⱼ wⱼ²; Lasso minimizes MSE + λ·Σⱼ |wⱼ|. λ (lambda) prices the leash: λ = 0 is no leash, λ → ∞ drags every weight to zero. The penalty-as-budget picture in Fig. 2.4 is the same statement in constrained form: minimizing loss subject to Σ|wⱼ| ≤ t (a diamond) or Σwⱼ² ≤ t (a disc).

The diamond's corners sit on the axes — where a coordinate is exactly zero — and corners are "sticky": an expanding contour is far more likely to first touch a protruding corner than any given flank point.

That is the entire, honest reason L1 gives sparsity and L2 doesn't.

Two gotchas. LogisticRegression exposes C = 1/λ — inverse regularization, so C = 0.01 is a short leash and C = 100 is practically off-leash; people burn hours tuning it backwards. And penalties punish weight magnitudes, which only compare fairly across features on a common scale — one more job StandardScaler was quietly doing for you.

There are no dumb questions

My model hit 95% on training data but 62% on test. What happened?
Overfitting — the model memorized training noise instead of learning signal; the 33-point gap is the tell. In order of preference: add regularization (shrink C, or raise α), cross-validate to catch it early, get more data, and prune noisy features. It's the ML version of hardcoding until CI passes: the green build (train score) was never the thing that mattered.
Why would I ever want Lasso to zero out a feature?
Because a zeroed weight is a free audit finding: "these 35 of your 50 features carry no signal." The surviving model is smaller, faster, and — the part Elena's team actually cares about — explainable in one slide. Feature selection you'd otherwise do by hand falls out of the optimizer.
Why impute the median instead of dropping rows — or using the mean?
Dropping rows with any NaN throws away ~10% of Elena's data and, unless missingness is MCAR, biases what remains (imagine deleting mostly mobile users). The mean is hostage to outliers — one $4,000 cart drags it far from typical; the median doesn't budge. And because the imputer sits inside the Pipeline, its statistics come from training data only.
Is logistic regression still worth my time in 2026, honestly?
Yes, on the market's own testimony: the job-market research lists classical ML fundamentals as "still a baseline expectation" despite the GenAI wave, and interviewers use exactly these questions to check depth. In production it earns its keep too: microsecond scoring, well-calibrated probabilities out of the box, and coefficients that survive a compliance review. Module 03's gradient-boosted trees usually beat it on raw tabular accuracy — but you need this baseline to prove that, and to justify the added complexity.
Why does preprocessing live inside the pipeline object?
Three compounding wins: no leakage (statistics learned per training fold), no train/serve skew (inference replays the identical transform — the JSON handler needed zero preprocessing code), and one artifact to version and deploy — joblib.dump(pipeline) ships imputer, scaler, encoder, and model as a unit.
Boardroom translation

The elevator sentence: "Propensity scores let marketing spend follow probability instead of intuition." Today CartGenius pays $800K a quarter to reach 2 million people for 1.8% conversion — a blast that our holdout economics show can literally lose money once send costs are priced in.

The model ranks every user by probability of buying: on held-out data, the top 30% of the ranking captures 57% of all eventual buyers, and the top half captures 78%.

Same budget, aimed: fewer sends, more conversions per dollar, and a dial (the threshold) that finance can set from the cost matrix rather than from vibes — in our simulation, tuning that one dial swung quarterly campaign profit from −$72 to +$4,659 per 1,800 users reached.

And because the model is a linear one, the "why" is printable: bigger carts, longer sessions, email referrals, returning visitors — each with a signed, quantified weight Elena can read to her board.

07 · The labThe Profit Dial

The model exists. Elena's real question was never "what is the probability"; it was "whom do we email". That is a threshold, and a threshold is a business decision with a price on each kind of mistake. The lab sets it with money.

Fig. 2.3 called the threshold "a dial you set." Time to set it with money. Finance prices each premium outreach at $9 all-in (incentive + send + list-fatigue cost) and values a converted contact at $24 net margin. Here's the worked 80%: a threshold sweep that turns predicted probabilities into expected campaign profit.

Step-by-step: what threshold_picker.py does, in plain English
  1. Import numpy, the model, the splitter and Pipeline, and reuse the data generator and the preprocessor from section 05's file, which must sit in the same folder.
  2. Set the two business numbers: $9 to contact someone, and $24 of margin when a contacted person buys.
  3. Generate 6,000 visitors with a fresh seed, and split 70/30 with stratification.
  4. Chain the preprocessor and a LogisticRegression, fit on the training rows, and take one buy probability per holdout visitor from column 1 of predict_proba.
  5. expected_profit(threshold): mark every holdout visitor whose probability clears the threshold as contacted, count how many of them really bought using the true labels, and return margin × conversions minus cost × contacts.
  6. Sweep thresholds from 0.05 to 0.95 in steps of 0.05, compute the profit at each, and find the threshold with the largest profit.
  7. Compute the blast-everyone baseline: the same formula with every holdout visitor contacted.
  8. Print the baseline, the profit at the default 0.5 cutoff, and the best threshold with its profit.
threshold_picker.pyruns offline
# pip install "scikit-learn>=1.9,<2" "pandas>=3,<4"   # verified Aug 2026
# Prereq: cartgenius_pipeline.py (section 05) saved in the same folder.
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline

from cartgenius_pipeline import generate_ecommerce_data, make_preprocessor

COST_PER_CONTACT = 9.0        # incentive + send + list-fatigue, priced by finance
MARGIN_PER_CONVERSION = 24.0  # net margin of a converted contact

df = generate_ecommerce_data(n_samples=6000, seed=7)
X = df.drop(columns=["Purchased", "SpendAmount"])
y = df["Purchased"]
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.30, random_state=7, stratify=y)

clf = Pipeline([("prep", make_preprocessor()),
                ("model", LogisticRegression(C=1.0, max_iter=1000, random_state=7))])
clf.fit(X_tr, y_tr)
proba = clf.predict_proba(X_te)[:, 1]

def expected_profit(threshold: float) -> float:
    contacted = proba >= threshold          # who this policy would reach
    conversions = y_te[contacted].sum()     # …and how many of them actually buy
    return MARGIN_PER_CONVERSION * conversions - COST_PER_CONTACT * contacted.sum()

thresholds = np.round(np.arange(0.05, 0.96, 0.05), 2)
profits = np.array([expected_profit(t) for t in thresholds])
best = thresholds[profits.argmax()]

blast = MARGIN_PER_CONVERSION * y_te.sum() - COST_PER_CONTACT * len(y_te)
print(f"blast-everyone baseline : ${blast:,.0f}")
print(f"default threshold 0.50  : ${expected_profit(0.50):,.0f}")
print(f"best threshold {best:.2f}     : ${profits.max():,.0f}")

# blast-everyone baseline : $-72        ← spray-and-pray LOSES money
# default threshold 0.50  : $4,347
# best threshold 0.35     : $4,659      ← theory says cost/margin = 9/24 = 0.375 ✓

Here is the whole sweep as a curve, with the three printed numbers marked on it.

THE PROFIT AT EVERY CUTOFF: $24 PER SALE MINUS $9 PER CONTACT $0 $2,500 $5,000 0 0.25 0.5 0.75 1.0 cutoff: contact everyone whose p is at least this → p* = 9 ÷ 24 = 0.375 1 2 0.35: $4,659 3 0.50: $4,347 profit = $24 × sales − $9 × contacts, on the 1,800 holdout visitors (672 of them buyers) every dot is one line of the sweep in threshold_picker.py; cut at 0 is the −$72 blast why the best cutoff is near 0.375: a contact costs $9 and returns $24 only if that person buys, so it pays when p × 24 > 9, that is p > 0.375 below 0.35: paying $9 for people who mostly do not buy above 0.35: skipping people who would have paid off blast all: 1,800 × $9 = $16,200 out, 672 × $24 = $16,128 in → −$72
Fig. 2.5h — Expected profit at every cutoff, from threshold_picker.py's own sweep rerun to print all nineteen values. Contacting everyone loses $72; the default 0.50 earns $4,347; the peak is $4,659 at 0.35, next to the break-even p* = 9 ÷ 24 = 0.375.
  1. Blast everyone. A cutoff of 0 contacts all 1,800 holdout visitors at $9 each, $16,200. The 672 who buy return $24 each, $16,128. The campaign loses $72, which is Elena's spray-and-pray in miniature.
  2. The peak. At 0.35 the model contacts 805 people and 496 of them buy: 496 × $24 − 805 × $9 = $4,659. Lower the cutoff and the extra people you add are mostly non-buyers who cost $9; raise it and you skip people whose $24 you would have collected. The best cutoff sits where a contact's expected return, p × $24, just covers its $9 cost, which is p = 0.375.
  3. The default. 0.50 contacts 533 people, 381 buy, $4,347. It is $312 short of the peak, not because the model changed but because 0.5 is a coin-flip cutoff with no dollars in it. The agreement between 0.35 and 0.375 only holds if the people scored 0.4 really buy about 40% of the time; that is calibration, and it is the lab.

Note that the empirically-best dial, 0.35 (marker 2 in Fig. 2.5h), lands right next to the theoretical break-even p* = cost/margin = 0.375, the dashed line in Fig. 2.5h. That agreement is only guaranteed when the model's probabilities are calibrated — when "p = 0.4" events really happen about 40% of the time. Your lab is to verify, and where needed repair, exactly that.

LAB 02 — Calibrated propensity engine with a profit-maximizing threshold

Mission: extend threshold_picker.py into a calibration-audited targeting tool: measure how honest the classifier's probabilities are, calibrate them, and let the cost matrix pick the operating threshold. Fully offline — synthetic data only.

  • Plot a reliability diagram with sklearn.calibration.calibration_curve (10 bins) for the raw model: predicted probability vs observed frequency, with the y = x diagonal for reference; save as calibration_raw.png
  • Wrap the pipeline in CalibratedClassifierCV(estimator, method="isotonic", cv=5), refit, and overlay the calibrated curve on the same axes
  • Report Brier score (brier_score_loss) before and after — calibrated must not be worse, and your README explains what the number measures
  • Re-run the profit sweep on calibrated probabilities and show the profit-optimal threshold now sits within 0.05 of the analytic break-even p* = cost ÷ margin
  • Sensitivity table: optimal threshold and profit for margins $15 / $24 / $60 at fixed $9 cost — one paragraph explaining why the dial moves the way it does
  • README documents: metrics, 3 failure modes you found (e.g. calibration at the probability extremes, threshold instability on small holdouts), and fix iterations

Stretch goal: replace the flat $24 margin with per-user expected margin = 0.3 × the spend predictor's output, and re-derive the optimal policy — now the threshold differs per user. Compare total profit against the flat-margin policy.

08 · Interview radarHow This Shows Up in Interviews

Interview radar

The market research is blunt: despite the GenAI wave, "classical ML remains a baseline expectation" — these five recurring questions are how screens verify you have foundations under the LLM work.

"Explain the bias–variance tradeoff — to a PM."

The real test The "to a PM" is the point — they're grading whether you can teach the idea in plain language, not whether you can recite the decomposition.

Strong answer Bias means the model is too simple to represent the truth: a straight line forced through a curve is wrong everywhere, consistently.

Variance means it is too flexible, so it reshapes itself around each training set's noise — it aces training and flunks production.

Total error is the sum of the two, so you tune model complexity to balance them, and regularization is your variance dial.

You diagnose which one you have from the gap: train and test both bad points to bias, while train far better than test points to variance.

Land it Bonus points for section 04's cousin lesson: know your diagnostics before your remedies.

"My fraud model is 99.2% accurate." Why is the interviewer frowning?

The real test Whether you spot the base-rate trap before you praise the number.

Strong answer Base rates. If fraud is 0.5% of traffic, a model that just does return False scores 99.5% — beating this one without catching a single fraud. So report metrics that survive imbalance instead: ROC-AUC for ranking quality, and PR-AUC when positives are very rare. Then pick the threshold from the cost asymmetry, because a missed fraud costs about 100× what a false alarm does.

Land it Citing a dummy-classifier baseline, class weights, and a profit/cost curve — your lab — reads as "has shipped this."

"L1 vs L2 — when and why?"

Strong answer Draw Fig. 2.4 from memory: both penalties cap the weight budget, and the shape of the cap decides the behavior.

L1's constraint region is a diamond whose corners sit on the axes, so solutions land on the corners and features die — that's sparsity, which gives you built-in feature selection.

L2's region is a circle with no corners, so all weights shrink smoothly instead — that's stability, especially with correlated features, where Lasso would arbitrarily keep one of a correlated group and drop the rest. When you want both behaviors, use ElasticNet.

Land it Currency flex: sklearn ≥ 1.8 expresses this via l1_ratio, with penalty= deprecated.

"Your logistic model gives CartValue a coefficient of +1.02. Interpret it."

Strong answer Coefficients act on log-odds, so +1.02 means each standard deviation of CartValue — the features were standardized, and saying so is part of the answer — multiplies the odds of purchase by e1.02 ≈ 2.8×. Then add the caveats that mark seniority:

  • Units — the effect is per unit of the scaled feature, not per raw dollar in the cart
  • Correlation — correlated features share credit unstably, so no single coefficient is trustworthy on its own
  • Association, not causation — the model learned that big carts go with buying, not that big carts cause it

Land it The causal caveat is the closer: raising cart values by fiat won't mint buyers.

"Marketing wants buy-probability scoring at 5,000 req/s, p99 < 20 ms. Sketch it. Would you use an LLM?"

The real test System design plus judgment — knowing when not to reach for the shiny tool is what's being graded.

Strong answer No LLM in the hot path. This is structured-feature scoring, where a fitted sklearn pipeline predicts in microseconds for roughly zero marginal cost, is deterministic, and explains itself; an LLM would add 100–1000× the latency and cost for less accuracy on tabular signals.

Then the sketch: the pipeline artifact is versioned (joblib/MLflow) and served behind a stateless service, features are fetched from a low-latency store, calibration and drift are monitored, and the decision threshold is owned by config, not code, so the business can move it without a redeploy.

Land it LLMs still earn a seat — but offline, deriving features from support-ticket text that feed this same model.

Quick reference — Regression and classification

Linear regression
Predicts a number. Fits the line that makes the squared errors smallest (Fig. 2.1, the dashed gaps).
Logistic regression
Predicts a probability. Same idea, squeezed through a sigmoid so the answer lands between 0 and 1.
residual
Actual minus predicted — the part the model got wrong. Looking at residuals tells you more than any single accuracy score.
gradient descent
Take the slope, step downhill, repeat (Fig. 2.2b, panel 2). This one mechanism trains almost every model in this course.
learning rate
How big each step is. Too large and it overshoots forever; too small and it never arrives. Choose it with a short sweep: try values a few times apart and keep the largest whose loss falls smoothly (Fig. 2.4h).
Regularization
Penalising complexity to stop overfitting. Ridge (L2) shrinks weights; Lasso (L1) drives some to exactly zero, which selects features.
data leakage
Information from the future, or from the test set, reaching the model during training. It produces excellent scores and a useless model — and a Pipeline is what prevents it.
standard deviation
The typical distance of a value from its column's average: square the distances, average the squares, take the square root. Page views 2, 4 and 3 give 0.816 (Fig. 2.4f).
training set and test set
The rows the model learns from, and the rows held back to score it as if they were next week's visitors: 2,400 and 600 here.
overfitting and underfitting
Training score far above test score means memorised: a tree with no depth limit scores AUC 1.000 against 0.616. Both scores low and equal means learned nothing: DeviceType alone scores 0.52 and 0.52 (Fig. 2.5i).
target leakage
A feature that only exists after the outcome, such as SpendAmount for "will they buy?". It scores a perfect test AUC and is empty at decision time (Fig. 2.5j).
stack decision
Pick the simplest tool whose switch-when condition you have not crossed; write the condition down so the switch is a decision, not a drift.

09 · RecapWhat You Can Do Now

  • You can implement gradient descent from scratch in numpy and narrate every line — forward pass, residuals, gradients, update — without notes.
  • You can diagnose divergence (loss → inf/NaN), name its cause (feature-scale curvature vs learning rate), and fix it with standardization.
  • You can scale a column by hand (average, distances, squares, variance, square root) and show with numbers why a smaller learning rate is no substitute for scaling.
  • You can build a leakage-proof sklearn Pipeline + ColumnTransformer over mixed numeric/categorical data with missing values, and defend why each transform lives inside it.
  • You can tell overfitting from underfitting by comparing training and test scores, and spot a leaked column by asking whether it exists at the moment of the decision.
  • You can choose and justify metrics for imbalanced classification — and demolish an accuracy claim with a dummy-classifier baseline.
  • You can read logistic coefficients as log-odds, convert them to odds ratios, and translate them into a stakeholder sentence.
  • You can pick Ridge, Lasso, or ElasticNet from the constraint-geometry argument, not from folklore.
  • You can classify missingness as MCAR/MAR/MNAR and match the imputation strategy to the mechanism.
  • You can turn probabilities into decisions: calibrate a classifier and set its threshold from a cost matrix to maximize expected profit.
🧠 Flex your memory

From this module: on a blank page, write the gradient descent update rule for w and b, annotate every symbol in words, and then explain — in terms of the contour picture (Fig. 2.2, and its canyon in Fig. 2.4c) — why an unscaled 0–300 feature breaks it while standardization repairs it.

Reaching back to Module 01: this module pinned "scikit-learn>=1.9,<2" rather than floating the latest version. Restate Module 01's argument for pinning the working stack — then name the concrete Exhibit A this module handed you (hint: a parameter that trained yesterday's tutorials now emits FutureWarnings on its way to removal).