Recommenders & Forecasting — The Classic Money-Makers
"Predict what they want before they ask. Predict what will happen before it does."
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.
"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."
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."
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:
| Strategy | The assistant says… | Signal used | Weakness |
|---|---|---|---|
| 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. |
"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.
- 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.
- 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.
- 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.
- 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.
| Stage | In the from-scratch version (section 03, recsys_svd.py) | In the production funnel (section 05) | What flows out |
|---|---|---|---|
| Collect interactions | synth_interactions() fakes 6,000 clicks with a long tail | Event logs: views, add-to-carts, purchases, each with a timestamp | A user × item table that is 99.99% empty |
| Learn representations | FunkSVD().fit(df): one 20-number vector per user and per item | Two-tower training, nightly; item vectors written into an ANN index | Vectors that put similar tastes near each other |
| Candidate generation | None. scores_for() scores all 200 items in one matrix–vector product | User tower at request time, then one ANN lookup, about 10 ms | About 500 candidates |
| Ranking | np.argsort(s)[::-1]: sort by predicted rating, highest first | A gradient-boosted or neural scorer with rich user and item features, about 50 ms | About 50 scored items |
| Business-rule re-ranking | exclude=seen drops what user 42 already rated | Diversity caps, in-stock, margin and freshness rules, about 5 ms | The 10 items shown |
| Evaluation | The coverage@10 audit at the bottom of __main__ | Temporal holdout NDCG@K and coverage offline; A/B tests on click-through online | The number that says which stage to fix |
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.
- 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.
- 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.
- 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.
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.
recsys_svd.py’s own output and settings.)- 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.
- 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.
- 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.
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.
-
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
- Rank the items 1 to 200 and give each a traffic weight
1 / rank0.8; normalise to sum to 1. - Draw a user and an item for every interaction, the items using those weights, so a few items get most of the traffic.
- Build each rating from 3.5 plus a user generosity, an item quality and noise; round and clip to 1–5.
- Drop repeated (user, item) pairs and return a table.
chunk1_data.py (added lines)runs offlineimport 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.normalfor the noise.python chunk1_data.pyprints5350 interactions | 500 users | 200 itemsand three sample rows. Measured. - Rank the items 1 to 200 and give each a traffic weight
-
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
- Store the learning settings: 20 factors, step size, a small penalty, 20 passes, a seed.
- Compute the global average rating
muand map each user and item id to a row number. - Create
P(users × 20) andQ(items × 20) of small random numbers, and zeroed bias arraysbu,bi. - Stack (user row, item row, rating) into one array: the observed cells only.
chunk2_setup.py (added lines)runs offlineclass 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.pyprintsuser table P: (500, 20) item table Q: (200, 20)andguess-the-average RMSE: 0.9936. Measured. Nothing is learned yet. -
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
- Shuffle the triples each pass.
- For each: prediction = average + user bias + item bias + the dot product of the two vectors; error = rating − prediction.
- 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.
- Every fifth pass, print the root-mean-square error.
chunk3_train.py (added lines)runs offlinefor 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.pyprints the error falling:epoch 5/20 train RMSE 0.8821, then0.8175,0.7783,0.7511. Measured. Below the 0.9936 of rung 2, so it learned something. -
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
scores_for: average + the user's bias + every item bias +Q @ P[u].recommend: an unknown user returns an empty list (cold start); otherwise sort best first, skip items already seen, keep the top n.- In the main block, ask for user 42's top 5.
chunk4_recommend.py (added lines)runs offlinedef 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.pyprints, 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. -
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
- Loop over every user and count each item in their top 10.
- Coverage: how many different items appeared at all.
- 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.pyends withcatalog coverage@10: 27/200 items (14%)andtop-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
- Bring in three libraries:
Counterto tally which items get recommended,numpyfor the arithmetic, andpandasto hold the interaction table. - 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. - 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.
- 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.
- Define the
FunkSVDclass and its settings.n_factorsis how many hidden numbers each user and item gets.lris the step size andregthe pull toward zero.n_epochsis how many passes over the data, and a seed makes runs repeatable. - In
fit(), store the global average ratingmu. Then convert user and item ids into row positions withpd.factorize, keeping the lookup lists. - Create the user table
Pand item tableQ, filled with small random numbers. Create two bias arraysbuandbi, filled with zeros. - Stack the (user position, item position, rating) triples into one array. This is the whole training set: only the cells that were observed.
- 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
pucopy keeps the item update honest. - Every five epochs, print the training root-mean-square error, so you can watch it fall.
- Define
scores_for(): predict every item's rating for one user in a single matrix-times-vector operation. This is why serving is fast. - 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 topnas (item, score) pairs. - 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.
- 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.
# 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 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.
- 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.
- 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.
- 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.
pred = self.mu1 + self.bu[u]2 + self.bi[i]3 + self.P[u]4 @5 self.Q[i]6
- 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.
- 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
uis a row position frompd.factorize, not the raw user id. Indexing with the raw id is the classic silent bug here. - 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.
- 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.
- 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. - 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 asself.Q @ self.P[u]. That is a whole table times one vector, which is why serving costs microseconds.
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:
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.
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.)- 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.
- 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.
- 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. - 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.
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:
- Popularity fallback — new users get bestsellers within their context (country, device, referral source, time of day) until signal accrues.
- Content bootstrapping — new items enter via their attributes and embeddings (content-based side of the hybrid); ask new users for three favorite categories at onboarding.
- Explore/exploit — a multi-armed bandit (e.g. Thompson sampling) deliberately spends a small slice of traffic probing the 173 never-recommended items at marker 1 of Fig. 13.2d, and probing new users’ tastes, buying information with a little short-term CTR.
- Re-rank for diversity and coverage — Stage 3 caps items per category, penalizes near-duplicates, and boosts fresh inventory, trading a sliver of predicted relevance for a catalog that actually sells through.
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.
- 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.
- 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.
- 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.
Tonight's talk: Collaborative Filtering and Content-Based Filtering argue over the question, "Who's more important?"
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.
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:
- LLM-generated item features. The item tower is only as good as its inputs, and catalogs are full of terrible metadata. Teams now run every product description through an LLM to extract structured attributes, style tags, and use-case summaries, then embed those. This directly softens item cold start: a brand-new product gets a rich vector from its text alone, before a single click.
- Conversational recommendation. "Something like Severance but lighter, and my partner hates subtitles" is a recommendation query no click matrix can parse. LLM chat surfaces increasingly sit in front of the classic funnel — the LLM interprets intent and constraints, then calls the recommender (often as a tool, Module 09-style) rather than replacing it. The funnel still does the heavy lifting; the LLM is the new front door.
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.
- 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.
- 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.
- 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:
| Metric | The question it answers | Gotcha |
|---|---|---|
| Precision@K | Of the K items shown, what fraction did the user actually engage with? | Ignores rank order within the K and total relevant count. |
| Recall@K | Of everything relevant to this user, what fraction made the top K? | Punishes small K on users with many relevant items. |
| NDCG@K | Are the most relevant items ranked highest? (position-discounted) | The default headline metric; needs graded relevance to shine. |
| MRR | How high is the first relevant item? | Only cares about one item — good for "find the one right answer" UIs. |
| Hit rate@K | Did the user engage with any of the K? | Coarse; fine for quick baselines. |
| Coverage | What share of the catalog ever gets recommended? | The popularity-bias alarm — watch it alongside accuracy, as our audit showed. |
| Serendipity | Are 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.
- 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.
- 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.
- 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.
- 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.
| Shopper | Shoes | Yoga mat | Trail jacket | Smartwatch | Running socks | Foam roller | Yoga blocks | Headlamp |
|---|---|---|---|---|---|---|---|---|
| Ana | 5 | 1 | 4 | 5 | 4 | 3 | — | 5 |
| Ben | 4 | 2 | — | 4 | 5 | 2 | 1 | — |
| Cho | 1 | 5 | 2 | — | 2 | 4 | 5 | 3 |
| Dev | 5 | 1 | — | — | — | — | — | — |
| Dev, the following week (held out) | owned | owned | 2 | 5 | 4 | — | — | — |
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:
- 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.
- 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.
| Product | Who voted | Score | Station 3 | Slot on the page |
|---|---|---|---|---|
| Smartwatch | Ana, Ben | 4.509 | Kept | 1 |
| Headlamp | Ana, Cho | 4.444 | Kept | 2 |
| Running socks | Ana, Ben, Cho | 4.083 | Kept | 3 |
| Shoes | Ana, Ben, Cho | 3.935 | Struck out: Dev owns them | None |
| Trail jacket | Ana, Cho | 3.444 | Kept | 4, not shown |
| Foam roller | Ana, Ben, Cho | 2.753 | Kept | 5, not shown |
| Yoga blocks | Ben, Cho | 2.140 | Kept | 6, not shown |
| Yoga mat | Ana, Ben, Cho | 2.065 | Struck out: Dev owns it | None |
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.
- Mark each slot. Slot 1, smartwatch: a hit. Slot 2, headlamp: a miss, because he never bought it. Slot 3, running socks: a hit.
- Precision@3. Hits divided by the slots shown: 2 ÷ 3 = 0.667.
- Recall@3. Hits divided by the relevant products that exist: 2 ÷ 2 = 1.000.
- 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.
- The best possible DCG@3. Put the two hits in slots 1 and 2: 1.000 + 0.631 = 1.631.
- 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 | Recall@3 | |
|---|---|---|
| The question it answers | Of the products we showed, how many did he want? | Of the products he wanted, how many did we show? |
| Divides by | The 3 slots on the page | The 2 products he wanted |
| Dev's list | 2 ÷ 3 = 0.667 | 2 ÷ 2 = 1.000 |
| What pulls it down | A wasted slot: the headlamp | A wanted product left off the page |
| Its ceiling here | Only 2 relevant products exist, so 0.667 is the best any three-product list can score | Had Dev loved 6 products, the best possible would be 3 ÷ 6 = 0.500 |
- 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.
- 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.
- 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.
- 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:
- 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.
- 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.
- Average the squares. (0.241 + 0.007 + 2.086) ÷ 3 = 2.334 ÷ 3 = 0.778.
- 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:
| Neighbour model | Product average | |
|---|---|---|
| How it predicts | Similarity-weighted neighbours, from the walk above | Each product's average rating from Ana, Ben and Cho |
| Smartwatch, actual 5 | 4.509, squared miss 0.241 | 4.500, squared miss 0.250 |
| Running socks, actual 4 | 4.083, squared miss 0.007 | 3.667, squared miss 0.111 |
| Trail jacket, actual 2 | 3.444, squared miss 2.086 | 3.000, squared miss 1.000 |
| RMSE | √(2.334 ÷ 3) = 0.882 | √(1.361 ÷ 3) = 0.674, the winner |
| Top 3 shown to Dev | Smartwatch, headlamp, running socks | Smartwatch, headlamp, running socks |
| Precision@3 and NDCG@3 | 0.667 and 0.920 | 0.667 and 0.920, a tie |
| Same order for every shopper? | No | Yes |
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.
- 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.
- 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.
- 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.
- 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.
- Count the smartwatch's buyers. Ana and Ben: 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.
- Headlamp. Bought by Ana and Cho, so 2. Only Ana bought both. Cosine = 1 ÷ √(2 × 2) = 1 ÷ 2 = 0.500.
- 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:
| Product | Counting every purchase | Counting liked purchases (4 or 5) |
|---|---|---|
| Running socks | 2 ÷ √(2 × 3) = 0.816 | 2 ÷ √(2 × 2) = 1.000 |
| Shoes | 2 ÷ √(2 × 4) = 0.707 | 2 ÷ √(2 × 3) = 0.816 |
| Trail jacket | 1 ÷ √(2 × 2) = 0.500 | 1 ÷ √(2 × 1) = 0.707 |
| Headlamp | 1 ÷ √(2 × 2) = 0.500 | 1 ÷ √(2 × 1) = 0.707 |
| Foam roller | 2 ÷ √(2 × 3) = 0.816 | 0 ÷ √(2 × 1) = 0.000 |
| Yoga mat | 2 ÷ √(2 × 4) = 0.707 | 0 ÷ √(2 × 1) = 0.000 |
| Yoga blocks | 1 ÷ √(2 × 2) = 0.500 | 0 ÷ √(2 × 1) = 0.000 |
- 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.
- 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.
- 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.
- 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.
- 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: shopper to shopper | Product page: product to product | |
|---|---|---|
| Compares | Rows: whose ratings look like Dev's? | Columns: which products share buyers with the smartwatch? |
| The yardstick | Cosine similarity | Cosine similarity |
| Needs the visitor's history? | Yes. Ravi, with 0 clicks, gets an empty list, as in Fig. 13.2e | No. It needs only the product on the screen |
| A brand-new product, item 201 | Invisible | Invisible too: its column is empty, so every cosine is 0 |
| When the work happens | When the visitor arrives, from their row | Ahead 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.
"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."
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:
- 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.
- 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.
- 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,monthanddoyare always legal features. - 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.
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?
| Layer | We use | Alternatives | Why this one | Switch when |
|---|---|---|---|---|
| Recommender model | A hand-written FunkSVD in numpy | implicit (ALS), LightFM, Surprise, a two-tower network in PyTorch | You 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 lookup | One matrix-times-vector in numpy | FAISS, pgvector, a managed vector search | Exact 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 handling | pandas | Polars, DuckDB, Spark | Every 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 forecaster | Prophet | statsmodels ETS and ARIMA, StatsForecast, NeuralProphet | Reads 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 forecaster | LightGBM on lag and rolling features | XGBoost, MLForecast, Darts | Handles 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 forecaster | Not used here; named so you know it exists | Chronos-2, TimesFM | Zero-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. |
| Backtesting | Walk-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
- Bring in
logging,numpy,pandasand theProphetmodel class. Also bring in two of Prophet's diagnostics helpers:cross_validationto run the backtest andperformance_metricsto score it. - Silence
cmdstanpy, the fitting engine underneath Prophet, which otherwise prints a line per iteration. - 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 namedds(the date) andy(the value), the names Prophet insists on. - Build a
holidaystable 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. - Split by position, not at random: the first 700 days train, the last 30 days are the holdout the model never sees.
- Create a
Prophetwith 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. - Ask for a date frame that extends 30 days past the training data, and predict it. The result has
yhat, the forecast, andyhat_lowerandyhat_upper, the uncertainty band. - 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. - 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.
- Print the error per horizon.
rolling_window=1averages over the whole horizon instead of reporting each day separately.
# 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.
leakage_trap.py in section 08.)- 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. - 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%.
- 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
- Bring in
numpy,pandasandlightgbm, the gradient-boosting library from Module 03. SetHORIZONto 30: the business orders stock 30 days out, so every forecast is 30 days ahead. - Define
synth_demand(), the same generator as inforecast_prophet.py: 730 days of trend, weekly and yearly waves, two holiday bumps, and noise. - 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. - 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.
- 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.
- 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.
- Drop the early rows where the lags are empty and reset the index. That is the first 63 days, because
lag_63needs 63 days of history. - Define
mape(): the average of |actual − prediction| / actual, as a percentage, guarding against zero. - When run as a script, build the feature table and list every column except the date and the target as a feature.
- 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.
- Fit a
LGBMRegressorwith 400 trees, a learning rate of 0.05 and 31 leaves per tree, predict the window, and score it. - 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. - Print the mean model error across the five windows.
# 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.
forecast_gbm.py.)- 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.
- 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 namermean_28does not mention the shift at all. - 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.
out["rmean_28"]1 = y.shift(horizon)2.rolling(28)3.mean()4
- 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.
- The shift. Move the whole series down by
horizonrows, 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. Writeshift(1)and the backtest looks superb, and the feature cannot be computed when the model actually runs. - 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. - 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.
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:
| Option | Choose when | Avoid when | Typical cost |
|---|---|---|---|
| Prophet | A 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 features | Many 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 naive | Always — as the baseline every model must beat. | Never skip it. | One line. |
| ARIMA / statsforecast | Single 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.
| Week starting | Mon | Tue | Wed | Thu | Fri | Sat | Sun | Week total |
|---|---|---|---|---|---|---|---|---|
| 20 Oct | 70 | 70 | 66 | 69 | 56 | 53 | 57 | 441 |
| 27 Oct | 57 | 65 | 78 | 68 | 49 | 60 | 60 | 437 |
| 3 Nov | 63 | 68 | 81 | 74 | 75 | 60 | 62 | 483 |
| 10 Nov | 68 | 81 | 82 | 80 | 63 | 58 | 60 | 492 |
| 17 Nov | 74 | 86 | 79 | 74 | 69 | 61 | 69 | 512 |
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.
- lag_30. Count back 30 days from 23 December: Sunday 23 November, the last cell. The value is 69, the freshest one allowed.
- lag_35. Count back 35 days, five whole weeks: Tuesday 18 November, in the last row. The value is 86.
- lag_42. Six whole weeks back: Tuesday 11 November. The value is 81.
- lag_63. Nine whole weeks back: Tuesday 21 October, in the first row. The value is 70.
- 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.
- rmean_28, the sum. Add the four week totals: 437 + 483 + 492 + 512 = 1,924.
- 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.
- 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.
- 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.
- 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.
- 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.
| Column | Value | Where it comes from |
|---|---|---|
| lag_30 | 69 | Sunday 23 November |
| lag_35 | 86 | Tuesday 18 November |
| lag_42 | 81 | Tuesday 11 November |
| lag_63 | 70 | Tuesday 21 October |
| rmean_28 | 68.71 | Average of 27 October to 23 November |
| rstd_28 | 9.33 | Standard deviation of the same 28 days |
| dow | 1 | Tuesday; Monday is 0 |
| month | 12 | December |
| doy | 357 | The 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
- The model's miss. |140 − 100.45| = 39.55 units. The vertical bars mean "ignore the sign".
- As a share of the actual. 39.55 ÷ 140 = 0.2825, so 28.25%.
- The seasonal naive guess. It is lag_35, 86. |140 − 86| = 54 units, and 54 ÷ 140 = 0.3857, so 38.57%.
- Last year, for scale. 23 December 2024 sold 126, and that day is in the training rows.
- 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.
- 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.
- 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.
- 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.
- 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:
| Part of the window | MAPE | Average miss |
|---|---|---|
| 1 to 14 December, before the rush | 35.33% | +25.41 units: too high |
| 15 to 30 December, the rush | 18.89% | −27.11 units: too low |
| The whole window | 26.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:
- 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.
- 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.
- Average the five Tuesdays. (+7.00 + 2.57 − 1.00 + 10.71 + 12.86) ÷ 5 = 32.14 ÷ 5 = +6.43.
- 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.
| Mon | Tue | Wed | Thu | Fri | Sat | Sun | |
|---|---|---|---|---|---|---|---|
| From the five weeks | −1.17 | +6.43 | +9.63 | +5.43 | −5.17 | −9.17 | −5.97 |
| The generator's true wave | 0.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 | Trend | |
|---|---|---|
| What it is | A shape that repeats on a fixed clock: the week, the year | A slow drift in one direction |
| Over one full cycle | Adds up to zero: the seven weekday values sum to 0.00 | Keeps adding: 0.05 units a day, 18.25 a year, in this generator |
| In the five weeks | Wednesday +9.63, Saturday −9.17 | +1.70 units |
| A future date | Looks like the same date one cycle earlier | Sits at a level no past date ever had |
| Where a model gets it | dow, doy and month, all known in advance | Nothing 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.
- 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.
- 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.
- 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.
- 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.
| Legal: shift(30) | shift(1): everything ends yesterday | No shift on the 28-day mean | |
|---|---|---|---|
| Newest lag | lag_30 = 69, from 23 Nov | lag_1 = 148, from 22 Dec | lag_30 = 69, from 23 Nov |
| Next lag | lag_35 = 86, from 18 Nov | lag_6 = 143, from 17 Dec | lag_35 = 86, from 18 Nov |
| 28-day mean | 68.71, from 27 Oct to 23 Nov | 101.82, from 25 Nov to 22 Dec | 102.64, from 26 Nov to 23 Dec |
| Forecast for 23 Dec, actual 140 | 100.45 | 128.11 | 126.48 |
| Mean MAPE over the five windows | 14.53% | 10.96% | 15.43% |
| Computable on 23 November? | Yes | No | No |
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.
- 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.
- 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.
- 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.
- 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
- Bring in
numpy,pandasand scikit-learn'sHistGradientBoostingRegressor, the same tree-boosting family as LightGBM with no extra install. Also bring intrain_test_split, the function this script exists to warn you about. - Reuse
synth_demand()andmake_features()unchanged fromforecast_gbm.py, so the only thing that can differ between the two experiments is the split. - Build the feature table, then separate
X(every feature column) fromy(the demand to predict). - The wrong way: call
train_test_splitwithshuffle=True. It scatters 20% of the days at random into the test set, each one surrounded by training days from the same week. - Fit one boosted model on the shuffled training rows and print its MAPE on the shuffled test rows. This is the flattering number.
- 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.
ilockeeps the row order equal to the time order. - 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.
# 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}%")
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.
leakage_trap.py above.)- 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.
- 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.
- 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.
- 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.
- 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%. - 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%.
- 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.
- 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.
- 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.
- 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: installprophet, not the pre-2021fbprophetpackage, and skipscikit-surprisefor 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
skuandwarehouseas 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.
- 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.
- 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.
- 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.
- 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.
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.
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
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
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).