▚ The AI Engineer's Field Manual
Module 13 · Act IV — Production & the Business

Recommenders & Forecasting — The Classic Money-Makers

"Predict what they want before they ask. Predict what will happen before it does."

~6 hours Builds on: Modules 02–03 · 08 Tools: numpy · LightGBM · Prophet Job-spec line it unlocks: "classical ML remains a baseline expectation"

01 · The hookTwo Machines That Print Money

The two AI systems that most reliably make money: one that decides what to show each person, and one that predicts what a number will do next.

Field report · ShopStream

"Our homepage shows the same 20 bestsellers to all 2 million users. Meanwhile, Amazon shows every visitor a different page. Our click-through rate is 1.2%. Theirs is 35%. We're leaving an estimated $2.4M a year on the table. I want personalized recommendations on the homepage, the product page, and the cart page by next quarter — every user sees a different page, served in under 100 milliseconds."

— Priya Sharma, VP of Product at "ShopStream"

Before LLMs ate the headlines, two ML systems quietly generated more revenue than everything else combined: recommender systems (what should this user see next?) and time series forecasting (how much of this will we need?). They still do. Amazon's homepage, Netflix's rows, Spotify's Discover Weekly, every retailer's inventory order, every cloud provider's capacity plan — these are recommenders and forecasters, running billions of times a day.

Let's be honest about scope up front: these are deep specializations. Companies employ entire teams for each, and this module will not turn you into one of them.

What it will do is take you to solid working knowledge: you'll build both systems small, understand the production architecture around them, know the 2026 tooling and its traps, and be able to hold the room when either topic comes up in a design review or an interview.

For a senior GenAI engineer, that's the bar that actually gets tested — the market research is blunt that "despite the GenAI wave, classical ML remains a baseline expectation."

You already know this

A recommender is a search engine where the query is the user. You've built search: an index for fast retrieval, a scoring function, business rules on top. Same three layers here — swap the text query for a learned representation of the person. And the retrieval layer is literally Module 08's vector store: embed things, ANN-search them. Same infrastructure, different payload.

A forecaster is capacity planning with a model instead of a spreadsheet. You've eyeballed a traffic dashboard and provisioned servers for the holiday spike; forecasting formalizes exactly that read — trend, cycles, and the part you admit you can't predict.

02 · RecSys: the intuitionThree Flavors, One Funnel

Priya’s memo put one number on the table: 1.2% click-through, because all 2 million ShopStream visitors see the same 20 bestsellers, with about $2.4M a year riding on the gap. We have exactly one raw material to fix it, the click log, and one hard limit, 100 milliseconds per page. So before writing any code we need two answers. Which family of recommender can actually run on nothing but a click log, and what shape must the system take to answer 2 million people inside 100 milliseconds?

Imagine walking into a massive department store with a personal shopping assistant. There are three kinds of assistant, and they map exactly onto the three families of recommendation strategy:

The three recommendation strategies — what signal each one uses, and where each one fails
StrategyThe assistant says…Signal usedWeakness
Collaborative filtering "Customers who bought the same shoes as you also loved this jacket." The user × item interaction matrix (ratings, clicks, purchases). No idea why you liked the shoes — just the pattern. Cold start: useless for brand-new users and brand-new items.
Content-based filtering "You bought running shoes — here are more running products in your size and favorite color." Item attributes (category, brand, price, description) matched to your history. Filter bubble: recommends more of the same, never surprises you.
Hybrid "Based on your purchase and what similar fitness enthusiasts bought, you might love this smartwatch." Both — modern systems learn user and item embeddings jointly from interactions and attributes. Complexity. This is what the big players run, with teams to match.
BE the recommender

Your turn to play the machine. Collaborative filtering has one move: find the people whose past looks most like yours, then copy what they liked. Below are four ShopStream customers and four products, rated 1 to 5. A blank means that person never touched that product. Dev is the customer on the homepage right now.

  1. Ana — shoes 5 · yoga mat 1 · trail jacket 4 · smartwatch 5
  2. Ben — shoes 4 · yoga mat 2 · trail jacket (blank) · smartwatch 4
  3. Cho — shoes 1 · yoga mat 5 · trail jacket 2 · smartwatch (blank)
  4. Dev — shoes 5 · yoga mat 1 · trail jacket ? · smartwatch ?

With a pencil: which of the other three is Dev's closest twin, judged only on the products both of them rated? Which product, the trail jacket or the smartwatch, should the homepage show Dev? Write your reasoning in one line before opening the answer.

Check your answer

Dev has rated two products, shoes and the yoga mat, so those two columns are the only evidence. Compare Dev's pair (5, 1) with each neighbor's pair on the same two products. The standard yardstick is cosine similarity. It is a number from 0 to 1 saying how much two lists of numbers point the same way.

To compute it, multiply matching numbers and add them up, then divide by the length of each list. A list's length is the square root of the sum of its squares, so (5, 1) has length √26, about 5.0990. The table shows all three comparisons, then the two predictions that follow from them.

Dev (5, 1) vs Ana (5, 1)(5·5 + 1·1) / (√26 · √26) = 26 / 26 = 1.0000. Identical taste on the overlap.
Dev (5, 1) vs Ben (4, 2)(5·4 + 1·2) / (√26 · √20) = 22 / 22.8035 = 0.9648. Very close.
Dev (5, 1) vs Cho (1, 5)(5·1 + 1·5) / (√26 · √26) = 10 / 26 = 0.3846. Nearly opposite.
Smartwatch for DevAna said 5 and Ben said 4, weighted by similarity: (1.0·5 + 0.9648·4) / (1.0 + 0.9648) = 8.8592 / 1.9648 = 4.5090
Trail jacket for DevAna said 4 and Cho said 2: (1.0·4 + 0.3846·2) / (1.0 + 0.3846) = 4.7692 / 1.3846 = 3.4445
1 THE OVERLAP — all Dev has rated 2 THE GAPS — a dash means never rated shoes yoga mat trail jacket smartwatch Ana Ben Cho Dev 5 1 4 5 4 2 — 4 1 5 2 — 5 1 3.44 4.51 cosine to Dev 1.0000 0.9648 0.3846 (Dev himself) 3 4 cos(Dev, Ana) = (5·5 + 1·1) ÷ (√26 · √26) = 26 ÷ 26 = 1.0000 cos(Dev, Ben) = (5·4 + 1·2) ÷ (√26 · √20) = 22 ÷ 22.8035 = 0.9648 cos(Dev, Cho) = (5·1 + 1·5) ÷ (√26 · √26) = 10 ÷ 26 = 0.3846 smartwatch = (1.0000×5 + 0.9648×4) ÷ (1.0000 + 0.9648) = 4.5090 trail jacket = (1.0000×4 + 0.3846×2) ÷ (1.0000 + 0.3846) = 3.4445 4.51 beats 3.44, so ShopStream shows Dev the smartwatch.
Fig. 13.0b — The exercise you just did, drawn. Four customers, four products, two blanks per neighbour, and one predicted rating written into the cell it belongs in. (Ratings invented to keep the arithmetic small; every number shown is computed from them.)
  1. The overlap. Dev has touched two products, so the two shaded columns are the entire evidence. Every similarity on this picture is computed from Dev’s pair (5, 1) against each neighbour’s pair on those same two columns. Columns Dev never rated cannot be compared, so they take no part in judging who his twin is.
  2. The gaps. A dash is not a zero and not a bad rating. It means the pair never happened. A real ShopStream grid is about 99.99% dashes, which is why every method on this page is really a method for guessing what belongs in them.
  3. The similarity column. Cosine similarity runs from 0 to 1 and says how much two lists of numbers point the same way. Ana scores 1.0000 because her overlap pair is identical to Dev’s. Ben scores 0.9648, close but not identical. Cho scores 0.3846, because she loves the yoga mat Dev dislikes.
  4. The filled cell. The predicted rating is the neighbours’ ratings averaged, weighted by how similar each neighbour is. Ana counts almost twice as much as Cho. The smartwatch comes out at 4.51 and the trail jacket at 3.44, so the smartwatch is what the homepage shows.

Show Dev the smartwatch. Notice what never happened: nobody looked at what a smartwatch is, what it costs, or whether Dev runs. The verdict came from two numbers in Ana's row. That is the whole strength of collaborative filtering, and its whole weakness. Give Dev zero ratings and every similarity above is undefined, because there is nothing to compare. That is cold start, and section 04 hits it head on.

The from-scratch model in section 03 does the same job a different way. Instead of comparing rows on the spot, it learns a short vector per user and per item ahead of time. The comparison is precomputed. The intuition is unchanged: people with similar histories get similar recommendations.

"Why not just recommend the most popular items? It's one SQL query, it never crashes, and it doesn't need Ana's row."

— a backend lead who has shipped a "Trending now" widget

Popularity is the right first answer, and every serious recommender keeps it. It is the fallback for a brand-new user in section 04. It is also the baseline your model must beat in the lab. If "top sellers in this category, in this country, at this hour" already lifts click-through, ship that. Measure it before building anything else.

The trouble is that popularity is what ShopStream already has. The same 20 bestsellers go to 2 million people, and click-through is 1.2%. Popularity does not know who is looking. The money in personalization comes from the long tail: products Dev wants and most people never would. Dev got the smartwatch because of Ana’s row, marker 4 in Fig. 13.0b, not because watches sell well.

Personalization has an honest downside. It needs history it does not have on day one. It costs a three-stage funnel and a team to run it. Left alone it drifts back toward popularity anyway. You will measure that drift in section 04, where the from-scratch model recommends only 27 of 200 items, 14% of the catalogue, drawn as marker 1 of Fig. 13.2d. Popular-plus-rules is a fine floor and a poor ceiling.

The second thing to internalize is that no serious system scores the whole catalog with one model. Netflix, Amazon, and Spotify all converged on the same multi-stage funnel: a fast, approximate stage cuts 500,000 items to a few hundred candidates; a slower, precise model ranks those; and a final pass applies the business rules that models don't know about.

Catalog · 500,000 items Stage 1 · candidate generation — two-tower embeddings + ANN · ~10 ms ~500 candidates Stage 2 · ranking — GBM / neural scorer, rich user+item features · ~50 ms ~50 scored Stage 3 · re-ranking — diversity, in-stock, margin, already-bought filter · ~5 ms 10 shown to the user — p99 budget ≈ 100 ms end-to-end 1 2 3 4
Fig. 13.1 — The production funnel: each stage trades precision for speed, so the expensive model only ever sees a few hundred items. (Bar widths are illustrative — 500,000 → 10 is a 50,000× cut.)
  1. The catalog. Every item ShopStream could possibly show: 500,000 of them. Nothing in the system is allowed to score all of these at request time, and the three stages below exist entirely to avoid doing so. The block widths shrink down the picture to show how much is thrown away at each step.
  2. Stage 1, candidate generation. A cheap, approximate cut from 500,000 to about 500 in roughly 10 milliseconds. It is cheap because it compares vectors, not features: one lookup in a nearest-neighbour index, the same machinery as Module 08’s document search. It will miss some good items, and that is the price of the speed.
  3. Stage 2, ranking. A slow, feature-rich model scores those 500 and keeps about 50, in roughly 50 milliseconds. This is where the real judgment happens, and it is affordable only because stage 1 already removed 99.9% of the work.
  4. Stage 3, re-ranking. The business rules the model has no idea about: out of stock, already bought, too many of one brand, the margin the buyer negotiated. About 5 milliseconds, and it always runs last, because a rule applied before ranking would just be overruled by the score.

Now the same funnel a second time, with this module's real code in each row. The left column is the small recommender you build in section 03. It has no funnel at all: it scores every item for every user. The middle column is the production version from section 05. If a stage in Fig. 13.1 feels abstract, find its row here.

The file and function names below have not been explained yet, and you are not expected to recognize them. Every one of them appears in full in sections 03 and 05. This table exists so you can come back and see exactly where each stage lives.

Fig. 13.1 again, concretely: each stage as it exists in this module's code and in production
StageIn the from-scratch version (section 03, recsys_svd.py)In the production funnel (section 05)What flows out
Collect interactionssynth_interactions() fakes 6,000 clicks with a long tailEvent logs: views, add-to-carts, purchases, each with a timestampA user × item table that is 99.99% empty
Learn representationsFunkSVD().fit(df): one 20-number vector per user and per itemTwo-tower training, nightly; item vectors written into an ANN indexVectors that put similar tastes near each other
Candidate generationNone. scores_for() scores all 200 items in one matrix–vector productUser tower at request time, then one ANN lookup, about 10 msAbout 500 candidates
Rankingnp.argsort(s)[::-1]: sort by predicted rating, highest firstA gradient-boosted or neural scorer with rich user and item features, about 50 msAbout 50 scored items
Business-rule re-rankingexclude=seen drops what user 42 already ratedDiversity caps, in-stock, margin and freshness rules, about 5 msThe 10 items shown
EvaluationThe coverage@10 audit at the bottom of __main__Temporal holdout NDCG@K and coverage offline; A/B tests on click-through onlineThe number that says which stage to fix
🧠 Brain power

Before reading on: what would happen if you deleted Stage 1 and simply ran the precise ranking model over all 500,000 items for every page load?

Reveal the answer

Do the math: a ranking model with rich features costs roughly 0.1–1 ms per item (feature assembly dominates, not the model). 500,000 items × 0.5 ms ≈ four minutes per pageview, against a 100 ms budget.

The funnel exists because precision costs compute, so you spend it only on items that already survived a cheap filter.

It's the same retrieve-then-rerank shape you built in Module 08's RAG pipeline — coarse ANN retrieval, then an expensive reranker over the shortlist. This pattern shows up wherever a scoring budget meets a large corpus.

The answer to that question is worth drawing, because it is the whole reason the funnel exists.

1 WITH THE FUNNEL — inside Priya’s 100 ms budget 0 10 60 100 ms stage 1 · candidate generation · 500,000 → 500 · 10 ms stage 2 · ranking · 500 → 50 · 50 ms stage 3 · business rules · 50 → 10 · 5 ms 2 total 65 ms, so 35 ms of head-room is left over 3 WITHOUT STAGE 1 — rank all 500,000 items 500,000 items × 0.5 ms of feature assembly each = 250,000 ms = 4 minutes 10 seconds for one page view
Fig. 13.1b — The same three stages as Fig. 13.1, this time drawn on a clock. Stage 1 costs a tenth of the budget and removes 99.9% of the work; ranking everything instead costs 2,500 times the whole budget. (0.5 ms per item is the middle of the 0.1–1 ms range quoted above.)
  1. The budget bar. The whole bar is Priya’s 100 milliseconds, the time a ShopStream page has to come back. Each block is one stage of Fig. 13.1, drawn at its real width in milliseconds, so the picture is a clock rather than a diagram of boxes.
  2. The head-room. 10 plus 50 plus 5 is 65 milliseconds, which leaves 35 milliseconds of dashed empty space for network time, page rendering and a bad day. A design with no head-room is a design that misses its budget the first time traffic doubles.
  3. The runaway bar. Delete stage 1 and the expensive ranker has to touch all 500,000 items. At half a millisecond each that is 250,000 milliseconds, four minutes and ten seconds, for one page view. Drawn at the top bar’s scale this bar would be about 1.1 million pixels long, roughly 290 metres of screen. That is why the cheap stage goes first.

Cut the catalog cheaply.

Rank the shortlist carefully.

Apply the business rules last.

Cut the catalogue cheaply: that is stage 1 in Fig. 13.1, marker 1, where 500,000 items become about 500 in 10 milliseconds. Rank the shortlist carefully: stage 2, marker 2, the expensive model that only ever sees those 500. Apply the business rules last: stage 3, marker 3, where out-of-stock and already-bought are struck out. Fig. 13.1b, marker 3, is why the order can never be swapped: ranking everything first costs 250,000 milliseconds against Priya’s 100.

03 · Build it yourselfMatrix Factorization From Scratch

You have just played the recommender by hand and found Dev a smartwatch by comparing four rows. Priya has 2 million rows and 500,000 products and 100 milliseconds, so comparing rows at request time is finished as an idea. What she needs instead is a short vector per person and a short vector per product, learned once overnight and multiplied at serving time. That is matrix factorisation, and this section builds it from nothing in about forty lines.

The classic collaborative-filtering engine — and still the concept interviews probe — is matrix factorization. Picture the interaction data as one gigantic, mostly-empty spreadsheet: 2M user rows × 500K item columns, with a rating or click wherever a user touched an item.

Maybe 0.01% of cells are filled. The trick: approximate that monster as the product of two skinny matrices — one row of K numbers per user (their taste vector), one row of K numbers per item (its DNA). Predicting any empty cell then costs one dot product.

R · ratings (2M × 500K) 4 1 5 3 2 5 ? 99.99% of cells empty ≈ U (2M × K) K ≈ 64 × Vᵀ (K × 500K) row · column = one cell of R user u's taste vector · item i's DNA
Fig. 13.2 — Factorization compresses a 10¹²-cell sparse matrix into two dense matrices; predicting any missing rating is one K-dimensional dot product between a user row and an item column.

Nobody hand-labels those K dimensions — the model discovers them. In a movie recommender one latent factor might end up meaning "art-house vs blockbuster", another "gore tolerance".

You never name them; you just learn them by gradient descent so that predicted ratings match observed ones.

Here's the whole algorithm, from scratch, in a file you can run right now — including one honest touch most tutorials skip: the synthetic catalog has a realistic long tail, where a few head items get most of the traffic. Remember that; it detonates in the next section.

The squeeze is easier to believe with the small numbers this module actually runs on. The synthetic catalog is 500 users and 200 items, and the model is asked to learn 20 factors each.

1 R · 500 users × 200 items = 100,000 cells 5,350 observed just 5.4% of the grid 94,650 cells nobody has ever filled in ≈ 2 P · 500 × 20 10,000 × Qᵀ · 20 × 200 4,000 + bᵤ · one habit per user · 500 + bᵢ · one habit per item · 200 + μ · the global mean · 1 3 14,701 learned numbers in all one dot product of 20 numbers fills any one of the 100,000 cells
Fig. 13.2b — Fig. 13.2 with this module’s real counts on it: 100,000 possible ratings, 5,350 of them observed, and 14,701 numbers learned to stand in for the lot. (All four counts come from recsys_svd.py’s own output and settings.)
  1. What you have. 500 users by 200 items is 100,000 possible ratings, and the run prints 5,350 of them. The shaded strip is drawn at that share of the area, 5.4%, so you can see how little of the grid is evidence. ShopStream’s real grid is far emptier still, around one cell in ten thousand.
  2. What you learn. One row of 20 numbers per user is 10,000 numbers; one row of 20 per item is 4,000. That is the whole memory of the model about taste. The highlighted row and column are the pair that gets multiplied to predict a single cell.
  3. The trade. Add the two bias arrays and the global mean and the model holds 14,701 numbers in place of 100,000 cells. That is a squeeze of about 6.8 to 1, and it is what forces the model to generalise: there is no room to memorise 5,350 individual ratings, so it has to find patterns that several ratings share.

You have not been taught any of the lines below yet. That is on purpose. Guess first, then check. The step-by-step list above the code walks every line. The anatomy after the code takes apart the one line that matters most, and section 09 holds the math.

Sharpen your pencil

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

pop = 1.0 / ranks**0.8give item 1 the most traffic and let attention fall away down the list: a long tail, like a real catalog
items = rng.choice(n_items, size=n, p=pop)
df.drop_duplicates(["user_id", "item_id"])
self.mu = df["rating"].mean()
u_idx, self.user_ids = pd.factorize(df["user_id"])
self.P = rng.normal(0, 0.1, (len(self.user_ids), self.k))make a table with one row of k small random numbers per user: the taste vectors, before any learning
rng.shuffle(triples)
pred = self.mu + self.bu[u] + self.bi[i] + self.P[u] @ self.Q[i]
self.bu[u] += self.lr * (e - self.reg * self.bu[u])
pu = self.P[u].copy()keep a copy of the user's vector before it changes, because the item update two lines down needs the old one
return self.mu + self.bu[u] + self.bi + self.Q @ self.P[u]
order = np.argsort(s)[::-1]
Check your answers
pop = 1.0 / ranks**0.8give item 1 the most traffic and let attention fall away down the list: a long tail, like a real catalog
items = rng.choice(n_items, size=n, p=pop)draw 6,000 item ids at random, but weighted by that long tail, so head items are picked far more often than tail items
df.drop_duplicates(["user_id", "item_id"])keep only one row per user-and-item pair, so each cell of the ratings table holds at most one rating
self.mu = df["rating"].mean()store the average of every rating in the training set; it is the prediction you would make knowing nothing about the user or the item
u_idx, self.user_ids = pd.factorize(df["user_id"])turn arbitrary user ids into row positions 0, 1, 2 and so on, and keep the lookup list, so a user's vector can be found by position
self.P = rng.normal(0, 0.1, (len(self.user_ids), self.k))make a table with one row of k small random numbers per user: the taste vectors, before any learning
rng.shuffle(triples)visit the (user, item, rating) rows in a fresh random order each epoch, so the model does not learn the order the data happened to arrive in
pred = self.mu + self.bu[u] + self.bi[i] + self.P[u] @ self.Q[i]predict one rating: the global average, plus this user's habit, plus this item's habit, plus how well the user's taste vector lines up with the item's vector
self.bu[u] += self.lr * (e - self.reg * self.bu[u])nudge the user's bias a small step toward the observed rating, minus a tiny pull back toward zero so it cannot grow without bound
pu = self.P[u].copy()keep a copy of the user's vector before it changes, because the item update two lines down needs the old one
return self.mu + self.bu[u] + self.bi + self.Q @ self.P[u]the same prediction formula, but for every item at once: the item table times the user vector gives 200 predicted ratings in one operation
order = np.argsort(s)[::-1]sort the 200 predicted ratings lowest to highest, then reverse, so the item positions come out best first

Do not worry if you got half of these. If you guessed that @ multiplies two vectors into one number and that argsort sorts, you already have the serving half. The learning half is the two nudge lines. The by-hand exercise after the code makes you do one nudge with real numbers.

Build it in chunks

We build recsys_svd.py in five chunks. Each file runs on its own, takes seconds, and needs only numpy and pandas; the whole program comes after.

  1. Chunk 1 — make a fake clickstream with a long tail

    A recommender needs ratings, so we invent 500 users, 200 items and about 5,000 ratings. The item traffic follows a power law, which is what real shops look like and what causes the trouble later.

    Step-by-step: what this chunk does, in plain English
    1. Rank the items 1 to 200 and give each a traffic weight 1 / rank0.8; normalise to sum to 1.
    2. Draw a user and an item for every interaction, the items using those weights, so a few items get most of the traffic.
    3. Build each rating from 3.5 plus a user generosity, an item quality and noise; round and clip to 1–5.
    4. Drop repeated (user, item) pairs and return a table.
    chunk1_data.py (added lines)runs offline
    import pandas as pd
    
    
    def synth_interactions(n_users=500, n_items=200, n=6000, seed=42):
        """Synthetic clickstream with a REALISTIC long tail: item traffic follows
        a power law, and head items are (on average) genuinely a bit better --
        the correlation that makes popularity bias so seductive."""
        rng = np.random.default_rng(seed)
        ranks = np.arange(1, n_items + 1)
        pop = 1.0 / ranks**0.8
        pop /= pop.sum()
    
        users = rng.integers(0, n_users, size=n)
        items = rng.choice(n_items, size=n, p=pop)
    
        u_bias = rng.normal(0.0, 0.5, n_users)          # harsh vs generous graders
        i_bias = rng.normal(0.0, 0.3, n_items) + 0.6 * np.exp(-ranks / 30)
        raw = 3.5 + u_bias[users] + i_bias[items] + rng.normal(0.0, 0.8, n)
        ratings = np.clip(np.rint(raw), 1, 5).astype(int)
    
        df = pd.DataFrame({"user_id": users, "item_id": items, "rating": ratings})
        return df.drop_duplicates(["user_id", "item_id"]).reset_index(drop=True)
    
    if __name__ == "__main__":
        df = synth_interactions()
        print(f"{len(df)} interactions | {df['user_id'].nunique()} users"
              f" | {df['item_id'].nunique()} items")
        print(df.head(3).to_string(index=False))

    rng.choice(n, p=weights) — a weighted random draw; rng.normal for the noise.

    python chunk1_data.py prints 5350 interactions | 500 users | 200 items and three sample rows. Measured.

  2. Chunk 2 — give every user and every item a short vector of random numbers

    The model is two tables of 20 numbers each, one row per user and one per item. Before any learning, set them up and see what number a model must beat: just guessing the average rating.

    Step-by-step: what this chunk does, in plain English
    1. Store the learning settings: 20 factors, step size, a small penalty, 20 passes, a seed.
    2. Compute the global average rating mu and map each user and item id to a row number.
    3. Create P (users × 20) and Q (items × 20) of small random numbers, and zeroed bias arrays bu, bi.
    4. Stack (user row, item row, rating) into one array: the observed cells only.
    chunk2_setup.py (added lines)runs offline
    class FunkSVD:
        """Learn one K-dim taste vector per user and per item so that their
        dot product (plus biases) reproduces the observed ratings."""
    
        def __init__(self, n_factors=20, lr=0.005, reg=0.02, n_epochs=20, seed=42):
            self.k, self.lr, self.reg, self.n_epochs, self.seed = (
                n_factors, lr, reg, n_epochs, seed)
    
        def fit(self, df):
            self.mu = df["rating"].mean()               # global average rating
            u_idx, self.user_ids = pd.factorize(df["user_id"])
            i_idx, self.item_ids = pd.factorize(df["item_id"])
            self.u_map = {u: k for k, u in enumerate(self.user_ids)}
    
            rng = np.random.default_rng(self.seed)
            self.P = rng.normal(0, 0.1, (len(self.user_ids), self.k))   # user factors
            self.Q = rng.normal(0, 0.1, (len(self.item_ids), self.k))   # item factors
            self.bu = np.zeros(len(self.user_ids))
            self.bi = np.zeros(len(self.item_ids))
    
            triples = np.column_stack([u_idx, i_idx, df["rating"].to_numpy()])
            return self
    
    
    if __name__ == "__main__":
        df = synth_interactions()
        model = FunkSVD().fit(df)
        print("user table P:", model.P.shape, " item table Q:", model.Q.shape)
        print(f"guess-the-average RMSE: {np.sqrt(((df['rating'] - model.mu) ** 2).mean()):.4f}")

    pd.factorize — turns arbitrary ids into 0, 1, 2… row numbers.

    python chunk2_setup.py prints user table P: (500, 20) item table Q: (200, 20) and guess-the-average RMSE: 0.9936. Measured. Nothing is learned yet.

  3. Chunk 3 — learn: nudge the numbers a little for every observed rating

    This is the whole algorithm. For each known rating, predict it, see how wrong we were, and move the four things involved a small step toward the right answer. Do it 20 times through the data.

    Step-by-step: what this chunk does, in plain English
    1. Shuffle the triples each pass.
    2. For each: prediction = average + user bias + item bias + the dot product of the two vectors; error = rating − prediction.
    3. Nudge both biases and both vectors along the error, with a small penalty pulling them toward zero; keep a copy of the old user vector so both updates use the same one.
    4. Every fifth pass, print the root-mean-square error.
    chunk3_train.py (added lines)runs offline
            for epoch in range(self.n_epochs):
                rng.shuffle(triples)                    # SGD wants a fresh visit order
                sq_err = 0.0
                for u, i, r in triples:
                    u, i = int(u), int(i)
                    pred = self.mu + self.bu[u] + self.bi[i] + self.P[u] @ self.Q[i]
                    e = r - pred
                    sq_err += e * e
                    self.bu[u] += self.lr * (e - self.reg * self.bu[u])
                    self.bi[i] += self.lr * (e - self.reg * self.bi[i])
                    pu = self.P[u].copy()               # both updates need the OLD vector
                    self.P[u] += self.lr * (e * self.Q[i] - self.reg * pu)
                    self.Q[i] += self.lr * (e * pu - self.reg * self.Q[i])
                if (epoch + 1) % 5 == 0:
                    print(f"  epoch {epoch + 1:>2}/{self.n_epochs}"
                          f"  train RMSE {np.sqrt(sq_err / len(triples)):.4f}")
            return self   # the loop goes just before this line, inside fit()

    @ — the dot product of two vectors; the update rule is gradient descent written out by hand.

    python chunk3_train.py prints the error falling: epoch 5/20 train RMSE 0.8821, then 0.8175, 0.7783, 0.7511. Measured. Below the 0.9936 of rung 2, so it learned something.

  4. Chunk 4 — recommend: score every item for one user

    The learned tables are only useful if we can ask them for a top-10. One matrix-times-vector gives the predicted rating for all 200 items, so serving is a single line of arithmetic.

    Step-by-step: what this chunk does, in plain English
    1. scores_for: average + the user's bias + every item bias + Q @ P[u].
    2. recommend: an unknown user returns an empty list (cold start); otherwise sort best first, skip items already seen, keep the top n.
    3. In the main block, ask for user 42's top 5.
    chunk4_recommend.py (added lines)runs offline
        def scores_for(self, user_id):
            """Predicted rating for EVERY item at once -- one matvec, not a loop."""
            u = self.u_map[user_id]
            return self.mu + self.bu[u] + self.bi + self.Q @ self.P[u]
    
        def recommend(self, user_id, n=10, exclude=frozenset()):
            if user_id not in self.u_map:               # cold start: caller must
                return []                               # fall back to popularity
            s = self.scores_for(user_id)
            order = np.argsort(s)[::-1]
            recs = [(int(self.item_ids[i]), float(s[i]))
                    for i in order if self.item_ids[i] not in exclude]
            return recs[:n]
    
    # in the __main__ block:
    seen = set(df.loc[df["user_id"] == 42, "item_id"])
    print(f"Top 5 for user 42 (has rated {len(seen)} items):")
    for rank, (item, score) in enumerate(model.recommend(42, n=5, exclude=seen), 1):
        print(f"  #{rank:>2}  item {item:>3}  predicted {score:.2f}")

    np.argsort(s)[::-1] — item numbers ordered from highest score to lowest.

    python chunk4_recommend.py prints, after the training lines, Top 5 for user 42 (has rated 11 items) and #1 item 34 predicted 3.97, #2 item 7 predicted 3.74, #3 item 30 predicted 3.64, #4 item 12 predicted 3.60, #5 item 5 predicted 3.58. Measured.

  5. Chunk 5 — the audit: who actually gets recommended?

    A good error number does not tell you whether the shop shows 200 products or 27. This last chunk recommends ten items to all 500 users and counts which items fill the slots.

    Step-by-step: what this chunk does, in plain English
    1. Loop over every user and count each item in their top 10.
    2. Coverage: how many different items appeared at all.
    3. Share: what fraction of all 5,000 slots the three most-shown items took.
    chunk5_audit.py (added lines)runs offline
    # --- the audit most tutorials skip: WHO gets recommended? ---
    counts = Counter()
    for uid in model.user_ids:
        counts.update(item for item, _ in model.recommend(uid, n=10))
    n_items = df["item_id"].nunique()
    top3 = counts.most_common(3)
    top3_share = sum(c for _, c in top3) / (10 * len(model.user_ids))
    print(f"\ncatalog coverage@10: {len(counts)}/{n_items} items"
          f" ({100 * len(counts) / n_items:.0f}%)")
    print(f"top-3 items fill {100 * top3_share:.0f}% of all top-10 slots: {top3}")

    collections.Counter — counts things; .most_common(3).

    python chunk5_audit.py ends with catalog coverage@10: 27/200 items (14%) and top-3 items fill 29% of all top-10 slots: [(34, 500), (7, 492), (72, 469)]. Measured; the file is the whole program below.

Step-by-step: what recsys_svd.py does, in plain English
  1. Bring in three libraries: Counter to tally which items get recommended, numpy for the arithmetic, and pandas to hold the interaction table.
  2. Define synth_interactions(): fake 6,000 clicks from 500 users on 200 items. Item traffic follows a power law, so a few head items get most of the clicks, the way a real catalog behaves.
  3. Give each user a hidden generosity and each item a hidden quality. Head items get a small quality bonus on purpose; that correlation is what makes popularity bias so tempting later.
  4. Build each rating as 3.5 plus the user's habit plus the item's quality plus noise. Round it, clip it to 1 through 5, and drop duplicate user-item pairs.
  5. Define the FunkSVD class and its settings. n_factors is how many hidden numbers each user and item gets. lr is the step size and reg the pull toward zero. n_epochs is how many passes over the data, and a seed makes runs repeatable.
  6. In fit(), store the global average rating mu. Then convert user and item ids into row positions with pd.factorize, keeping the lookup lists.
  7. Create the user table P and item table Q, filled with small random numbers. Create two bias arrays bu and bi, filled with zeros.
  8. Stack the (user position, item position, rating) triples into one array. This is the whole training set: only the cells that were observed.
  9. For each epoch, shuffle the triples. Then, for each one, predict the rating and measure the error. Nudge the two biases and the two vectors a small step toward the observed rating. The pu copy keeps the item update honest.
  10. Every five epochs, print the training root-mean-square error, so you can watch it fall.
  11. Define scores_for(): predict every item's rating for one user in a single matrix-times-vector operation. This is why serving is fast.
  12. Define recommend(). For an unknown user it returns an empty list: that is cold start. Otherwise it sorts the scores best first, drops excluded items, and returns the top n as (item, score) pairs.
  13. When run as a script, build the data and fit the model. Print user 42's top ten, with the items they already rated excluded.
  14. Then the audit. Recommend ten items to every user and count how often each item appears. Print catalog coverage and the share of slots taken by the top three items.

The whole program

Lines 1–13 are the header and imports. Lines 14–35 are rung 1, 36–57 rung 2, 58–76 rung 3, 77–104 rung 4 (plus the main block that fits the model and prints user 42), and 105–115 rung 5. Each begins with a # ── rung n ── comment.

recsys_svd.pyruns offline
# pip install "numpy>=2.1" "pandas>=2.2"
"""ShopStream recommender: matrix factorization from scratch.

Production "SVD" recommenders are not textbook SVD (which can't handle
missing entries) -- they are gradient-descent factorization of the
OBSERVED cells only, plus bias terms. This is that algorithm (FunkSVD).
"""
from collections import Counter

import numpy as np
import pandas as pd


# ── rung 1: the fake clickstream ──
def synth_interactions(n_users=500, n_items=200, n=6000, seed=42):
    """Synthetic clickstream with a REALISTIC long tail: item traffic follows
    a power law, and head items are (on average) genuinely a bit better --
    the correlation that makes popularity bias so seductive."""
    rng = np.random.default_rng(seed)
    ranks = np.arange(1, n_items + 1)
    pop = 1.0 / ranks**0.8
    pop /= pop.sum()

    users = rng.integers(0, n_users, size=n)
    items = rng.choice(n_items, size=n, p=pop)

    u_bias = rng.normal(0.0, 0.5, n_users)          # harsh vs generous graders
    i_bias = rng.normal(0.0, 0.3, n_items) + 0.6 * np.exp(-ranks / 30)
    raw = 3.5 + u_bias[users] + i_bias[items] + rng.normal(0.0, 0.8, n)
    ratings = np.clip(np.rint(raw), 1, 5).astype(int)

    df = pd.DataFrame({"user_id": users, "item_id": items, "rating": ratings})
    return df.drop_duplicates(["user_id", "item_id"]).reset_index(drop=True)


# ── rung 2: tables of random numbers ──
class FunkSVD:
    """Learn one K-dim taste vector per user and per item so that their
    dot product (plus biases) reproduces the observed ratings."""

    def __init__(self, n_factors=20, lr=0.005, reg=0.02, n_epochs=20, seed=42):
        self.k, self.lr, self.reg, self.n_epochs, self.seed = (
            n_factors, lr, reg, n_epochs, seed)

    def fit(self, df):
        self.mu = df["rating"].mean()               # global average rating
        u_idx, self.user_ids = pd.factorize(df["user_id"])
        i_idx, self.item_ids = pd.factorize(df["item_id"])
        self.u_map = {u: k for k, u in enumerate(self.user_ids)}

        rng = np.random.default_rng(self.seed)
        self.P = rng.normal(0, 0.1, (len(self.user_ids), self.k))   # user factors
        self.Q = rng.normal(0, 0.1, (len(self.item_ids), self.k))   # item factors
        self.bu = np.zeros(len(self.user_ids))
        self.bi = np.zeros(len(self.item_ids))

        triples = np.column_stack([u_idx, i_idx, df["rating"].to_numpy()])
        # ── rung 3: learn ──
        for epoch in range(self.n_epochs):
            rng.shuffle(triples)                    # SGD wants a fresh visit order
            sq_err = 0.0
            for u, i, r in triples:
                u, i = int(u), int(i)
                pred = self.mu + self.bu[u] + self.bi[i] + self.P[u] @ self.Q[i]
                e = r - pred
                sq_err += e * e
                self.bu[u] += self.lr * (e - self.reg * self.bu[u])
                self.bi[i] += self.lr * (e - self.reg * self.bi[i])
                pu = self.P[u].copy()               # both updates need the OLD vector
                self.P[u] += self.lr * (e * self.Q[i] - self.reg * pu)
                self.Q[i] += self.lr * (e * pu - self.reg * self.Q[i])
            if (epoch + 1) % 5 == 0:
                print(f"  epoch {epoch + 1:>2}/{self.n_epochs}"
                      f"  train RMSE {np.sqrt(sq_err / len(triples)):.4f}")
        return self

    # ── rung 4: recommend ──
    def scores_for(self, user_id):
        """Predicted rating for EVERY item at once -- one matvec, not a loop."""
        u = self.u_map[user_id]
        return self.mu + self.bu[u] + self.bi + self.Q @ self.P[u]

    def recommend(self, user_id, n=10, exclude=frozenset()):
        if user_id not in self.u_map:               # cold start: caller must
            return []                               # fall back to popularity
        s = self.scores_for(user_id)
        order = np.argsort(s)[::-1]
        recs = [(int(self.item_ids[i]), float(s[i]))
                for i in order if self.item_ids[i] not in exclude]
        return recs[:n]


if __name__ == "__main__":
    df = synth_interactions()
    print(f"{len(df)} interactions | {df['user_id'].nunique()} users"
          f" | {df['item_id'].nunique()} items")

    model = FunkSVD().fit(df)

    seen = set(df.loc[df["user_id"] == 42, "item_id"])
    print(f"\nTop 10 for user 42 (has rated {len(seen)} items):")
    for rank, (item, score) in enumerate(model.recommend(42, exclude=seen), 1):
        print(f"  #{rank:>2}  item {item:>3}  predicted {score:.2f}")

    # ── rung 5: the audit ──
    # --- the audit most tutorials skip: WHO gets recommended? ---
    counts = Counter()
    for uid in model.user_ids:
        counts.update(item for item, _ in model.recommend(uid, n=10))
    n_items = df["item_id"].nunique()
    top3 = counts.most_common(3)
    top3_share = sum(c for _, c in top3) / (10 * len(model.user_ids))
    print(f"\ncatalog coverage@10: {len(counts)}/{n_items} items"
          f" ({100 * len(counts) / n_items:.0f}%)")
    print(f"top-3 items fill {100 * top3_share:.0f}% of all top-10 slots: {top3}")

Three engineering details worth noticing: the biases (mu, bu, bi) absorb "this user grades harshly" and "this item is universally loved" so the latent factors only have to learn genuine taste; the update snapshots pu because both factor updates must use the pre-update vector; and scores_for ranks the entire catalog with a single matrix–vector product — the reason factorization models serve in microseconds.

One line in that file carries the whole idea. Before you take it apart in words, look at it as an amount of money adding up.

the rating actually given: 5 1 μ · global mean 3.5000 2 bᵤ · user bias −0.3000 bᵢ · item bias +0.4000 3 Pᵤ · Qᵢ · dot product +0.1400 4 pred · the sum 3.7400 e = 5 − 3.7400 = 1.2600 every star of scale is 76 pixels wide Pᵤ · Qᵢ = 0.6×0.5 + (−0.2)×0.8 = 0.30 − 0.16 = 0.1400
Fig. 13.2c — One predicted rating, built from four pieces and drawn to scale. Three of the four pieces know nothing about taste at all; only the last one does. (Numbers are the by-hand example below: μ 3.5, bᵤ −0.3, bᵢ +0.4, Pᵤ = (0.6, −0.2), Qᵢ = (0.5, 0.8).)
  1. The global mean. The long bar is 3.5, the average of every rating in the training set. It is the guess you would make knowing nothing whatsoever. Notice how much of the final answer it already accounts for: the model’s job is only the small stuff on top of it.
  2. The two biases. The short bar pointing back is this user, a harsh grader, who runs 0.3 of a star below the crowd. The one pointing forward is this item, well liked, which runs 0.4 above. Neither says anything about who likes what; they are habits, and pulling them out first is what stops the taste vectors wasting their capacity relearning them.
  3. The dot product. This is the only piece that pairs a person with a product: multiply the two vectors term by term and add, giving 0.1400. It is the smallest bar in the picture, and it is the entire reason the system is called personalised. Everything else would give the same answer to everybody.
  4. The sum and the gap. The four pieces make 3.7400. The rating actually given was 5, so the arrow measures the error, 1.2600 of a star. Training is nothing but this gap, measured for all 5,350 observed cells, over and over, with every piece nudged a little to close it.
Anatomy of a prediction — the one line to know by heart
pred = self.mu1 + self.bu[u]2 + self.bi[i]3 + self.P[u]4 @5 self.Q[i]6
  1. The global mean. The average of every rating in the training set, about 3.5 here. It is the prediction you would make knowing nothing. Leave it out and the vectors waste their first epochs learning the number 3.5 instead of learning taste.
  2. The user bias. How far this user's ratings sit above or below the global mean: a harsh grader is negative, a generous one positive. The index u is a row position from pd.factorize, not the raw user id. Indexing with the raw id is the classic silent bug here.
  3. The item bias. How far this item sits above or below the mean regardless of who rates it. This is also where popularity bias enters. Head items have hundreds of ratings, so their bias is estimated confidently. Tail items have three, so regularization pulls theirs toward zero. Marker 2 of Fig. 13.2c is this term carrying +0.4000 for a well-liked item.
  4. The user's taste vector. Twenty numbers nobody named. Reading dimension 3 as "likes gore" is a story you tell afterwards; the model only knows that the number helps the predictions.
  5. The dot product. Multiply the two vectors element by element and add the results. That gives one number saying how well the taste and the item line up. Write * instead and you get twenty numbers, which numpy will cheerfully add to the biases without complaint.
  6. The item's vector. The same twenty dimensions, seen from the item's side. In scores_for() the same formula runs for every item at once as self.Q @ self.P[u]. That is a whole table times one vector, which is why serving costs microseconds.
Sharpen your pencil

Make one prediction and one learning step by hand, with two hidden numbers instead of twenty. Suppose the model has learned this much so far. The global mean μ (mu) is 3.5. User u is a harsh grader with bias −0.3. Item i is well liked, with bias +0.4. The vectors are Pu = (0.6, −0.2) and Qi = (0.5, 0.8). Now user u rates item i a 5.

Pu · Qi = 0.6·0.5 + (−0.2)·0.8 =0.30 − 0.16 = 0.1400
pred = 3.5 + (−0.3) + 0.4 + 0.1400 =
e = 5 − pred =
new bu = −0.3 + 0.005 · (e − 0.02 · (−0.3)) =
new Pu = Pu + 0.005 · (e · Qi − 0.02 · Pu) =

The step size 0.005 is lr and the pull toward zero 0.02 is reg, both straight from the code. Work to four decimal places. Then answer: after this one step, did the prediction for this cell move toward 5, and by how much?

Check your answers
pred3.5 − 0.3 + 0.4 + 0.14 = 3.7400
e5 − 3.74 = 1.2600. The model guessed low by 1.26 stars.
new bu−0.3 + 0.005 · (1.26 + 0.006) = −0.3 + 0.005 · 1.266 = −0.3 + 0.0063 = −0.2937
new Pue · Qi = (0.63, 1.008); minus 0.02 · Pu = (0.012, −0.004) gives (0.618, 1.012); times 0.005 gives (0.0031, 0.0051); so Pu becomes (0.6031, −0.1949)

Run the matching updates for bi and Qi, using the old Pu as the pu copy does. The new prediction is 3.7607, about 0.02 of a star closer to 5. lr is small on purpose, so no single rating can yank a vector around. Twenty epochs over 5,350 rows is about 107,000 of these nudges. That is how 0.02 at a time becomes a training error of 0.75.

The error was positive, so every parameter moved to raise the prediction. The user’s vector moved toward the item’s vector: the 0.63 and 1.008 came from Qi. That is the whole idea: a user who likes an item drifts toward it in the hidden space. The regularization terms were tiny, 0.012 and 0.004, but they never sleep. Over thousands of steps they stop a three-rating tail item from being memorized. Marker 4 of Fig. 13.2c is the gap those nudges are closing: 1.2600 of a star.

04 · Watch it breakPopularity Bias & the Cold-Start Wall

The model trains, the error falls to 0.75, and user 42 gets ten plausible picks. This is the moment to be suspicious, because Priya did not ask for plausible picks. She asked for 2 million different pages instead of one bestseller wall. So we run the one extra audit most tutorials skip: count which items the model hands to all 500 users. The answer is 27 of them, out of 200.

Run the file. Training converges nicely, user 42 gets ten plausible picks… and then the audit at the bottom tells you what you actually built:

output — one run (yours will vary slightly)runs offline
5350 interactions | 500 users | 200 items
  epoch  5/20  train RMSE 0.8821
  epoch 10/20  train RMSE 0.8175
  epoch 15/20  train RMSE 0.7783
  epoch 20/20  train RMSE 0.7511

Top 10 for user 42 (has rated 11 items):
  # 1  item  34  predicted 3.97
  # 2  item   7  predicted 3.74
  ...

catalog coverage@10: 27/200 items (14%)
top-3 items fill 29% of all top-10 slots: [(34, 500), (7, 492), (72, 469)]

Two numbers in that audit are the whole failure, and one more failure is hiding where the audit cannot see it. Here are all three, drawn from this run.

1 COVERAGE@10 · one square per item 27 lit = every item any of the 500 users is ever shown 173 dark = 86% of the catalog, unreachable 2 WHO FILLS THE 5,000 SLOTS item 34 item 7 item 72 500 492 469 appearances in the 500 users’ top-10 lists 1,461 of 5,000 slots taken by three items = 29% item 34 is in every single list 3 COLD START · what the audit cannot even count new user 9001 · 0 clicks recommend() returns [ ] new item 201 · 0 ratings no column in R at all 4 WHY · item 34 carries hundreds of ratings, so its bias is estimated confidently. A tail item carries three, so regularization pulls its bias toward zero and it never wins.
Fig. 13.2d — The audit at the bottom of recsys_svd.py, drawn. 27 of 200 items are ever recommended, three items take 29% of all slots, and the two customers who most need help are the two the model cannot see at all. (Every count is from the printed output above.)
  1. The coverage grid. Two hundred squares, one per item in the synthetic catalog. The 27 lit squares are every item that appears in any of the 500 users’ top-10 lists. The other 173 are never shown to anybody, ever. Priya asked for 2 million different pages; this grid says the model has 27 products to build them from.
  2. The three head items. Each bar is how many of the 500 users get that item in their ten. Item 34 scores 500 out of 500: it is in every list on the site. Together the top three take 1,461 of the 5,000 available slots, 29%. That is what popularity bias looks like when you count it instead of arguing about it.
  3. The two empty rows. A customer who signed up this morning has no row in the ratings grid, so there is nothing to compare and recommend() hands back an empty list. A product added yesterday has no column, so collaborative filtering cannot see it however good it is. Neither of these appears anywhere in the coverage number, which is what makes cold start easy to ship by accident.
  4. The reason. The item bias of Fig. 13.2c, marker 2, is estimated from however many ratings an item has. Hundreds of ratings give a confident bias; three ratings give a bias that regularization shrinks back toward zero, which reads as “probably average”. Ranking by predicted rating then puts the confident items on top of every list, forever.
Failure mode

Popularity bias. Read that last line again: item 34 appears in all 500 users’ top-10, and only 14% of the catalog is ever recommended to anyone. Those are markers 1 and 2 of Fig. 13.2d, drawn straight from this run.

The model isn’t broken — it’s doing exactly what we asked. Head items have hundreds of observations, so their factors and biases are estimated confidently; tail items have two or three, so regularization shrinks them toward “meh”, and the safe bet wins every slot. Marker 4 of Fig. 13.2d is that sentence drawn.

In production this becomes a feedback loop: popular items get recommended, so they get clicked, so they get more popular — the rich get richer, 86% of ShopStream’s inventory becomes undiscoverable, and the personalized homepage quietly converges back to… the same bestseller wall Priya complained about.

And the cold-start wall. A user who signed up this morning has no row in the matrix — recommend() returns an empty list. A product added yesterday has no column, so collaborative filtering literally cannot see it. Every pure-CF system has this hole, and it is the bottom strip of Fig. 13.2d, marker 3.

Production systems attack both problems with the later stages of the funnel in Fig. 13.1 and a few standard plays you should be able to rattle off in an interview:

Before the two of them argue, look at what each one actually does with ShopStream’s data. The left panel is everything collaborative filtering can see; the right panel is everything content-based filtering can see. Every claim in the chat below points at a number in this picture.

1 COLLABORATIVE · SEES ONLY CLICKS Dev’s row 5 1 ? ? shoes · mat · jacket · watch closest twin: Ana, cosine 1.0000 → smartwatch, predicted 4.51 new user Ravi · 0 clicks recommend() → [ ] · nothing at all 2 CONTENT-BASED · SEES ONLY ATTRIBUTES item 201 · added yesterday · 0 clicks category: trail running · brand: Vertex price $120 · waterproof · unisex matches Ravi’s 3 onboarding categories → a full page on day one, before any click Dev bought running shoes socks · insoles · more shoes 3 of 3 in one category: the bubble 3 THE SCORECARD · four questions, two different answers question collaborative content-based new user empty list 3 categories → a page new item invisible until clicked a vector from its text surprise found the 4.51 watch never leaves footwear coverage 14% of the catalog only as good as metadata
Fig. 13.2e — The two jobs, side by side. Collaborative filtering reads the clicks and nothing else (left); content-based filtering reads the product and nothing else (right); the scorecard is where each one wins and loses. (Dev, Ana and the 4.51 come from Fig. 13.0b; the 14% comes from the audit in Fig. 13.2d.)
  1. The clicks-only view. All collaborative filtering ever sees is a row of numbers. From Dev’s two ratings it reaches Ana, and from Ana’s row it reaches a smartwatch at 4.51. Nothing in that chain knows what a smartwatch is. The same blindness is why Ravi, with no row at all, gets an empty list.
  2. The attributes-only view. Content-based filtering never looks at anyone else’s behaviour. It reads item 201’s own fields and matches them against what it knows Ravi likes, so it can fill a page before his first click. The cost is directly below it: matching on attributes keeps returning the same category, which is the filter bubble.
  3. The scorecard. Four questions, and neither column wins all four. Read it as a shopping list rather than a verdict: the production answer is to take the right-hand column’s answers for new users and new items, and the left-hand column’s answers once somebody has actually clicked on something.
Fireside chat

Tonight's talk: Collaborative Filtering and Content-Based Filtering argue over the question, "Who's more important?"

Collaborative Filtering
Content-Based Filtering

Marker 1, left panel. I have never read a product description in my life and I do not need to. Dev rated two things: shoes 5, yoga mat 1. From those two numbers alone I found Ana, the twin with a cosine of 1.0000, and I predicted 4.51 for a smartwatch. Nobody wrote a rule joining yoga mats to wrist hardware. Nobody could have. You would still be matching on the word “shoe”.

collaborative filtering works purely from the clicks in the grid. It found Dev a smartwatch because another customer with the same two ratings loved one, and no product description was involved.

And directly under the same marker is Ravi, who signed up this morning with 0 clicks. Your recommend() returned an empty list. An empty list. Now look at marker 2: I had a full page for Ravi before his first click, from three onboarding categories and item 201’s attributes. You say “cold start” as if it were weather. It is your architecture.

a brand-new user has no row in the grid, so the collaborative method has literally nothing to compare and returns nothing. Content-based filtering only needs the product’s own attributes, so it can fill a page on day one.

It is a hole, I grant it. Now read the lower half of marker 2. A customer buys running shoes and you show them socks, insoles and more shoes: three of three in one category. You are the reason the phrase “filter bubble” exists. I found Dev a smartwatch because his row looked like Ana’s, and no attribute in that catalogue would ever have carried you from footwear to a watch.

matching on attributes keeps recommending the same kind of thing. That is safe and it is boring, and it is the price content-based filtering pays for being explainable.

Surprise is cheap when you cannot explain it. Ask your model why item 34 sits in 500 of 500 lists on the scorecard at marker 3. It cannot say. I can show a product manager the attribute match behind every single line I produce. And when the catalogue team adds item 201 tomorrow, I can recommend it tomorrow. You need weeks of clicks before you can even see that it exists.

the collaborative model’s reasons live in unnamed numbers, so nobody can audit them. The content model’s reasons are the product’s own attributes, which a human can read.

Item 34 is a fair hit. Popularity bias is mine and I own it: the bottom row of the scorecard says 14% of the catalogue ever recommended. But read the fix list just above this chat. A diversity re-ranker, a bandit, popularity-in-context, and yes, you, for new items. Nobody there proposed replacing me with attributes. And your attributes are only as good as the catalogue metadata, which at every company I have worked for is a mess.

the cure for popularity bias is a set of additions around the collaborative model, not a replacement for it. And the content model depends on metadata quality, which is usually poor.

Which is why the item tower now gets its features from a language model reading the description, as section 05 shows in the next few paragraphs. My inputs improved this decade. Yours are still clicks, and clicks are contaminated by whatever the last recommender chose to put on the page. You train on your own output.

modern content features are extracted from text by a language model, so poor metadata is less of an excuse than it was. Click data, meanwhile, only contains items the previous system chose to show.

The feedback loop is real, and it is yours too the moment you go live, because your clicks come from your recommendations as well. The difference is the third row of the scorecard. “Art-house versus blockbuster” is not a column in anyone’s catalogue. It is factor 3, and it is the only reason Dev’s 4.51 exists at all.

both methods eventually train on data their own choices produced. The collaborative method’s one unique gift is taste dimensions that no attribute column records.

Factor 3. You cannot name it and you want credit for it. Fine, let us put this where the industry put it: a hybrid. My attributes get item 201 through the door and give Ravi a first page. Your interactions decide where everything sits once people have actually touched it. Two towers, one vector space.

the production answer is to use both. Attributes cover the cold start, interactions do the ranking once history exists, and both are trained into the same vector space.

Credit for finding it; naming it was never the job. You take the left tower. We’ll revisit who is more important after the A/B test.

in a two-tower model the content signals usually feed the item side. Neither voice concedes, and the argument is settled by an online experiment rather than by an opinion.

The A/B test in which your arm has an empty list for Ravi. Same time next week.

an online test still has to serve new users, and the collaborative arm cannot. That is the last word, and it is a fair one.

05 · The industry directionRecSys in 2026: Two Towers & LLMs at the Edges

We now have a working recommender and a measured failure: 14% catalogue coverage, and item 34 in all 500 lists. The fix list names two-tower retrieval, content features and a diversity re-rank, and Priya’s engineers will want to know what the industry actually runs in 2026 before they sign off on any of it. This section is that answer, and it keeps her 100 millisecond budget in view throughout. It also gives you the vocabulary to say which of her numbers moved.

Matrix factorization is the concept exams test; the modern candidate generator (as of Aug 2026, and for several years now) is the two-tower model.

One neural network ("tower") encodes the user — history, context, device — into a vector; another encodes each item — title, brand, price, description — into a vector in the same space; training pushes dot products high for observed clicks and low for non-clicks. Sound familiar?

It's Module 08's embedding retrieval with the math serving a different master: instead of "query text near document text", it learns "this kind of person near this kind of product". Same vector-store infrastructure, same ANN indexes (HNSW and friends), different training signal.

online · per request user features history · context user tower user vector query ANN index 500K item vectors top ~500 candidates in ~10 ms → Stage 2 offline · nightly batch item catalog item tower embed all items, rebuild index
Fig. 13.3 — Two-tower serving: item vectors are precomputed offline into an ANN index (Module 08's vector store, different payload); at request time one user-tower forward pass plus one ANN lookup yields ~500 candidates. Matrix factorization is the degenerate case where each tower is a plain embedding lookup.

LLMs meet RecSys (awareness level)

Two towers fix Priya’s 100 millisecond budget, but on their own they do not fix her 14% coverage, because a product nobody has clicked still has nothing for the item tower to learn from. The two currents below are where a 2026 team gets a usable vector for a brand-new product, and where a shopper finally gets to say in words what no click can express. Know that they exist, and know exactly what they do not replace.

Two currents worth knowing about, both active research-to-production territory as of Aug 2026 — know they exist, don't claim depth you don't have:

Item cold start is the one Priya can feel in the catalog. Here is what the first of those two currents actually does to it.

1 WHAT THE CATALOG HAS item 201 · 0 clicks “Vertex Ridge Shell” blue · size M · $120 LLM 2 WHAT THE MODEL EXTRACTS use case: trail running material: waterproof shell style: technical, minimal embed 3 THE ANN INDEX trail running kitchenware item 201 lands here on day zero without it: item 201 waits weeks for its first clicks, and Fig. 13.2d says it may wait forever with it: a usable item vector the day the product is created the clicks still decide where item 201 finally sits. This only gets it through the door, and it does nothing at all for a brand-new user, who still needs the onboarding questions.
Fig. 13.3b — Item cold start, softened by content. A language model turns a thin catalog record into attributes, those attributes become a vector, and the vector lands beside genuinely similar products before anyone has clicked the product once. (Item 201 is the new product from Fig. 13.2e; the neighbourhoods are drawn, not measured.)
  1. The thin record. Most catalogs hold a title, a colour and a price, and very little else. That is not enough to place a product anywhere sensible, which is the real reason teams gave up on content features in the first place and waited for clicks instead.
  2. The extracted attributes. A language model reads the description and writes down what the product is for, what it is made of, and who it suits. These are ordinary structured fields; the interesting part is that they were free and did not need a catalog team. This is the single most common production use of an LLM inside a recommender today.
  3. The landing place. Embedding those attributes puts item 201 inside the cluster of things it genuinely resembles, on its first day. It can now be retrieved by stage 1 of Fig. 13.1 like any other item. Clicks will still move it later; this only stops the catalog from hiding it in the meantime.

Finally, the vocabulary you'll use to evaluate any of this. Rating-error metrics like RMSE died with the Netflix Prize era; production evaluation is ranking evaluation, plus health checks the accuracy metrics can't see:

RecSys evaluation cheat sheet — offline metrics computed against a held-out future slice of interactions
MetricThe question it answersGotcha
Precision@KOf the K items shown, what fraction did the user actually engage with?Ignores rank order within the K and total relevant count.
Recall@KOf everything relevant to this user, what fraction made the top K?Punishes small K on users with many relevant items.
NDCG@KAre the most relevant items ranked highest? (position-discounted)The default headline metric; needs graded relevance to shine.
MRRHow high is the first relevant item?Only cares about one item — good for "find the one right answer" UIs.
Hit rate@KDid the user engage with any of the K?Coarse; fine for quick baselines.
CoverageWhat share of the catalog ever gets recommended?The popularity-bias alarm — watch it alongside accuracy, as our audit showed.
SerendipityAre we surprising users with relevant-but-unexpected items?Hard to compute; proxy = relevance × dissimilarity from the user's history.

Only one of those metrics needs a picture, because it is the one that decides arguments. NDCG asks whether the good items are near the top, and here is what “near the top” is worth.

1 THE POSITION DISCOUNT · 1 ÷ log₂(position + 1) 1.000 1 0.631 2 0.500 3 0.431 4 0.387 5 0.356 6 0.333 7 0.315 8 0.301 9 0.289 10 slot on the page · what one relevant item there is worth 2 RANKING A · the two items user 42 wanted land at slots 1 and 3 1 2 3 4 5 6 7 8 9 10 DCG = 1.000 + 0.500 = 1.500 · NDCG = 1.500 ÷ 1.631 = 0.920 3 RANKING B · the same two items land at slots 8 and 10 1 2 3 4 5 6 7 8 9 10 DCG = 0.315 + 0.289 = 0.604 · NDCG = 0.604 ÷ 1.631 = 0.370 4 precision@10 = 2 ÷ 10 = 0.200 for both rankings. It cannot tell them apart.
Fig. 13.3c — Why the headline metric is NDCG and not precision. Two rankings of the same ten items, with the same two hits in them, score 0.920 and 0.370 because of where the hits sit. (Discounts are 1 ÷ log₂(i+1); the ideal ordering scores 1.000 + 0.631 = 1.631.)
  1. The discount. Each slot on the page is worth less than the one above it, by 1 divided by the base-2 logarithm of the position plus one. Slot 1 is worth 1.000; slot 10 is worth 0.289, barely a quarter as much. The shape is a modelling choice rather than a law, and it roughly matches how fast people stop looking down a list.
  2. The good ranking. User 42’s two genuinely wanted items land at slots 1 and 3, so they collect 1.000 and 0.500. Dividing by the best possible arrangement, 1.631, gives an NDCG of 0.920. The division is what makes scores comparable between a user with two relevant items and a user with twenty.
  3. The bad ranking. The same two items, pushed to slots 8 and 10, collect 0.315 and 0.289. NDCG falls to 0.370, which is the honest verdict: the shopper almost certainly never scrolled that far, so in practice ShopStream showed them nothing they wanted.
  4. Why precision is not enough. Both rows contain exactly two hits out of ten, so precision@10 reports 0.200 for both and cannot separate a good page from a useless one. That is the whole argument for a position-aware metric, and it is the answer interviewers are listening for.

Questions you might be asking now

The cheat sheet and Fig. 13.3c score a list somebody else built. The questions below build one list from nothing, mark it, and then ask what the marks miss. Every answer uses the same small grid: the four shoppers from Fig. 13.0b with four more products, plus what Dev bought the week after. Every number comes from rerunning recs_by_hand.py.

The grid every answer below uses. The first four products are Fig. 13.0b unchanged; a dash means the shopper never bought that product. The last row is Dev's following week, which no model is allowed to see. All ratings are invented to keep the arithmetic small.
ShopperShoesYoga matTrail jacketSmartwatchRunning socksFoam rollerYoga blocksHeadlamp
Ana514543—5
Ben42—4521—
Cho152—2453
Dev51——————
Dev, the following week (held out)ownedowned254———
Walk one shopper all the way through: how does Dev end up with three products on his homepage, and how does anyone find out whether they were good ones?

Four stations. Compare Dev with the other shoppers, score every product, strike out what he already owns, and show the top three: smartwatch, headlamp, running socks. A week later, mark that list against what he actually bought. It scores precision@3 0.667, recall@3 1.000 and NDCG@3 0.920.

This is the funnel of Fig. 13.1, shrunk to four shoppers. Each station below is one of its stages, and each one fits on a pencil line. The last station is the one the cheat sheet takes for granted: a finished list, and a record of what the shopper did next.

Station 1: find the shoppers most like Dev

Dev has rated two products, shoes 5 and yoga mat 1, so those two columns are all the evidence there is. You worked out the cosine similarities by hand in section 02: Ana 1.0000, Ben 0.9648 and Cho 0.3846. A 1 means identical taste on the shared columns. Cho's low score means she likes what Dev dislikes.

Station 2: score every product

A product's score is the neighbours' ratings for it, averaged, with each vote weighted by that neighbour's similarity to Dev. A neighbour who never bought the product does not vote. Two products worked out in full:

  1. Running socks, all three voted. Top: 1.0000 × 4 + 0.9648 × 5 + 0.3846 × 2 = 9.593. Bottom, the weights that voted: 1.0000 + 0.9648 + 0.3846 = 2.3494. Score: 9.593 ÷ 2.3494 = 4.083.
  2. Headlamp, only Ana and Cho voted. Top: 1.0000 × 5 + 0.3846 × 3 = 6.1538. Bottom: 1.0000 + 0.3846 = 1.3846. Score: 6.1538 ÷ 1.3846 = 4.444.
Stations 2 and 3 for all eight products, sorted by score
ProductWho votedScoreStation 3Slot on the page
SmartwatchAna, Ben4.509Kept1
HeadlampAna, Cho4.444Kept2
Running socksAna, Ben, Cho4.083Kept3
ShoesAna, Ben, Cho3.935Struck out: Dev owns themNone
Trail jacketAna, Cho3.444Kept4, not shown
Foam rollerAna, Ben, Cho2.753Kept5, not shown
Yoga blocksBen, Cho2.140Kept6, not shown
Yoga matAna, Ben, Cho2.065Struck out: Dev owns itNone

Ben never bought a headlamp, so its score leans on Ana and Cho alone. That exposes a weakness of this simple average. A product bought only by Cho would inherit her rating unchanged, however unlike Dev she is. Real neighbour systems keep only the closest few shoppers and demand a minimum number of votes.

Station 3: apply the rules, then show three

Business rules run after scoring, as stage 3 of Fig. 13.1 does. The only rule here is "never show what he already owns", the same job exclude=seen does in recsys_svd.py. It strikes out the shoes and the yoga mat. The three that remain on top are the smartwatch, the headlamp and the running socks.

Station 4: mark the list a week later

A list is marked against what the shopper did next, never against ratings the model trained on. That is the time split of Fig. 13.5b. The following week Dev bought three products: the smartwatch, rated 5, running socks, rated 4, and the trail jacket, rated 2. Call a product relevant if he bought it and rated it 4 or 5. Two products are relevant.

  1. Mark each slot. Slot 1, smartwatch: a hit. Slot 2, headlamp: a miss, because he never bought it. Slot 3, running socks: a hit.
  2. Precision@3. Hits divided by the slots shown: 2 ÷ 3 = 0.667.
  3. Recall@3. Hits divided by the relevant products that exist: 2 ÷ 2 = 1.000.
  4. DCG@3. Add up each hit's slot value, 1 ÷ log₂(slot + 1), where log₂ is the base-2 logarithm. Slot 1 is worth 1.000 and slot 3 is worth 0.500, so the total is 1.500.
  5. The best possible DCG@3. Put the two hits in slots 1 and 2: 1.000 + 0.631 = 1.631.
  6. NDCG@3. Divide the real total by the best one: 1.500 ÷ 1.631 = 0.920.

Precision and recall count the same two hits, so they look alike. They divide by different things, and that is the whole difference:

Precision@3 and recall@3 on Dev's list, side by side
Precision@3Recall@3
The question it answersOf the products we showed, how many did he want?Of the products he wanted, how many did we show?
Divides byThe 3 slots on the pageThe 2 products he wanted
Dev's list2 ÷ 3 = 0.6672 ÷ 2 = 1.000
What pulls it downA wasted slot: the headlampA wanted product left off the page
Its ceiling hereOnly 2 relevant products exist, so 0.667 is the best any three-product list can scoreHad Dev loved 6 products, the best possible would be 3 ÷ 6 = 0.500
1 NEIGHBOURS Dev: shoes 5, yoga mat 1 Ana 1.0000 Ben 0.9648 Cho 0.3846 cosine on the 2 shared columns 2 SCORE EVERY PRODUCT smartwatch 4.51 headlamp 4.44 running socks 4.08 shoes 3.93 trail jacket 3.44 foam roller 2.75 yoga blocks 2.14 yoga mat 2.07 socks: 9.593 ÷ 2.3494 = 4.083 headlamp: 6.1538 ÷ 1.3846 = 4.444 3 RULES, THEN TOP 3 struck out, already owned: shoes, yoga mat Dev's homepage 1 smartwatch 2 headlamp 3 running socks slots 4 to 6: not shown 4 NEXT WEEK Dev bought and rated: smartwatch 5 · socks 4 trail jacket 2 ✓ hit, rated 5 ✗ miss, never bought ✓ hit, rated 4 precision@3 = 2 ÷ 3 = 0.667 recall@3 = 2 ÷ 2 = 1.000 NDCG@3 = 1.500 ÷ 1.631 = 0.920 Stations 1 to 3 are the funnel of Fig. 13.1 at toy size. Station 4 is its offline evaluation.
Fig. 13.3d — One shopper through the whole funnel. Dev's two ratings pick his neighbours, the neighbours score eight products, a rule strikes out two, three reach the page, and the following week marks them. Values from rerunning recs_by_hand.py.
  1. Neighbours. Dev's two ratings are compared with each shopper's ratings on the same two products. Ana matches exactly, Ben nearly, and Cho points the other way. The bars are drawn to scale, so Cho's vote counts for well under half of Ana's in station 2.
  2. Scores. Every product gets a similarity-weighted average of the neighbours' ratings. The three highlighted bars are the ones that reach the page. The two worked lines under the bars are the lettered steps above, for the socks and the headlamp.
  3. Rules, then the page. The shoes and the yoga mat are struck out because Dev owns them. The shoes would only have come fourth, so striking them out changes nothing in this top three. It would matter the day one of Dev's own purchases scored highest.
  4. The marking. Next week's purchases decide each slot: two hits and one miss. The three numbers under the page are the lettered steps of station 4. NDCG is below 1 only because the miss sits in slot 2, above a hit.

Notice what NDCG added. Precision@3 is already at its ceiling, so it cannot say the list could be better. NDCG can. Swap the headlamp and the socks, and both hits sit in slots 1 and 2, which lifts NDCG@3 from 0.920 to 1.000.

A recommendation is only a guess until next week's behaviour marks it. Precision divides by what you showed, recall by what they wanted, and NDCG also asks which slot each hit landed in.

The training output showed RMSE falling to 0.75. If RMSE got better, why does this section call it the wrong yardstick for a homepage?

Because RMSE grades every rating it can find, while a homepage is judged only on the order of the few products it shows. On Dev's following week, a plain product average beats the neighbour model on RMSE, 0.674 against 0.882. Yet both models show the same three products in the same order, and both score NDCG@3 0.920.

RMSE, root mean squared error, is the typical size of a miss, measured in stars. It is the number recsys_svd.py printed every five epochs in section 04. Here are its four steps for the neighbour model, on the three products Dev rated the following week:

  1. Find each miss. Actual minus predicted. Smartwatch: 5 − 4.5090 = +0.4910. Running socks: 4 − 4.0832 = −0.0832. Trail jacket: 2 − 3.4444 = −1.4444.
  2. Square each miss. 0.241, 0.007 and 2.086. Squaring stops a +0.5 and a −0.5 from cancelling out. It also makes one big miss count far more than several small ones.
  3. Average the squares. (0.241 + 0.007 + 2.086) ÷ 3 = 2.334 ÷ 3 = 0.778.
  4. Take the square root. √0.778 = 0.882. The root puts the answer back in stars.

Now a second model. It ignores Dev completely and predicts each product's average rating among Ana, Ben and Cho. This is popularity with star ratings attached: every shopper gets the same order. Here are the two models on the same three ratings:

The neighbour model and the product average, scored by RMSE and by the page, measured by recs_by_hand.py
Neighbour modelProduct average
How it predictsSimilarity-weighted neighbours, from the walk aboveEach product's average rating from Ana, Ben and Cho
Smartwatch, actual 54.509, squared miss 0.2414.500, squared miss 0.250
Running socks, actual 44.083, squared miss 0.0073.667, squared miss 0.111
Trail jacket, actual 23.444, squared miss 2.0863.000, squared miss 1.000
RMSE√(2.334 ÷ 3) = 0.882√(1.361 ÷ 3) = 0.674, the winner
Top 3 shown to DevSmartwatch, headlamp, running socksSmartwatch, headlamp, running socks
Precision@3 and NDCG@30.667 and 0.9200.667 and 0.920, a tie
Same order for every shopper?NoYes

Three things RMSE does that a homepage does not care about:

  • It counts products that never reach the page. The trail jacket sits below the top three for both models, off the page. It supplies 2.086 of the neighbour model's 2.334, which is 89% of its squared error.
  • It cannot see a wasted slot. The headlamp in slot 2 was a miss, but Dev never rated it, so there is no number to square. Precision@3 and NDCG@3 both counted that miss.
  • It rewards hedging. Averages sit near the middle of the scale, so they are rarely far wrong. The neighbour model trusted Ana's 4 for the jacket, and Dev disagreed with a 2.
1 WHAT RMSE SEES · squared miss per rated product neighbour model product average smartwatch 0.241 0.250 running socks 0.007 0.111 trail jacket 2.086 1.000 2 jacket: off the page for both models neighbours: √(2.334 ÷ 3) = 0.882 product average: √(1.361 ÷ 3) = 0.674 RMSE's verdict: the product average is better 3 WHAT THE HOMEPAGE SEES · Dev's top 3 neighbour model product average 1 smartwatch 2 headlamp 3 running socks ✓ ✗ ✓ 1 smartwatch 2 headlamp 3 running socks ✓ ✗ ✓ 4 NDCG@3 0.920 NDCG@3 0.920 precision@3 0.667 precision@3 0.667 headlamp in slot 2: a wasted slot, but Dev never rated it, so neither RMSE has a number to square the page's verdict: a tie
Fig. 13.3e — Two models, one shopper, two verdicts. RMSE, on the left, prefers the product average, 0.674 against 0.882. The homepage, on the right, cannot tell the two models apart. Values from rerunning recs_by_hand.py.
  1. The squared misses. One pair of bars per product Dev rated the following week, drawn to scale. The two models are close on the smartwatch. The neighbour model is better on the socks, and the product average hedges its way to a smaller miss on the jacket.
  2. The product nobody shows. The trail jacket's bars are the longest on the picture, yet the jacket sits below the top three for both models and never appears on the page. Most of the RMSE gap comes from a product Dev never sees.
  3. The page. Both models put the same three products in the same order, so every ranking metric gives the same answer for Dev: NDCG@3 0.920 and precision@3 0.667 for both.
  4. The miss RMSE cannot count. The headlamp took slot 2, and Dev never bought it. With no rating there is no error to square, so RMSE ignores the only wasted slot on the page.

The product average also fails a test that neither score here runs. It shows every shopper the same order, which is the bestseller wall Priya started with. Coverage, the last health row of the cheat sheet, is the number that catches it, as marker 1 of Fig. 13.2d did for the real model.

The honest limit cuts both ways. RMSE is still a useful training signal, which is why the code prints it: if it stops falling, the model is not learning. And a tie between two models on one shopper proves little on its own. The claim is narrower. A better RMSE does not promise a better page, so choose between models with the ranking metric the page is judged by.

RMSE grades every star it can find; a homepage is graded on the order of the few products it shows. Train with RMSE if you like, but choose between models with a ranking metric.

Priya also wants a "customers who bought this also bought" row on the product page. Is that the same calculation that found Dev his smartwatch?

Nearly. It is the same cosine similarity turned sideways: it compares product columns instead of shopper rows. On the smartwatch page it puts running socks first. And it needs no history from the visitor, only the product on the screen, so it works for Ravi on his first visit.

Dev's homepage asked a question about people: whose row looks like Dev's? The product page asks a question about products: which column looks like the smartwatch's? A product's column lists who bought it. Two products are similar when mostly the same shoppers bought both of them.

Write 1 for bought and 0 for never bought. Cosine similarity on two columns of ones and zeros shrinks to a simple count:

cosine = shoppers who bought both ÷ √(buyers of the first × buyers of the second)

Symbol key: ÷ divide, √ square root, × multiply. The top counts the overlap. The bottom stops a product from scoring high just because it has many buyers.

  1. Count the smartwatch's buyers. Ana and Ben: 2.
  2. Running socks. Bought by Ana, Ben and Cho, so 3. Ana and Ben bought both. Cosine = 2 ÷ √(2 × 3) = 2 ÷ 2.4495 = 0.816.
  3. Headlamp. Bought by Ana and Cho, so 2. Only Ana bought both. Cosine = 1 ÷ √(2 × 2) = 1 ÷ 2 = 0.500.
  4. Yoga mat. Bought by all four shoppers. Ana and Ben bought both. Cosine = 2 ÷ √(2 × 4) = 2 ÷ 2.8284 = 0.707.

The yoga mat is the problem. It scores 0.707 with the smartwatch only because every shopper bought one, including Dev, who rated it 1. A product that everybody buys turns up beside everything. Two common repairs: count only purchases the shopper rated highly, or weight a purchase down when nearly everyone makes it. Here is the first, with a rating of 4 or 5 counting as liked:

Every product's cosine with the smartwatch, counting two ways, measured by recs_by_hand.py
ProductCounting every purchaseCounting liked purchases (4 or 5)
Running socks2 ÷ √(2 × 3) = 0.8162 ÷ √(2 × 2) = 1.000
Shoes2 ÷ √(2 × 4) = 0.7072 ÷ √(2 × 3) = 0.816
Trail jacket1 ÷ √(2 × 2) = 0.5001 ÷ √(2 × 1) = 0.707
Headlamp1 ÷ √(2 × 2) = 0.5001 ÷ √(2 × 1) = 0.707
Foam roller2 ÷ √(2 × 3) = 0.8160 ÷ √(2 × 1) = 0.000
Yoga mat2 ÷ √(2 × 4) = 0.7070 ÷ √(2 × 1) = 0.000
Yoga blocks1 ÷ √(2 × 2) = 0.5000 ÷ √(2 × 1) = 0.000
1 WHO BOUGHT WHAT · read down a column shoes yoga mat jacket smartwatch socks roller blocks headlamp Ana Ben Cho Dev 5 1 4 5 4 3 — 5 4 2 — 4 5 2 1 — 1 5 2 — 2 4 5 3 5 1 — — — — — — smartwatch vs running socks: Ana and Ben bought both bought 2 ÷ √(2 × 3) = 0.816 · liked 2 ÷ √(2 × 2) = 1.000 2 smartwatch vs yoga mat: all four shoppers bought a mat bought 2 ÷ √(2 × 4) = 0.707 · liked 0 ÷ √(2 × 1) = 0.000 bold green: rated 4 or 5, a purchase the shopper liked 3 SIMILAR TO THE SMARTWATCH · cosine counting bought counting liked running socks 0.816 1.000 shoes 0.707 0.816 trail jacket 0.500 0.707 headlamp 0.500 0.707 foam roller 0.816 0.000 yoga mat 0.707 0.000 4 yoga blocks 0.500 0.000 5 Ravi, 0 clicks, on the smartwatch page gets this row: it is keyed to the product, not to the visitor
Fig. 13.3f — "Customers who bought this also bought", computed. The grid is read down its columns instead of across its rows, and every product is scored by how many buyers it shares with the smartwatch. Values from rerunning recs_by_hand.py.
  1. The grid, read downwards. The same ratings as the table above the questions. The shaded columns are the smartwatch, the running socks and the yoga mat. Bold green numbers are ratings of 4 or 5, purchases the shopper liked. Reading down a column tells you who bought that product.
  2. Two comparisons, worked. The socks and the smartwatch share the same two buyers, Ana and Ben, so both ways of counting score them high. The yoga mat shares Ana and Ben too, but only because all four shoppers bought one.
  3. The whole row, both ways. Each product gets two bars. Counting every purchase puts the foam roller level with the socks at 0.816. Counting only liked purchases separates them: socks 1.000, foam roller 0.000.
  4. The product everybody buys. The yoga mat drops from 0.707 to 0.000. Nobody who liked the smartwatch liked the mat, and Dev, who rated the mat 1, would have found it recommended beside his new watch.
  5. Ravi on the product page. The row belongs to the smartwatch, not to whoever is looking. Ravi's empty history does not matter here, which is why product pages can show a sensible row to a first-time visitor while his homepage cannot.

Now the comparison the question asked for:

Dev's homepage and the smartwatch's product page, side by side
Dev's homepage: shopper to shopperProduct page: product to product
ComparesRows: whose ratings look like Dev's?Columns: which products share buyers with the smartwatch?
The yardstickCosine similarityCosine similarity
Needs the visitor's history?Yes. Ravi, with 0 clicks, gets an empty list, as in Fig. 13.2eNo. It needs only the product on the screen
A brand-new product, item 201InvisibleInvisible too: its column is empty, so every cosine is 0
When the work happensWhen the visitor arrives, from their rowAhead of time: one short list per product

Two honest limits. With four shoppers every cosine is a ratio of tiny counts, so ties are everywhere: the socks and the foam roller both score 0.816. A real store computes these over millions of orders. And product-to-product does nothing for a product nobody has bought. Item 201 still needs the content features of Fig. 13.3b before it can appear at all.

Shopper-to-shopper compares rows and needs the visitor's history. Product-to-product compares columns and needs only the product on the screen. It is the same cosine, asking a different question.

Deprecation radar: the scikit-surprise library that older tutorials lean on is effectively unmaintained and fights modern Python/numpy builds — that's why we wrote FunkSVD by hand (it's ~40 lines). For implicit-feedback factorization at scale the implicit library is the maintained classic; real candidate generation is two-tower + ANN as above.

06 · The second hookThe $1M/Month Inventory Problem

Priya’s half is finished: a funnel, a from-scratch model, a measured bias of 14% coverage, and the 2026 stack that fixes it. The second money machine on this page belongs to a different person at a different company, and it is worth more per month than ShopStream’s whole recommender is worth per year. The beats are the same: a named stake, a naive build, and one failure that is very easy to ship by accident. Read the memo below and hold on to the number he asks for, because every measurement in the rest of this page is judged against it.

Field report · LogiFlow

"We have 10,000 SKUs across 50 warehouses. Every day we're either overstocking — burning $400K a month in holding costs — or under-stocking and losing $600K a month in missed sales. I need demand forecasts accurate to ±5% for the next 30 days, for every product–warehouse pair."

— Carlos Mendez, Head of Supply Chain at "LogiFlow"

A million dollars a month, and the fix is a regression problem with a clock in it. Time series forecasting is the least glamorous, highest-ROI modeling work in industry — and the one where a specific, catastrophic evaluation mistake is easiest to make (that's section 08).

The intuition is highway traffic. If you had to predict traffic on the interstate at 5 pm next Tuesday, you'd instinctively decompose the problem: the road gets busier every year as the city grows (trend); rush hour, the weekend dip, and summer vacations repeat on schedule (seasonality); if traffic was heavy five minutes ago it's probably still heavy (autocorrelation — the recent past predicts the near future); and a random accident is (noise) — the part an honest model must admit it cannot forecast. Every classical forecasting method is a formalization of exactly that read:

observed = trend + seasonality + residual 1 2 3 4
Fig. 13.4 — Decomposition: observed = trend + seasonality + residual. Trend and seasonality are learnable structure; the residual is what an honest model refuses to promise. Your forecast error floor is the residual's size.
  1. The observed series. This is the only line Carlos actually has: one number of demand per day, wobbling. Everything below it is the same data taken apart. The decomposition is not a model of the world; it is a way of asking which parts of that wobble repeat and which parts do not.
  2. The trend. The slow drift, here upward, with the week-to-week wiggle removed. It answers “is the business growing?” and it is the part that tree models cannot extrapolate on their own, which is why section 09 recommends differencing the target before handing it to LightGBM.
  3. The seasonality. The pattern that repeats on a fixed clock: the weekly shape, and over a longer stretch the yearly one. Because it repeats, it is knowable in advance for any future date, which is exactly why dow, month and doy are always legal features.
  4. The residual. What is left when the two learnable parts are subtracted: a small, patternless jitter. This is the honest part of the picture. No amount of modelling removes it, so its size is the floor under your error, and a forecaster claiming to beat that floor is measuring something wrong.
🧠 Brain power

Before reading on: LogiFlow's demand doubles every year, and the December spike grows proportionally — 10% of December's volume, not a fixed 500 units. What breaks in the additive model above?

Reveal the answer

Additive decomposition assumes the seasonal swing is a constant number of units. When the swing scales with the level, you need the multiplicative form observed = trend × seasonality × residual — or, equivalently, take the log of the series, which turns multiplication back into addition and stabilizes the variance. Practically: eyeball whether the seasonal amplitude grows with the level; if yes, log-transform (or set seasonality_mode="multiplicative" in Prophet).

07 · The industry toolProphet, Then What Industry Actually Ships

Carlos needs demand 30 days ahead for 10,000 products in 50 warehouses, to ±5%, because every point of forecast error costs him roughly $40K a month. We have two years of daily history and nothing else. So the job now is to build the forecaster twice, once with the friendly tool and once the way industry ships it, and to score both against the dumbest baseline there is. If neither beats copying what happened five weeks ago, Carlos has bought a compute bill and nothing more.

Meta's Prophet is the friendliest serious entry point: it fits the decomposition you just saw directly — a piecewise trend, Fourier-series seasonalities, and explicit holiday effects — and hands you uncertainty intervals and component plots a stakeholder can read. It also ships its own walk-forward backtesting utilities, which we use here instead of hand-rolling one.

The stack, and why

Before the code, here is every tool this module leans on, and what you would pick instead.

The stack, and why

How many users, items and days of history do you have, and do you need an explanation a manager can read or the last point of accuracy?

What this module uses, what else you could use, and when to switch (as of October 2026)
LayerWe useAlternativesWhy this oneSwitch when
Recommender modelA hand-written FunkSVD in numpyimplicit (ALS), LightFM, Surprise, a two-tower network in PyTorchYou can read all of it and every number matches the by-hand pages. Weakness: a Python loop, so it is slow beyond about 100,000 ratings.More than ~1M ratings: implicit (ALS). Item text, images or session order matter: a two-tower model with an index.
Candidate lookupOne matrix-times-vector in numpyFAISS, pgvector, a managed vector searchExact and one line for 200 items. Weakness: cost grows with the catalog.More than ~100,000 items or answers needed in under 100 ms: an approximate nearest-neighbour index.
Data handlingpandasPolars, DuckDB, SparkEvery example in this course already uses it. Weakness: everything must fit in memory.More than ~10M rows or a 1 GB+ file that will not load: DuckDB or Polars.
Seasonal forecasterProphetstatsmodels ETS and ARIMA, StatsForecast, NeuralProphetReads the trend, weekly and yearly waves and holidays directly, with plots a manager can follow. Weakness: it often loses on accuracy to a tuned gradient-boosted model.Thousands of series on a schedule: StatsForecast is much faster. One series needing intervals: ARIMA/ETS.
Feature-based forecasterLightGBM on lag and rolling featuresXGBoost, MLForecast, DartsHandles price, promotions and weather as plain columns, and trains in seconds. Weakness: you must build lag features by hand and never leak the future.Fewer than ~2 years of history or one clean seasonal series: skip it and use Prophet or a seasonal-naive baseline.
Pretrained forecasterNot used here; named so you know it existsChronos-2, TimesFMZero-shot, no training. Weakness: published rankings come mostly from vendors, so test on your own series.You have hundreds of short series and no time to tune: run one on your backtest and keep it only if it beats LightGBM.
BacktestingWalk-forward windows (Prophet's cross_validation, a hand loop)scikit-learn TimeSeriesSplit, sktime, a random split (wrong)Always trains on the past and tests on the future, as in production. Weakness: slow, because you refit many times.Never switch to a random split for time series; it leaks the future (section 08).

Use the readable tool for each layer first; move to the faster or bigger one only when the named size or speed limit is hit.

Step-by-step: what forecast_prophet.py does, in plain English
  1. Bring in logging, numpy, pandas and the Prophet model class. Also bring in two of Prophet's diagnostics helpers: cross_validation to run the backtest and performance_metrics to score it.
  2. Silence cmdstanpy, the fitting engine underneath Prophet, which otherwise prints a line per iteration.
  3. Define synth_demand(): 730 days of fake daily demand starting 2024-01-01. Add up a slow upward trend, a 7-day wave and a 365-day wave. Add a late-November bump of 40, a mid-December bump of 60, and random noise with spread 5. Clip at zero, round, and return two columns named ds (the date) and y (the value), the names Prophet insists on.
  4. Build a holidays table by hand: Black Friday and Christmas for both years, each with a window. Christmas reaches 10 days back because the rush builds before the day; Black Friday reaches 3 days forward into its weekend.
  5. Split by position, not at random: the first 700 days train, the last 30 days are the holdout the model never sees.
  6. Create a Prophet with weekly and yearly seasonality on and the holiday table attached. Daily seasonality is off: there is one row per day, so there is no within-day pattern. Fit it on the training rows.
  7. Ask for a date frame that extends 30 days past the training data, and predict it. The result has yhat, the forecast, and yhat_lower and yhat_upper, the uncertainty band.
  8. Take the last 30 predictions and line them up with the 30 held-out actuals. Compute MAPE: the average of |actual − forecast| / actual, as a percentage. The np.maximum(actual, 1) stops a zero-demand day from dividing by zero.
  9. Run Prophet's own walk-forward backtest: start with 540 days of history, refit every 60 days, and forecast 30 days ahead each time. That gives three cutoffs and about ninety honestly scored test days.
  10. Print the error per horizon. rolling_window=1 averages over the whole horizon instead of reporting each day separately.
forecast_prophet.pyruns offline
# pip install "prophet>=1.1,<2" "pandas>=2.2"   # NOT "fbprophet" -- renamed in 2021
"""LogiFlow demand forecaster: Prophet with holiday effects and an
honest walk-forward backtest via Prophet's own diagnostics."""
import logging

import numpy as np
import pandas as pd
from prophet import Prophet
from prophet.diagnostics import cross_validation, performance_metrics

logging.getLogger("cmdstanpy").setLevel(logging.WARNING)   # silence fit chatter


def synth_demand(n_days=730, seed=42):
    """Two years of daily demand: trend + weekly + yearly cycles,
    holiday spikes, and noise the model must ADMIT it can't predict."""
    rng = np.random.default_rng(seed)
    dates = pd.date_range("2024-01-01", periods=n_days, freq="D")
    t = np.arange(n_days)
    trend = 50 + 0.05 * t
    weekly = 10 * np.sin(2 * np.pi * t / 7)
    yearly = 20 * np.sin(2 * np.pi * t / 365.25)
    holiday = np.where((dates.month == 11) & (dates.day >= 25), 40, 0) \
            + np.where((dates.month == 12) & (dates.day >= 15), 60, 0)
    y = np.maximum(trend + weekly + yearly + holiday + rng.normal(0, 5, n_days), 0)
    return pd.DataFrame({"ds": dates, "y": y.round()})     # Prophet wants ds/y


holidays = pd.DataFrame({
    "holiday": ["black_friday"] * 2 + ["christmas_rush"] * 2,
    "ds": pd.to_datetime(["2024-11-29", "2025-11-28", "2024-12-25", "2025-12-25"]),
    "lower_window": [0, 0, -10, -10],       # the rush builds 10 days before Christmas
    "upper_window": [3, 3, 0, 0],           # Black Friday bleeds into its weekend
})

if __name__ == "__main__":
    df = synth_demand()
    train, test = df.iloc[:-30], df.iloc[-30:]      # hold out the final month

    model = Prophet(weekly_seasonality=True, yearly_seasonality=True,
                    daily_seasonality=False, holidays=holidays)
    model.fit(train)

    future = model.make_future_dataframe(periods=30)
    forecast = model.predict(future)        # yhat plus yhat_lower / yhat_upper

    yhat = forecast["yhat"].tail(30).to_numpy()
    actual = test["y"].to_numpy()
    mape = np.mean(np.abs(actual - yhat) / np.maximum(actual, 1)) * 100
    print(f"30-day holdout MAPE: {mape:.2f}%")

    # Walk-forward backtest: refit at each cutoff, always predicting forward.
    cv = cross_validation(model, initial="540 days", period="60 days",
                          horizon="30 days")
    print(performance_metrics(cv, rolling_window=1)[["horizon", "mape", "rmse"]])

Before you answer that, look at what the two splits actually do to the calendar.

1 SPLIT BY TIME · every test day after every training day the last 30 days: the holdout 700 training days time flows one way, and the split cuts it exactly once 2 SHUFFLE · 20% of the days scattered in among the rest every test day now has training days on both sides of it the model reads 17 Oct to fill in 16 Oct 3 ZOOM · five October days 14 Oct train 15 Oct train 16 Oct held out 17 Oct train 18 Oct train same model, same features, same 730 days: 9.11% MAPE with the shuffle, 14.53% walking forward.
Fig. 13.4b — The two splits drawn on the calendar. Splitting by time asks the model to do the job it will really do; shuffling asks it to fill in a gap with the answer sitting on both sides. (Both percentages are printed by leakage_trap.py in section 08.)
  1. The honest split. One cut, at day 700. Everything left of the cut trains the model, everything right of it scores the model, and the arrow underneath is the only direction the model is ever asked to look. This is the arrangement the code makes with df.iloc[:-30], and it is the arrangement production lives in every morning.
  2. The shuffle. The same 730 days, with a fifth of them picked at random to be the test set. Nothing about the model changed. Nothing about the features changed. Only the choice of which days are held out, and that alone moves the reported error from 14.53% to 9.11%.
  3. The zoom. Five days in October, with 16 October held out. Both of its neighbours are in the training set, so the model has learned exactly what happened on the 15th and on the 17th. The dashed arrow is the problem: it runs backwards in time. Guessing a value with tomorrow already on the table is interpolation, and no forecaster is ever allowed to do it.

"Can't I use train_test_split on this like everything else? Shuffle, eighty-twenty, done. I've written that line for every model in this course."

— an engineer who has typed train_test_split two hundred times, looking at df.iloc[:-30]

For the classifiers earlier in the course, rows were independent, so shuffling was harmless. Days are not independent. Each day of demand looks like the days around it. Shuffle, and a test day from October has training days from the same week sitting on both sides of it, which is marker 3 in Fig. 13.4b: 16 October is held out and 17 October is in the training set. The model reads the neighbors and fills in the middle. That is interpolation, not forecasting.

Forecasting means guessing 30 days past the last row you have, with nothing on the far side. The only honest test looks the same, and it is marker 1 of Fig. 13.4b: one cut, training on the left, scoring on the right. Train on everything up to a cutoff, score the next block, move the cutoff forward, repeat. That is what iloc[:-30] and cross_validation() do here. The bottom line of that same picture is the price of getting it wrong: 9.11% error with a shuffle, 14.53% walking forward, on identical models and identical features.

Walking forward has an honest downside. It costs several fits instead of one. Each 30-day window is only 30 points, so the numbers are noisy. And it can only test futures that history already contains. With initial="540 days" the backtest here scores about ninety test days out of seven hundred. Fewer, honest numbers still beat one flattering one.

Now the honesty note this module owes you. Prophet is the tool tutorials teach; gradient boosting is what industry mostly ships. As of 2026, tabular demand forecasting at retailers, marketplaces, and logistics companies is dominated by LightGBM/XGBoost over lag and rolling-window features — the approach that swept the M5 forecasting competition and never gave the crown back. The reasons are practical: one global model trains across all 10,000 SKUs at once (pooling strength across products instead of fitting 10,000 fragile little models), and extra columns — price, promotions, weather, stock-outs — drop in as ordinary features. You already know the engine: it's Module 03's trees. Forecasting becomes feature engineering, with one iron rule — every feature must be computable on the day you make the call:

Step-by-step: what forecast_gbm.py does, in plain English
  1. Bring in numpy, pandas and lightgbm, the gradient-boosting library from Module 03. Set HORIZON to 30: the business orders stock 30 days out, so every forecast is 30 days ahead.
  2. Define synth_demand(), the same generator as in forecast_prophet.py: 730 days of trend, weekly and yearly waves, two holiday bumps, and noise.
  3. Define make_features(). This is the whole modeling idea. Turn "what will demand be on day t" into an ordinary table row. Every column must be something you could know 30 days before day t.
  4. Add four lag columns: the value 30, 35, 42 and 63 days earlier. The nearest legal lag is 30. On forecast day, the last sales figure you can see is 30 days before the day you are predicting. Lag 35 is the same weekday five weeks back.
  5. Add a 28-day rolling mean and standard deviation. Shift the series by 30 first, so the window ends 30 days ago rather than today. The anatomy after the code takes this line apart.
  6. Add calendar columns: day of week, month, and day of year. These are known in advance for any future date, so they are always legal features.
  7. Drop the early rows where the lags are empty and reset the index. That is the first 63 days, because lag_63 needs 63 days of history.
  8. Define mape(): the average of |actual − prediction| / actual, as a percentage, guarding against zero.
  9. When run as a script, build the feature table and list every column except the date and the target as a feature.
  10. Walk forward through five 30-day windows, oldest first. For each, train on every row before the window and test on the window. The training set grows each time; the test set is always strictly in the future.
  11. Fit a LGBMRegressor with 400 trees, a learning rate of 0.05 and 31 leaves per tree, predict the window, and score it.
  12. Score the seasonal-naive baseline on the same window: the prediction is simply lag_35, what happened five weeks ago on the same weekday. Print both errors side by side for every window.
  13. Print the mean model error across the five windows.
forecast_gbm.pyruns offline
# pip install "lightgbm>=4.5" "pandas>=2.2"
"""Same job, the way most industry teams ship it in 2026: gradient
boosting over lag + rolling + calendar features, walk-forward validated.
Reuses synth_demand() from forecast_prophet.py (copy it in or import)."""
import numpy as np
import pandas as pd
import lightgbm as lgb

HORIZON = 30            # the business ask: order stock 30 days out


def synth_demand(n_days=730, seed=42):
    rng = np.random.default_rng(seed)
    dates = pd.date_range("2024-01-01", periods=n_days, freq="D")
    t = np.arange(n_days)
    y = np.maximum(50 + 0.05 * t + 10 * np.sin(2 * np.pi * t / 7)
                   + 20 * np.sin(2 * np.pi * t / 365.25)
                   + np.where((dates.month == 11) & (dates.day >= 25), 40, 0)
                   + np.where((dates.month == 12) & (dates.day >= 15), 60, 0)
                   + rng.normal(0, 5, n_days), 0)
    return pd.DataFrame({"ds": dates, "y": y.round()})


def make_features(df, horizon=HORIZON):
    """Every feature must be knowable on forecast day. lag_1 would silently
    assume you know tomorrow's sales -- so the nearest legal lag is
    `horizon` days back."""
    out = df.copy()
    y = out["y"]
    for lag in (horizon, horizon + 5, horizon + 12, horizon + 33):
        out[f"lag_{lag}"] = y.shift(lag)            # lag_35 = same weekday, 5 wks back
    out["rmean_28"] = y.shift(horizon).rolling(28).mean()   # window ENDS 30 days ago
    out["rstd_28"] = y.shift(horizon).rolling(28).std()
    out["dow"] = out["ds"].dt.dayofweek             # calendar: known in advance
    out["month"] = out["ds"].dt.month
    out["doy"] = out["ds"].dt.dayofyear
    return out.dropna().reset_index(drop=True)


def mape(actual, pred):
    return float(np.mean(np.abs(actual - pred) / np.maximum(actual, 1)) * 100)


if __name__ == "__main__":
    data = make_features(synth_demand())
    features = [c for c in data.columns if c not in ("ds", "y")]

    scores, end, n_splits = [], len(data), 5
    for k in range(n_splits, 0, -1):                # oldest test window first
        lo, hi = end - k * HORIZON, end - (k - 1) * HORIZON
        train, test = data.iloc[:lo], data.iloc[lo:hi]
        model = lgb.LGBMRegressor(n_estimators=400, learning_rate=0.05,
                                  num_leaves=31, verbose=-1)
        model.fit(train[features], train["y"])
        pred = model.predict(test[features])
        actual = test["y"].to_numpy()
        naive = test[f"lag_{HORIZON + 5}"].to_numpy()   # seasonal naive: 5 wks back
        scores.append(mape(actual, pred))
        print(f"split {n_splits - k + 1}  {test['ds'].iloc[0].date()} .. "
              f"{test['ds'].iloc[-1].date()}   GBM {scores[-1]:5.2f}%"
              f"   naive {mape(actual, naive):5.2f}%")
    print(f"\nmean GBM MAPE over {n_splits} windows: {np.mean(scores):.2f}%")

One line in that feature table is the difference between a model you can run and a model you cannot. It is worth seeing on a calendar before you read it as code.

1 FORECAST MORNING · the freshest sales figure you can have is day t − 30 day t − 30 day t 2 y.shift(30).rolling(28).mean() days t−57 … t−30 · legal 3 rolling(28) with no shift days t−27 … t · includes today everything right of t − 30 is unknown on forecast morning The legal window has to end 30 days before the day you are predicting. One call to .shift(30) is the whole difference between a model and a lie.
Fig. 13.4c — The same 28-day average, placed two ways. Shifted first, it ends a month before the day being predicted and can always be computed. Unshifted, it runs right up to the day itself, which is data nobody has on forecast morning. (Horizon 30 days and window 28 days are the values in forecast_gbm.py.)
  1. The line you cannot cross. Carlos orders stock 30 days ahead, so on the morning of the decision the newest sales figure in the warehouse system is 30 days old. Everything to the right of that line exists in the historical file but will not exist when the model actually runs. The shading marks it as off limits.
  2. The legal window. shift(30) moves the whole series along by a month first, so the 28-day average ends where the data ends: days t−57 to t−30. It is less fresh than you would like, and it is the freshest thing that is real. Say the whole phrase out loud when you read the line, because the column name rmean_28 does not mention the shift at all.
  3. The illegal window. Drop the shift and the same 28 days slide forward into the forbidden zone, ending on the day being predicted. Measured on this data, it does not even score better: 15.43% against the legal window's 14.53% (feature_leak_cost.py). That is what makes it dangerous. The backtest raises no objection and hands you no warning, and production cannot compute it at all, so the model either crashes or is fed a stale value and quietly falls apart. This is the single most common leak in forecasting code.
Anatomy of a leakage-safe feature — the line that decides whether the model can run in production
out["rmean_28"]1 = y.shift(horizon)2.rolling(28)3.mean()4
  1. The new column. A 28-day average of recent demand, one value per row. The name says the window width, not the lag. Say "rolling mean, 28 days, ending 30 days ago" out loud when you read it. Otherwise you will forget the shift is there.
  2. The shift. Move the whole series down by horizon rows, so each row sees the value from 30 days earlier. This is the leakage guard. On the morning you forecast day t, the freshest sales figure you can have is from 30 days before t. Write shift(1) and the backtest looks superb, and the feature cannot be computed when the model actually runs.
  3. The window. Average the 28 rows ending at the already-shifted row, so the window covers day t−57 through day t−30. Call rolling(28) without the shift and the window includes today's value, which is the single most common leak in forecasting code.
  4. The reduction. Collapse the window to one number, the recent level. The .std() sibling on the next line captures how jumpy demand has been. The first rows come out empty because there is not yet 28 days of history. dropna() removes them, so the table is shorter than the raw series.
Sharpen your pencil

Score a forecast by hand once, and "beat the baseline" stops being a slogan. Here are three days from the test window, inside the Christmas rush of 2025. For each day you get the actual demand, the seasonal-naive guess and the gradient-boosting model's guess. The naive guess is whatever happened 35 days earlier, on the same weekday. Every number here comes from three_days_by_hand.py.

Fri 19 Dec · actual 136 · naive 63 · model 120.7naive error 73 / 136 = 0.5368 · model error 15.3 / 136 = 0.1122
Sat 20 Dec · actual 127 · naive 58 · model 120.7
Sun 21 Dec · actual 134 · naive 60 · model 120.7
MAPE = average of the three errors × 100, naive:
MAPE, model:

Each error is |actual − guess| divided by the actual. Work to four decimal places. Then answer: what exactly is the baseline copying on these three days, and why does that make it more than half wrong?

Check your answers
Sat 20 Decnaive |127 − 58| / 127 = 69 / 127 = 0.5433 · model |127 − 120.7| / 127 = 6.3 / 127 = 0.0493
Sun 21 Decnaive |134 − 60| / 134 = 74 / 134 = 0.5522 · model |134 − 120.7| / 134 = 13.3 / 134 = 0.0989
MAPE, naive(0.5368 + 0.5433 + 0.5522) / 3 = 1.6323 / 3 = 0.5441, so 54.41%
MAPE, model(0.1122 + 0.0493 + 0.0989) / 3 = 0.2604 / 3 = 0.0868, so 8.68%
actual demand seasonal naive model forecast 1 2 all three days sit inside the December rush 60 80 100 120 140 units 73 = 53.68% 69 = 54.33% 6 = 4.93% 74 = 55.22% 13 = 9.89% Fri 19 Dec Sat 20 Dec Sun 21 Dec Fri: naive 53.68% · model 11.22% Sat: naive 54.33% · model 4.93% Sun: naive 55.22% · model 9.89% 3 MAPE — naive 54.41% · model 8.68%
Fig. 13.4d — The three days you just scored by hand, taken from the test window’s Christmas rush. The naive guess is a flat copy of five weeks earlier, when the rush had not started; the model has the calendar columns, so it leans into the rise. Values from rerunning three_days_by_hand.py.
  1. The stale copy. Five weeks before Friday 19 December is Friday 14 November, an ordinary autumn day: 63 units. The rush has not started there, so the baseline copies a quiet week into the busiest one and lands 73 units short. Copying the past works only while the past looks like the present.
  2. The rush. All three days sit inside the December rush the data generator builds in from 15 December. The model has the month and day-of-year columns, and last year’s December in its training rows, so it lifts its forecast to about 121 units on all three days. It is still 5 to 15 units low: it knew the rush was coming, not how big it would be.
  3. The score. Averaging the three daily errors gives 54.41% for the baseline and 8.68% for the model. Two warnings ride along. MAPE divides by the actual, so a near-zero day can blow the average up on its own, and three days is an anecdote: over the whole 30-day window the model scores 27.19% against the baseline’s 32.27%, and over five walk-forward windows 14.04% against 17.84%.

On all three days the baseline is more than half wrong, because five weeks earlier was an ordinary November week. That is the honest shape of a seasonal-naive rule: strong while nothing changes, useless across the edge of an event.

The model is not brilliant either. It answers about 121 units on each of the three days, 5 to 15 units low, because it learned the rush from a single previous December. It beats the baseline here by a factor of six, and on the quiet week just before, 8 to 12 December, the two swap places: the baseline averages 13.4% and the model 21.5%.

Two cautions the arithmetic makes visible. MAPE divides by the actual, so a day with tiny demand can turn a small miss into an enormous percentage. That is why section 09 recommends WAPE alongside it. And three days is an anecdote. The backtest in the code scores five windows of thirty days. The mean over those 150 days is the number you quote.

On this series both approaches land in the same low-teens MAPE neighborhood, with the seasonal-naive baseline ("predict what happened 5 weeks ago, same weekday") around 18% — always print that baseline; a forecaster that can't beat it is a liability with a compute bill. Expect the worst split to be the one covering the December rush: the backtest doesn't just score the model, it tells you where it's weak. Choosing between the two tools is a judgment call you should be able to defend:

Decision table: Prophet vs gradient boosting vs the rest (as of Aug 2026)
OptionChoose whenAvoid whenTypical cost
ProphetA handful of series; strong holiday/seasonal structure; stakeholders need readable components and uncertainty bands; missing data and outliers abound.Thousands of related series; accuracy is the only KPI; you have rich exogenous features.Minutes to fit; near-zero engineering.
LightGBM + lag featuresMany related series (one global model); price/promo/weather features available; accuracy is king — the M5-winning recipe.One short series; no feature-engineering appetite; you need honest extrapolation of a strong trend (trees can't — difference or detrend the target first).Feature pipeline + backtest harness; still cheap to train.
Seasonal naiveAlways — as the baseline every model must beat.Never skip it.One line.
ARIMA / statsforecastSingle stable series; statistical rigor and intervals matter; interviewers ask about it.Large panels; heavy exogenous structure.Cheap; requires stationarity care.
TS foundation models (Chronos, TimesFM)Zero-shot forecasts across thousands of cold-start series; fast first pass.You have history and features — tuned GBMs still win most tabular bake-offs as of Aug 2026.Awareness level: know they exist, benchmark before trusting.

Questions you might be asking now

The feature code, the anatomy and the decision table above move quickly through lags, windows, trend and leaks. The questions below slow down on one real forecast: Tuesday 23 December 2025, in the Christmas rush. Every answer uses the same five weeks of demand from the page's own synth_demand() series, and every number comes from rerunning the script named in each caption.

The five weeks every answer below uses: daily demand from synth_demand(), 20 October to 23 November 2025, one row per week. On the morning Carlos forecasts 23 December, these are the newest figures that exist.
Week startingMonTueWedThuFriSatSunWeek total
20 Oct70706669565357441
27 Oct57657868496060437
3 Nov63688174756062483
10 Nov68818280635860492
17 Nov74867974696169512
What exactly are lag_35 and rmean_28? Work them out by hand for one real day.

A lag is an old value copied into today's row: lag_35 is the demand 35 days earlier. rmean_28 is the average of the 28 days that end 30 days before the day being predicted. For Tuesday 23 December both come straight out of the five weeks above: lag_35 is 86, and rmean_28 is 1,924 ÷ 28 = 68.71.

Pick the day to forecast: Tuesday 23 December 2025. Carlos orders 30 days ahead, so the forecast is made on the morning of Sunday 23 November. The bottom-right cell of the table, 69, is the newest sales figure that exists that morning. Every feature for 23 December must come from that cell or from cells before it.

  1. lag_30. Count back 30 days from 23 December: Sunday 23 November, the last cell. The value is 69, the freshest one allowed.
  2. lag_35. Count back 35 days, five whole weeks: Tuesday 18 November, in the last row. The value is 86.
  3. lag_42. Six whole weeks back: Tuesday 11 November. The value is 81.
  4. lag_63. Nine whole weeks back: Tuesday 21 October, in the first row. The value is 70.
  5. rmean_28, the window. The 28 days ending on 23 November run from 27 October to 23 November. That is exactly the last four rows.
  6. rmean_28, the sum. Add the four week totals: 437 + 483 + 492 + 512 = 1,924.
  7. rmean_28, the average. 1,924 ÷ 28 = 68.71.

The code gets the same numbers with two pandas calls. y.shift(35) slides the whole column down 35 rows, so each row receives the value from 35 days earlier. y.shift(30).rolling(28).mean() slides by 30 first, then averages each run of 28 rows. Its sibling rstd_28 is the standard deviation of the same 28 values, how far they typically sit from 68.71: here 9.33.

Why three of the four lags land on a Tuesday

Demand has a weekly shape. In the table, Tuesdays and Wednesdays run high and Saturdays run low; the trend question below measures that shape. A value from the same weekday carries the shape into the row for free. 35, 42 and 63 are whole numbers of weeks, so they land on Tuesdays. 30 is not. lag_30 is there because it is the newest value allowed.

Why the window is 28 days and not 30

28 days is exactly four weeks, so the window holds every weekday exactly four times. The high Tuesdays and the low Saturdays cancel, and the average moves only when the level of demand moves. A 30-day window holds two weekdays five times. Which two changes every day, so the average wobbles as the window slides.

Measured on the generator's weekly wave alone, with no noise and no trend, the 28-day average stays at 0.00 on every day. The 30-day average wanders by up to 0.59 units.

On the real noisy series the gap is small. The day-to-day change of the 28-day mean has a standard deviation of 0.668 units, against 0.740 for the 30-day mean. Four whole weeks is a tidy choice, not a big win.

1 FORECAST MORNING, SUN 23 NOV · the newest data for Tue 23 Dec Mon Tue Wed Thu Fri Sat Sun 20 Oct 70 70 lag_63 66 69 56 53 57 27 Oct 57 65 78 68 49 60 60 3 Nov 63 68 81 74 75 60 62 10 Nov 68 81 lag_42 82 80 63 58 60 17 Nov 74 86 lag_35 79 74 69 61 69 lag_30 3 rmean_28 1,924 ÷ 28 = 68.71 27 Oct – 23 Nov 2 35, 42, 63 days back: whole weeks, all Tuesdays 30 days later Tue 23 Dec 2025 the day being forecast 4 28 days = 4 weeks: each weekday counted 4 times, weekly wave left over 0.00 30 days = 4 weeks + 2: two weekdays counted 5 times, wobble up to 0.59
Fig. 13.4f — The five weeks drawn as a calendar, with every feature for Tuesday 23 December picked out of it. Four cells become the four lags; the last four rows become the 28-day mean. Values from rerunning forecast_row_by_hand.py.
  1. Forecast morning. Carlos decides on Sunday 23 November, 30 days before the day he needs stock for. The bottom-right cell is the newest figure in the building that morning, and it is lag_30. Nothing to the right of it, or below it, exists yet.
  2. The Tuesday lags. lag_35, lag_42 and lag_63 are five, six and nine whole weeks back, so all three are Tuesdays: 86, 81 and 70. They carry the high-Tuesday shape of the week into a row about a Tuesday.
  3. The 28-day window. The bracket covers the last four rows, 27 October to 23 November. Their totals add to 1,924, and 1,924 ÷ 28 = 68.71. The first row is outside the window; it is in the picture only because lag_63 reaches back that far.
  4. Why 28. Four whole weeks count every weekday four times, so the weekly wave cancels exactly. A 30-day window counts two weekdays five times, and the pure wave leaves up to 0.59 units of wobble in its average.

A lag copies one old cell into today's row; a rolling mean averages a run of old cells. Both must end on or before forecast morning, which for Carlos is 30 days before the day being predicted.

Walk one forecast all the way through: what does the model actually do with that row for 23 December, and how wrong does it end up?

The model reads nine numbers, adds up 400 small trees, and forecasts 100.45 units. Real demand that day was 140, so it missed by 39.55 units, which is 28.25%. Copying five weeks ago would have missed by 38.57%. About 21 of the model's units came from the three calendar columns alone.

Station 1: forecast morning

Sunday 23 November. LogiFlow's files hold every sales day up to and including that one, and nothing after it. Carlos needs a number for Tuesday 23 December, 30 days out.

Station 2: make_features() builds one row

Six of the nine columns come from the five weeks in the table. The other three come from the calendar, which is known years in advance.

The row for Tuesday 23 December 2025, printed by forecast_row_by_hand.py
ColumnValueWhere it comes from
lag_3069Sunday 23 November
lag_3586Tuesday 18 November
lag_4281Tuesday 11 November
lag_6370Tuesday 21 October
rmean_2868.71Average of 27 October to 23 November
rstd_289.33Standard deviation of the same 28 days
dow1Tuesday; Monday is 0
month12December
doy357The 357th day of the year

Read the value column the way the model sees it. Six numbers describe a calm autumn, with demand in the 60s, 70s and 80s. Only dow, month and doy say that this is Christmas week.

Station 3: the model turns the row into one number

The model is leakage_trap.py's gradient-boosted trees, the same model behind the December window's 26.56%. It was trained on 637 rows, from 4 March 2024 to 30 November 2025, so it has seen exactly one December.

It holds 400 small decision trees. Each tree sends the row down a few yes-or-no questions about its columns, such as whether doy is above some value, and adds a small correction to a running total. For this row the total comes to 100.45.

Station 4: how much of that number is the calendar?

Keep the six lag and window values, and change only month and doy to their 23 November values, 11 and 327. The same model now says 79.44. So the calendar columns lift this forecast by 100.45 − 79.44 = 21.01 units. They are the only way Christmas enters the row.

Station 5: mark it

  1. The model's miss. |140 − 100.45| = 39.55 units. The vertical bars mean "ignore the sign".
  2. As a share of the actual. 39.55 ÷ 140 = 0.2825, so 28.25%.
  3. The seasonal naive guess. It is lag_35, 86. |140 − 86| = 54 units, and 54 ÷ 140 = 0.3857, so 38.57%.
  4. Last year, for scale. 23 December 2024 sold 126, and that day is in the training rows.
1 FORECAST MORNING Sun 23 Nov sales known up to and including today 2 THE ROW one row, nine columns lags 69 · 86 · 81 · 70 rmean 68.71 · rstd 9.33 Tue · month 12 · doy 357 3 THE MODEL 400 small trees trained 4 Mar 2024 to 30 Nov 2025 forecast 100.45 WHERE 100.45 SITS · units of demand on Tue 23 Dec 2025 60 150 Nov calendar: 79.44 naive, lag_35: 86 model 100.45 23 Dec 2024: 126 actual 140 calendar columns add 21.01 4 model miss 39.55 = 28.25% 5 naive miss 54 = 38.57% trained on one December: the model knew Christmas week is busy, not how busy
Fig. 13.4g — One forecast, station by station. The top strip is what happens on 23 November; the number line is how the answer looks a month later. Values from rerunning forecast_row_by_hand.py.
  1. Forecast morning. Everything the model will ever know about 23 December is fixed on this day. It is the line drawn at marker 1 of Fig. 13.4c, turned into a date.
  2. The row. Nine numbers. The lags and the window describe the five calm weeks in the table; only the highlighted calendar line mentions December. This row is the model's entire view of the future.
  3. The model. 400 small trees, trained on everything up to 30 November, turn the row into 100.45. It is gradient boosting from scikit-learn, as in leakage_trap.py, so LightGBM in forecast_gbm.py would print a somewhat different number.
  4. The calendar's share. The same row with November's month and day of year comes out at 79.44. The 21.01 between the two dots is what dow, month and doy added: the model's whole idea of Christmas.
  5. The misses. Both brackets end at the real 140. The model is 39.55 short, and copying five weeks ago is 54 short. The model beat the baseline and still missed by more than a quarter.

The model beat the naive guess and still fell about 40 units short, below even last year's 126. From its one December it learned that December is busy, but not where the rush starts. The whole December window shows it:

The December walk-forward window split in two, measured by forecast_row_by_hand.py. The average miss is prediction minus actual.
Part of the windowMAPEAverage miss
1 to 14 December, before the rush35.33%+25.41 units: too high
15 to 30 December, the rush18.89%−27.11 units: too low
The whole window26.56%The number in Fig. 13.4e

So the worst window in Fig. 13.4e is not simply a missed rush. The model spread "December is busy" across the whole month: too high before the 15th, and too low after it. One day is still an anecdote, and 26.56% is the figure to quote. The single row is for seeing what each column does.

Follow one row through the model and you see what each column contributes. Here the lags said "calm autumn", the calendar said "Christmas", and one December of history could not say how big.

Is seasonality the same thing as trend? On a chart they both just look like demand going up.

No. Seasonality is a shape that repeats on a fixed clock and cancels out over one full cycle. Trend is a drift that never comes back. The difference decides what a model can learn. A tree given only calendar columns and trained on 2024 under-forecast every month of 2025 by about 18 units: one year of trend.

Start with the five weeks. Two things are happening in them at once, and a little arithmetic pulls them apart:

  1. Average each week. 441 ÷ 7 = 63.00, 437 ÷ 7 = 62.43, 483 ÷ 7 = 69.00, 492 ÷ 7 = 70.29 and 512 ÷ 7 = 73.14. A week holds every weekday once, so the weekly highs and lows cancel inside each average. What is left is the level.
  2. Subtract each day's own week average. In the week of 17 November, Tuesday is 86 − 73.14 = +12.86 and Saturday is 61 − 73.14 = −12.14.
  3. Average the five Tuesdays. (+7.00 + 2.57 − 1.00 + 10.71 + 12.86) ÷ 5 = 32.14 ÷ 5 = +6.43.
  4. Repeat for every weekday. The seven averages are the weekly shape, called the seasonal index. They add up to 0.00, because a season cancels over one cycle.
The weekly shape from five weeks, next to the true weekly wave the generator used, printed by trend_vs_season.py
MonTueWedThuFriSatSun
From the five weeks−1.17+6.43+9.63+5.43−5.17−9.17−5.97
The generator's true wave0.00+7.82+9.75+4.34−4.34−9.75−7.82

Five noisy weeks recover the shape to within 2 units on every day.

Now the level. The week averages rose from 63.00 to 73.14, which looks like trend. Mostly it is not. The generator knows its own parts: over these 35 days the trend added 1.70 units, and the yearly season added 6.66 as its wave climbed out of an autumn low. Five weeks of a yearly season look exactly like a trend.

Seasonality and trend, side by side
SeasonalityTrend
What it isA shape that repeats on a fixed clock: the week, the yearA slow drift in one direction
Over one full cycleAdds up to zero: the seven weekday values sum to 0.00Keeps adding: 0.05 units a day, 18.25 a year, in this generator
In the five weeksWednesday +9.63, Saturday −9.17+1.70 units
A future dateLooks like the same date one cycle earlierSits at a level no past date ever had
Where a model gets itdow, doy and month, all known in advanceNothing a tree can extend on its own

What a tree does with each

Train the page's tree model on 2024 with only three columns, dow, doy and month, then ask it for every day of 2025. Seasonality carries over, because a December Wednesday in 2025 looks like one in 2024. Trend does not. The average miss is −18.00 units, and every month sits between −16.2 and −20.0. One year of trend is 0.05 × 365 = 18.25 units.

The reason is how a tree answers. Its leaves hold values learned from training rows, so it has no way to reach a level that 2024 never showed. Adding a day-counter column does not help: the miss stays at −18.00, because every day of 2025 falls past the last counter value the tree ever split on.

1 THE WEEKLY SHAPE · repeats, and sums to 0 from the five weeks generator's true wave −1.17 Mon +6.43 Tue +9.63 Wed +5.43 Thu −5.17 Fri −9.17 Sat −5.97 Sun five noisy weeks recover it within 2 units on every day 2 THE LEVEL · each week's average 60 70 63.00 62.43 69.00 70.29 73.14 20 Oct 27 Oct 3 Nov 10 Nov 17 Nov true level moved: trend +1.70, yearly season +6.66 3 A TREE GIVEN ONLY THE CALENDAR · trained on 2024, asked for every month of 2025 0 Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec −18.25 4 every month misses by −16.2 to −20.0 units; the average miss over 2025 is −18.00 dashed line: one year of trend, 0.05 × 365 = 18.25 units
Fig. 13.4h — Seasonality and trend pulled apart. Top left, the weekly shape, which repeats and sums to zero. Top right, the level, which drifts. Bottom, what a tree does with each: the calendar carries the season into 2025, and the trend is missing from every month. Values from rerunning trend_vs_season.py.
  1. The weekly shape. Filled bars are the seasonal index worked out by hand above; outlined bars are the wave the generator really used. They agree within 2 units. Up days and down days balance, so the seven values sum to 0.00.
  2. The level. Each dot is one week's average, so the weekly shape has already cancelled out of it. The climb from 63.00 to 73.14 looks like trend, but the generator says only 1.70 of the rise was trend and 6.66 was the yearly season.
  3. Twelve months of the same miss. A tree trained on 2024's calendar alone gets the shape of 2025 right and the level wrong. Every bar hangs the same distance below zero, between −16.2 and −20.0 units.
  4. One year of trend. The dashed line is 0.05 × 365 = 18.25 units, the amount the generator's trend adds in a year. The bars sit on it. The missing level is exactly the part that never repeats.

Why you cannot simply subtract the trend first

The textbook fix, in the decision table above, is to remove the trend before the tree sees it, then add it back. That only works if you can measure the trend. A straight line fitted to 2024 alone has a slope of −0.0002 units a day, against a true +0.05, because one year of a yearly season hides the trend completely. Detrending with that line leaves the miss at −18.07.

That is the honest limit of the whole idea. Telling a yearly season from a trend needs at least two full years, and more is better. Even the two years here give a slope of +0.0353, closer but still short of +0.05, because the yearly wave still tilts a straight line fitted across it.

Seasonality repeats, so the calendar can carry it; trend never repeats, so a tree cannot. And a season watched for less than two full cycles looks just like a trend.

The anatomy says shift(1) would make the backtest look superb. How much would a leaky feature really have flattered the score?

It depends, and that is the lesson. Moving every feature to yesterday with shift(1) made the five windows report 10.96% instead of the honest 14.53%. Dropping the shift from the 28-day mean made them report 15.43%, slightly worse. You cannot find a leak by looking at the score. Only the forecast-morning question finds it.

Both leaks are the kind drawn at marker 3 of Fig. 13.4c. Here is what each one does to the row for 23 December, whose honest version the previous answer walked through. The split is the same five windows every time; only the feature table changes.

The same row and the same five windows with three feature tables, measured by feature_leak_cost.py
Legal: shift(30)shift(1): everything ends yesterdayNo shift on the 28-day mean
Newest laglag_30 = 69, from 23 Novlag_1 = 148, from 22 Declag_30 = 69, from 23 Nov
Next laglag_35 = 86, from 18 Novlag_6 = 143, from 17 Declag_35 = 86, from 18 Nov
28-day mean68.71, from 27 Oct to 23 Nov101.82, from 25 Nov to 22 Dec102.64, from 26 Nov to 23 Dec
Forecast for 23 Dec, actual 140100.45128.11126.48
Mean MAPE over the five windows14.53%10.96%15.43%
Computable on 23 November?YesNoNo

Look at the forecast row first. On 23 December both leaks look brilliant: 128.11 and 126.48, against the honest 100.45 and a truth of 140. The leaked columns simply contain the rush. The unshifted 28-day mean covers 26 November to 23 December, so it holds all 28 days after forecast morning, not only today's value.

Now the bottom line. Averaged over the five windows, shift(1) flatters the score by 3.57 points, but the unshifted mean makes it 0.90 points worse. Window by window the unshifted mean swings both ways: 6.24% against the legal 14.90% in the September window, and 19.37% against 8.89% in the August one.

1 WHERE EACH 28-DAY WINDOW SITS forecast morning, 23 Nov 23 Dec 20 Oct 23 Nov legal · mean 68.71 2 shift(1) · mean 101.82 no shift · mean 102.64 3 the legal window ends before the morning line; both leaked windows sit in data that does not exist yet 4 MEAN MAPE, SAME FIVE WINDOWS ±5% target legal 14.53% shift(1) 10.96% no shift 15.43% window by window: Aug legal 8.89, no shift 19.37 Sep legal 14.90, no shift 6.24 the score moved both ways
Fig. 13.4i — Two leaks, measured. Left, where each 28-day window sits against forecast morning for 23 December. Right, what each feature table does to the same five walk-forward windows. Values from rerunning feature_leak_cost.py.
  1. Forecast morning. The dashed line is 23 November. The shaded area to its right is data that does not exist when Carlos makes the forecast, and the second dashed line is the day being predicted.
  2. The legal window. shift(30) puts the 28 days entirely left of the morning line. Its average, 68.71, describes a calm autumn, which is why the honest forecast for the rush was low.
  3. The leaked windows. shift(1) and the unshifted mean both sit inside the shaded area. Their averages, 101.82 and 102.64, already contain the Christmas rush, which no model could know on 23 November.
  4. The scores. One leak lowers the error from 14.53% to 10.96%. The other raises it to 15.43%, after beating the legal table in September and losing badly in August. None of the three bars reaches Carlos's ±5%.

Had the team shipped shift(1), the slide would have said 10.96%, and the model could not have run at all. On 23 November nobody has 22 December's sales. That is the production failure the anatomy describes, and no backtest shows it.

So a leak cannot be caught by its effect on the score: the score can rise, fall or barely move. Module 02 found the same thing, where one leak moved the AUC by 0.0000. The reliable check is the forecast-morning question, asked of every column: could I have computed this on the morning of the forecast?

The honest limit: this is five windows of one synthetic series. On real data a leak often does flatter the backtest, sometimes absurdly, as the SpendAmount column did in Module 02 with an AUC of 1.000. The point is not that leaks are harmless. It is that their direction is unpredictable, so the score is no detector.

A leaky feature can make the backtest look better, worse or the same, so the score cannot find it. Only asking "could I have known this on forecast morning?" of every column can.

08 · Watch it break, againThe Random-Split Trap

We have a number to give Carlos and it looks good. Before it goes on a slide we have to ask how it was measured, because the split you have used for every model in this course is the one thing you must never do to data with a clock in it. This section runs the same model on the same features twice and changes only the split. The two answers differ by more than Carlos’s entire ±5% error budget, which is how a broken forecaster ships behind a green dashboard.

Here is the mistake that ships broken forecasters: evaluating with the same random train/test split you'd use for classification. Time flows one way. Shuffle the rows and your training set contains December while your test set contains October — the model has literally seen the future.

Every test day sits between training days, so the model interpolates neighbors instead of extrapolating forward, and your metric inflates. Let's measure the lie.

Same features, same model family, same data — the only thing that changes is the split (this demo uses sklearn's HistGradientBoostingRegressor, the same algorithm family as LightGBM, so it needs no extra installs):

Step-by-step: what leakage_trap.py does, in plain English
  1. Bring in numpy, pandas and scikit-learn's HistGradientBoostingRegressor, the same tree-boosting family as LightGBM with no extra install. Also bring in train_test_split, the function this script exists to warn you about.
  2. Reuse synth_demand() and make_features() unchanged from forecast_gbm.py, so the only thing that can differ between the two experiments is the split.
  3. Build the feature table, then separate X (every feature column) from y (the demand to predict).
  4. The wrong way: call train_test_split with shuffle=True. It scatters 20% of the days at random into the test set, each one surrounded by training days from the same week.
  5. Fit one boosted model on the shuffled training rows and print its MAPE on the shuffled test rows. This is the flattering number.
  6. The right way: walk forward through five 30-day windows, oldest first. For each window, fit a fresh model on every row strictly before it. iloc keeps the row order equal to the time order.
  7. Score each window and collect the five errors. Print their mean, which is what production will feel like, and their maximum, which is the December window.
leakage_trap.pyruns offline
# pip install "scikit-learn>=1.5" "pandas>=2.2"
"""The inflated-metric trap: score the SAME model on the SAME features
twice -- once with a random split, once respecting the arrow of time."""
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.model_selection import train_test_split

HORIZON = 30


def synth_demand(n_days=730, seed=42):
    rng = np.random.default_rng(seed)
    dates = pd.date_range("2024-01-01", periods=n_days, freq="D")
    t = np.arange(n_days)
    y = np.maximum(50 + 0.05 * t + 10 * np.sin(2 * np.pi * t / 7)
                   + 20 * np.sin(2 * np.pi * t / 365.25)
                   + np.where((dates.month == 11) & (dates.day >= 25), 40, 0)
                   + np.where((dates.month == 12) & (dates.day >= 15), 60, 0)
                   + rng.normal(0, 5, n_days), 0)
    return pd.DataFrame({"ds": dates, "y": y.round()})


def make_features(df, horizon=HORIZON):
    out = df.copy()
    y = out["y"]
    for lag in (horizon, horizon + 5, horizon + 12, horizon + 33):
        out[f"lag_{lag}"] = y.shift(lag)
    out["rmean_28"] = y.shift(horizon).rolling(28).mean()
    out["rstd_28"] = y.shift(horizon).rolling(28).std()
    out["dow"] = out["ds"].dt.dayofweek
    out["month"] = out["ds"].dt.month
    out["doy"] = out["ds"].dt.dayofyear
    return out.dropna().reset_index(drop=True)


def mape(actual, pred):
    return float(np.mean(np.abs(actual - pred) / np.maximum(actual, 1)) * 100)


if __name__ == "__main__":
    data = make_features(synth_demand())
    features = [c for c in data.columns if c not in ("ds", "y")]
    X, y = data[features], data["y"]

    # WRONG: shuffling scatters test days BETWEEN training days.
    Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.2, shuffle=True,
                                          random_state=0)
    lie = HistGradientBoostingRegressor(max_iter=400, learning_rate=0.05,
                                        random_state=0).fit(Xtr, ytr)
    print(f"random 80/20 split      MAPE {mape(yte.to_numpy(), lie.predict(Xte)):5.2f}%"
          "   (interpolation, not forecasting)")

    # RIGHT: five walk-forward windows -- train strictly before test.
    scores, end = [], len(data)
    for k in range(5, 0, -1):
        lo, hi = end - k * HORIZON, end - (k - 1) * HORIZON
        m = HistGradientBoostingRegressor(max_iter=400, learning_rate=0.05,
                                          random_state=0).fit(X.iloc[:lo], y.iloc[:lo])
        scores.append(mape(y.iloc[lo:hi].to_numpy(), m.predict(X.iloc[lo:hi])))
    print(f"walk-forward (5 splits) MAPE {np.mean(scores):5.2f}%"
          "   (what production will feel like)")
    print(f"worst split (Dec rush)  MAPE {max(scores):5.2f}%")
Failure mode

One verified run (sklearn 1.9; your numbers may drift by a hair):

random 80/20 split      MAPE  9.11%
walk-forward (5 splits) MAPE 14.53%
worst split (Dec rush)  MAPE 26.56%

The random split reports 9% — you promise Carlos his ±5% is within reach, ship it, and production delivers 14.5% on average and 26.6% in December, the one month when inventory errors cost the most. Nothing about the model was wrong; the measurement was.

This is temporal data leakage, and it has a sneakier cousin: features that peek forward — a rolling mean whose window includes today, a "days until next promotion" column, a target-encoded category computed over the full dataset.

Audit every feature with one question: could I have computed this value on the morning I made the forecast? If the answer is no, that feature is a leak, however good it makes the backtest look. Marker 3 of Fig. 13.4c is what one looks like.

Three numbers, one picture, and Carlos’s whole decision hangs on which of them you put on the slide.

Carlos asked for ±5% 2 random 80/20 split 9.11% 3 walk-forward · 5 windows 14.53% 4 worst window · December 26.56% 0% 10% 20% 30% 1 Same 730 days, same features, same model family. Only the split changed.
Fig. 13.4e — The cost of the wrong split, measured. The flattering number is not a slightly better version of the honest one; it is under half of December’s real error, in the month where being wrong costs Carlos the most. (All three numbers are printed by leakage_trap.py above.)
  1. The target line. Carlos asked for ±5%. It is drawn as a line rather than written as a sentence so you can see that no bar on this picture reaches it. Knowing that before the meeting is the difference between a hard conversation and a broken promise.
  2. The flattering number. 9.11% comes from the shuffled split of Fig. 13.4b, marker 2. It is close enough to ±5% that a team can talk itself into shipping. Nothing produced it except the choice of which days to hold out.
  3. The honest average. 14.53% is what five walk-forward windows report, and it is what production will feel across an average month. It is worse than the promise, and it is the number you can actually defend when someone re-runs the backtest.
  4. The worst window. 26.56% is the December window, the one month where a stock-out or an overstock costs the most money. A mean hides it completely, which is why the chant below insists on reporting the worst window and not just the average.
train test random split ✗ every test day has training neighbors on both sides — the model interpolates split 1 split 2 split 3 ✓ walk-forward: train only on the past, test only on the future — like production time 1 2 3
Fig. 13.5 — Never random-split time data. Walk-forward validation grows the training window and always tests on the next unseen block — the only evaluation that resembles the job the model will actually do.
  1. The scattered test days. One long strip of days with the held-out ones sprinkled through it. Each dark block has training days immediately before and after it, which is the arrangement drawn close up at marker 3 of Fig. 13.4b. This is what train_test_split(shuffle=True) produces, and it is what reported 9.11%.
  2. The three walk-forward splits. Read them downwards. The training block grows by one window each time and the test block moves one window further into the future, so every score is earned on days the model had never seen. Five of these windows are what reported 14.53%, and the December one reported 26.56%.
  3. The time arrow. Every block on this picture is laid out along real calendar time, not row number. That is the whole discipline: keep the rows in date order, cut once, never let a later row train a model that will be scored on an earlier one.

One more subtlety this discipline buys you for free: the same rule applies to recommender evaluation, which sends us straight back to Priya. Interactions are timestamped events — train on the past, test on each user's future clicks. Randomly splitting interactions leaks taste from the future into training, just more quietly, and Fig. 13.5b is that leak drawn on user 42's own eleven ratings.

1 BY TIME · hold out each user’s latest clicks 9 earlier clicks: train 2 latest: test user 42’s 11 ratings, in the order they happened 2 AT RANDOM · hold out any two of the eleven 3 TASTE LEAKS BACKWARDS · the same mistake, just much quieter
Fig. 13.5b — The split rule, applied to Priya’s half of the page. A recommender is evaluated honestly the same way a forecaster is: train on what each user did first, score on what they did next. (User 42 rated 11 items in the run printed in section 04.)
  1. The honest cut. Order user 42’s 11 ratings by timestamp and hold back the last two. The model learns from nine earlier choices and is asked to guess the next two, which is precisely what it will be asked to do on the live homepage tomorrow morning.
  2. The random cut. Pick any two of the eleven instead. Now some of the training ratings happened after the test ratings, and the model has been told what this person grew to like before being asked what they liked first.
  3. Why it is quieter than the forecasting version. There is no calendar on the screen and no obvious December window, so nothing looks wrong. The metric simply comes out better than production will ever be. The fix is the same three words as for Carlos: split by time.

Split by time.

Never shuffle.

Lag only what you could have known that morning.

Beat the naive baseline first.

Report the worst window, not just the mean.

Split by time: Fig. 13.4b, marker 1, where every test day sits after every training day. Never shuffle: marker 3 of the same figure, where 17 October sits on the right of the held-out day and the model reads it. Lag only what you could have known that morning: Fig. 13.4c, marker 1, the shift that keeps the window behind day t minus 30. Beat the naive baseline first: Fig. 13.4d, where copying five weeks ago scores 25.43% and the model scores 6.74%. Report the worst window: Fig. 13.4e, marker 4, December at 26.56%.

09 · Under the hoodThe Math, If You Want It

Both halves are built and both failures are measured: 14% catalogue coverage for Priya, 14.53% MAPE for Carlos. Everything below this line is optional. It is the algebra underneath the two formulas you have already worked by hand, the rating prediction and the error metric, plus the two diagnostics an interviewer may reach for. Skip it and you can still ship both systems. Read it and you can defend every number you just quoted to them.

Matrix factorization and NDCG — optional depth

The factorization. Approximate the ratings matrix R (M users × N items) as R ≈ U·Vᵀ, where U is M×K and V is N×K, with K hidden ("latent") dimensions — typically 16–128. The full prediction for user u and item i:

r̂ui = μ + bu + bi + Pu·Qi

where μ is the global mean rating; bu is the user bias (a harsh grader's ratings run low regardless of taste); bi is the item bias (a blockbuster runs high regardless of who's rating); and Pu·Qi — the dot product of the user's taste vector with the item's feature vector — measures pure alignment. Pulling μ, bu, bi out first matters: without them, the factors waste capacity relearning "some people rate low" instead of learning taste.

Why not textbook SVD? True singular value decomposition needs a complete matrix, and 99.99% of R is missing. Filling blanks with zeros would teach the model that everything unwatched is hated. So we minimize squared error over observed cells only, with L2 regularization strength λ (lambda) to stop the skinny matrices from memorizing:

min Σ(u,i) observed (rui − r̂ui)² + λ(‖Pu‖² + ‖Qi‖² + bu² + bi²)

SGD on this objective gives exactly the update rules in the code: with error e = r − r̂ and learning rate η (eta), each visit nudges bu ← bu + η(e − λbu), and Pu ← Pu + η(e·Qi − λPu) (symmetrically for Qi) — move each parameter in the direction that shrinks this example's error, minus a leak toward zero.

NDCG@K, the ranking metric that respects position.

Discounted cumulative gain sums each recommended item's relevance, damped by how far down the list it sits: DCG@K = Σi=1..K reli / log₂(i+1) — position 1 divides by 1, position 10 by ~3.46, so burying a great item costs you.

Dividing by the ideal ordering's DCG (IDCG) normalizes to 0–1, making scores comparable across users with different numbers of relevant items. The log discount is a modeling choice, not a law: it roughly matches how sharply user attention decays down a list.

Stationarity, ACF/PACF, and error metrics — optional depth

Stationarity. A series is stationary when its statistical properties (mean, variance, autocorrelation) don't drift over time. Classical models like ARIMA require it. Standard fixes: differencing — model yt − yt−1 instead of yt, which removes trend (and is the honest fix for tree models' inability to extrapolate a trend) — and the log transform, which stabilizes variance that grows with the level. The Augmented Dickey-Fuller (ADF) test formalizes the check: p < 0.05 → reject the unit root, treat as stationary.

ACF and PACF are the classical diagnostic plots. The autocorrelation function asks "how does today correlate with k days ago?"; the partial ACF asks the same after removing the influence of the days in between. In ARIMA(p,d,q) terms, the PACF's cutoff suggests p (autoregressive order), the ACF's suggests q (moving-average order), and d is how many times you differenced. Even if you ship LightGBM, the ACF is how you discover which lags to engineer — it's a feature-selection tool now.

Error metrics. MAPE = mean of |y − ŷ| / |y| × 100 — beloved by business because "12% off" needs no translation, but it explodes when actuals near zero and punishes over-forecasting more than under. For intermittent demand prefer WAPE = Σ|y − ŷ| / Σ|y|, which weights errors by volume and never divides by a tiny day. Quote both; per-SKU dollar-weighted WAPE is what supply-chain teams actually steer by.

There are no dumb questions

My users don't rate anything — they just click, scroll, and buy. Where do ratings come from?
They mostly don't, and industry moved on: this is implicit feedback. You treat interactions as weighted positive signals (view = 1, add-to-cart = 3, purchase = 5), treat non-interaction as weak negative evidence, and train with confidence-weighted factorization or ranking losses (BPR) that only care about ordering pairs, not predicting a star value. The architecture is unchanged — the loss function is what adapts.
Why learn matrix factorization if two-tower models run the show?
Because MF is a two-tower model — the degenerate case where each tower is a plain embedding lookup with no features. Every concept transfers: latent vectors, dot-product affinity, ANN serving, cold start. Interviewers ask MF because it isolates the idea; if you can whiteboard r̂ = μ + bu + bi + Pu·Qi, the modern stack is "same thing, deeper encoders."
Shouldn't an LLM or a foundation model just do the forecasting now?
Time-series foundation models (Chronos, TimesFM and kin) are real and useful for zero-shot forecasts on series with no history. But on tabular demand data with features, tuned gradient boosting still wins most published and internal bake-offs as of Aug 2026. Benchmark before believing either camp — the backtest harness you built today is exactly that benchmark.
Do I still need ARIMA, or is that exam trivia?
Working knowledge, yes: stationarity, differencing, and what (p,d,q) mean still come up in interviews and in reading older systems. In practice, reach for a maintained AutoARIMA (statsforecast) as a baseline rather than hand-tuning orders. Deprecation radar: install prophet, not the pre-2021 fbprophet package, and skip scikit-surprise for the reasons above.
These are both "small data" demos. What changes at 10,000 SKUs × 50 warehouses?
Less than you'd fear. The GBM approach scales by design — it's one global model over a long table with sku and warehouse as categorical features. The work moves to engineering: feature pipelines, a backtest that runs in CI, per-segment error dashboards, and retraining cadence. That's Module 12's discipline applied to a classical model — and it's why forecasting roles hire engineers, not just statisticians.

Both halves of this page end in a sentence somebody repeats in a meeting. Here is the arithmetic behind each one, drawn so you can see where every figure comes from.

1 SHOPSTREAM · AN UPLIFT STORY 2,000,000 visitors a month 1.2% CTR today → 24,000 views 6% CTR target → 120,000 views +96,000 extra product views × 3% conversion = 2,880 orders × $40 order value = $115,200 ≈ $1.4M a year 2 3 LOGIFLOW · A COST STORY $1,000,000 a month burned $400K holding + $600K stockouts both scale with forecast error MAPE 25% → 15% = 40% less error ≈ $400,000 a month returned ≈ $40,000 per point of MAPE ≈ $4.8M a year 4 Priya’s number is a lift you still have to prove, with an A/B test in quarter one. Carlos’s number is a saving you can only claim as far as the honest backtest reaches: 14.53%, not 9.11%. Both of these are sentences a CFO repeats. Neither survives a metric measured the wrong way.
Fig. 13.5c — The two business cases as arithmetic. One is revenue you do not have yet; the other is cost you are already paying. (Every input is a number from the two hook memos; the conversion rate and order value are ShopStream’s stated averages.)
  1. The traffic you already have. Nothing in the left column asks for more visitors. The 2 million are already arriving and already seeing the same 20 bestsellers; the entire case is about what happens on the page they land on. That is why a recommender is an easier sell than an acquisition campaign.
  2. The click-through gap. Everything hinges on this one step: 1.2% to 6% is 96,000 extra product views a month. Note what 6% is not — it is nowhere near the 35% the leaders reach, so the estimate is deliberately unambitious. Quote a target you can miss and still look good.
  3. The cost that is already burning. Carlos is spending $1M a month whether or not anyone builds anything, split between stock sitting in warehouses and sales lost when shelves are empty. Both costs are sized by how wrong the forecast is, so cutting the error is cutting the bill.
  4. The dollars per point. Dividing the monthly cost by the error gives roughly $40,000 for each percentage point of MAPE. That single figure is the one Carlos will remember, and it is also the one that makes Fig. 13.4e dangerous: quoting 9.11% instead of 14.53% promises him about $217,000 a month that does not exist.
Boardroom translation

Recommenders are an uplift story. The widely cited McKinsey figures — roughly 35% of Amazon purchases and 75% of Netflix viewing driven by recommendations — put personalization at 20–35% of revenue for the majors. You don't promise that on day one; you promise the climb toward it.

ShopStream math, drawn as Fig. 13.5c, markers 1 and 2: 2M monthly visitors × (6% − 1.2%) homepage CTR = 96,000 extra product views a month; at 3% conversion and $40 average order, that's ≈ $115K/month ≈ $1.4M/year — from a CTR target still far below the leaders, validated by an A/B test in quarter one.

Forecasting is a cost story. LogiFlow burns $1M/month ($400K holding + $600K stockouts), and both costs scale, to first order, with forecast error: safety stock is sized off error variance, and stockouts happen when error exceeds the buffer.

Cut MAPE from 25% to 15% — a 40% error reduction — and the first-order estimate returns ≈ $400K/month, which is markers 3 and 4 of Fig. 13.5c. The CFO sentence: "every point of forecast error is worth about $40K a month at our scale, and here's the backtest showing which ten points we can buy."

10 · The labBuild the Real Thing

Priya’s recommender and Carlos’s forecaster both exist now, as forty-line teaching files fed on synthetic data. The lab swaps in real data and makes you keep the audits: catalogue coverage for the recommender, walk-forward windows for the forecaster. Pick one track and finish it. What an interviewer probes is not whether you can define NDCG, it is whether you have ever measured your own model honestly and disliked the answer.

LAB 13 — Pick one track: recommender with a bias audit, or a forecast bake-off

Track A — Movie recommender with a bias audit (offline). Mission: extend recsys_svd.py to the public MovieLens-100K ratings set (a free download; 943 users × 1,682 movies) and evaluate it like production would.

  • Temporal split — hold out each user's latest interactions by timestamp; no random splitting of interactions
  • Implement precision@10 and NDCG@10; your MF model beats a popularity-only baseline on both (report the table)
  • Popularity-bias audit: catalog coverage@10 and the share of top-10 slots taken by the top-1% most-rated movies — for baseline and model
  • Apply one mitigation (score penalty or diversity re-rank) and measure its price: NDCG delta vs coverage gain
  • Cold-start path: a user with zero history gets a sane fallback list, covered by a test
  • README documents: metrics, 3 failure modes found, fix iterations

Track B — Demand forecast bake-off (offline). Mission: turn this module's forecasting scripts into one harness that crowns a winner honestly.

  • Walk-forward backtest: ≥ 5 splits × 30-day horizon over ≥ 2 years of daily data (the synthetic generator or any public daily series)
  • Three contenders on identical splits, chosen with the decision table from section 07: seasonal naive, Prophet (with holidays), LightGBM (with lag/rolling features) — MAPE and WAPE per split
  • Feature audit table in the README: every GBM feature marked "available at forecast time?" with the lag arithmetic shown
  • Best model beats the seasonal-naive baseline by ≥ 15% relative error; identify the worst window and explain why it's worst
  • README documents: backtest table, 3 failure modes found, fix iterations

Stretch goals: (A) build a two-tower variant using sentence-transformer embeddings of movie titles/genres as the item tower — item cold start solved with content. (B) add a P90 quantile forecast (LightGBM objective="quantile") and convert it into a safety-stock recommendation in units and dollars.

11 · Interview radarHow This Shows Up in Interviews

Interview radar

ML system design is one of the three system-design prompt types at FAANG-tier companies, and "design a recommender" is its most common opener. Classical-ML judgment questions remain baseline screens even for GenAI roles.

"Design a recommendation system for [video app / marketplace / job board]."

The real test The most common ML system-design opener — can you draw the whole funnel and the loop around it, not just name a model?

Strong answer Draw the same three stages as Fig. 13.1, in order, then the loop that keeps them honest:

  • Candidate generation — multiple sources in parallel: two-tower ANN retrieval, co-occurrence, and popular-in-context
  • Ranking — a feature-rich ranker, typically a GBM or a small neural net, scoring the shortlist
  • Business-rule re-ranking — applied last: rules like "don't show what they already bought"
  • The loop around it — interaction logging, temporal offline eval (NDCG@K), online A/B on CTR and conversion, and a latency budget stated per stage

Land it Naming the offline–online metric gap and the feedback-loop risk is what separates a senior answer from a mid-level one.

"A new user signs up — what do they see?"

Strong answer Cold start is layered, not solved by one trick, so walk the layers in order:

  • Popularity-within-context first — what's popular on this surface right now is a sane day-one default
  • Contextual features — device, geo, referrer, and hour of day personalize before any history exists
  • Onboarding preference capture — ask for a few interests up front and use them immediately
  • Content embeddings for new items — and mentioning LLM-extracted features here is a current-sounding touch
  • Explore/exploit bandits — deliberately spend a few slots to buy information about the user

Land it Define when a user "graduates" to the personalized path — that boundary is the design decision most candidates forget to make.

"Why can't you random-split time-series data?"

Strong answer Temporal leakage. A shuffled split lets the model train on the future and interpolate between neighboring days, so the metrics are inflated before you've done anything else wrong.

Quote your own experiment, the three numbers leakage_trap.py printed: the random split reported 9.11% MAPE, walk-forward showed the real 14.53% — and 26.56% in the holiday window, exactly where the forecast matters most.

Answer with the fix, walk-forward validation, and then volunteer the sneaky variant: features that peek forward, like unshifted rolling windows or target encoding computed over the full dataset, leak even when the split itself is correct.

Land it Mention that the same rule applies to recommender evals — hold out each user's latest interactions, never a random sample — and you're done.

"Your precision@10 is 0.9 but users are bored. What's happening?"

The real test Metric-choice judgment — do you trust a headline number, or do you know what it can hide?

Strong answer Accuracy metrics can be gamed by popularity: a recommender that shows everyone the same blockbusters scores high on precision while teaching users there's nothing new here. So check the health metrics next to it — coverage, diversity, serendipity, and position-aware NDCG — and suspect the feedback loop, because a model trained on its own recommendations keeps narrowing what it shows. Then offer the forecasting twin: "MAPE looks great but December was a disaster" is the same failure, a healthy average hiding a broken segment.

Land it The cure is the same in both worlds: per-window backtests and volume-weighted WAPE over headline averages.

"When would you NOT use a neural recommender / a foundation model forecaster?"

The real test Vendor-agnostic judgment — the fashionable option is on the table, so name what keeps you off it.

Strong answer With a small catalog or sparse traffic, popularity plus rules wins outright — there isn't enough interaction data for a neural model to learn anything better. Above that, a strong MF or GBM baseline is cheaper to run, easier to debug, and easier to explain to the business than a neural system. Neural only pays off when you have rich features and real scale to feed it.

Land it It's the same logic as "when not OpenAI's API" from Module 06 — baseline first, complexity only when the eval demands it.

Quick reference — Recommenders and forecasting

The stack rule
Readable first: numpy and pandas for recommenders, Prophet then LightGBM for forecasts, a walk-forward backtest always. Switch only at a named size: ~1M ratings, ~100,000 items, ~10M rows.
The three recommender families
Collaborative: people like you liked this. Content-based: this is similar to what you liked. Hybrid: both, and what everyone actually ships.
multi-stage funnel
Candidate generation (millions → hundreds, must be fast) then ranking (hundreds → a few, can be expensive). Every large recommender has this shape.
matrix factorization
Learn a vector for each user and each item so that their dot product predicts the rating. The classic collaborative method.
cold start
A new user or new item has no history, so collaborative filtering has nothing to work with. Fixes: popularity fallback, content bootstrapping, and explore/exploit.
Popularity bias
Recommending what is already popular makes it more popular. Coverage and diversity metrics are how you notice it happening: our own run recommended 14% of the catalog.
The ranking metrics
Precision@K · Recall@K · NDCG@K (rewards putting the good ones near the top) · MRR · hit rate@K · coverage.
Forecasting: the split rule
Never shuffle time series. Train on the past, test on the future, or you have leaked tomorrow into yesterday. Audit every feature with the forecast-morning question.
Precision@K vs recall@K
Both count hits in the top K. Precision divides by the K slots shown; recall divides by everything the shopper wanted. Dev's list scored 0.667 and 1.000, worked by hand.
Item-to-item ("also bought")
The same cosine similarity, computed between product columns instead of shopper rows. It needs only the product on screen, so it works for a first-time visitor, but it cannot see a product nobody has bought. Worked example.
Lag feature and rolling mean
A lag copies one old value into today's row; a rolling mean averages a run of old values. For a 30-day forecast both must end at least 30 days back: for 23 December, lag_35 is 86 and rmean_28 is 68.71, by hand.
Seasonality vs trend
Seasonality repeats on a clock and sums to zero over one cycle, so calendar columns carry it. Trend never repeats, so a tree cannot extend it: every month of 2025 came out about 18 units low.

12 · RecapWhat You Can Do Now

  • You can explain collaborative, content-based, and hybrid recommendation — and pick one — in stakeholder language
  • You can sketch the three-stage production funnel with counts and latency budgets, and justify why it exists
  • You can implement matrix factorization from scratch and read its update rules as plain gradient descent
  • You can audit a recommender for popularity bias (coverage, slot concentration) and name four cold-start mitigations
  • You can connect two-tower retrieval to Module 08's embedding search — and say what LLMs add at the edges, without overclaiming
  • You can decompose a series into trend/seasonality/residual and choose Prophet vs LightGBM-with-lags on defensible grounds
  • You can build a walk-forward backtest, prove why random splits lie, and audit features for temporal leakage
  • You can translate both systems into money: CTR-uplift math for the board, MAPE-to-dollars math for the CFO
  • You can walk one shopper from ratings to a marked top-3 list, and say what precision, recall, NDCG and RMSE each notice and miss
  • You can build one forecast row by hand from a calendar of past days, and explain why the season carries into next year while the trend does not
🧠 Flex your memory

From this module: close the page and sketch the recommendation funnel from memory — three stages, the item counts flowing between them, the latency budget per stage, and which stage handles "don't show me what I already bought."

Reaching back to Module 08: a two-tower recommender and your RAG pipeline both end in an ANN index. Write three sentences on what's identical (infrastructure, the retrieve-then-rerank shape) and what differs (what the embeddings mean, and the training signal that shaped them).