Skip to content

Part 6 checkpoint

This checkpoint tests Part 6 as a whole. Each exercise combines ideas from Modules 45 through 49 on the course datasets: you index and route catalog and store data, diagnose collinearity and compress matrices with SVD, optimize models with exact Hessians and hand-built autograd, infer posteriors with Beta–Binomial updating and Metropolis–Hastings MCMC, detect sensor drift with information theory, and separate correlation from causation with CUPED, IPW, Difference-in-Differences, GLMs and Kaplan–Meier survival curves.

How to use it:

  1. Work without your notes first. Read the task and the expected output (or acceptance criteria), then write your code.
  2. Stuck for more than 10 minutes? Open one hint at a time.
  3. Open the solution only after a real attempt. Compare both your numerical checks and your written reasoning against it.
  4. Score yourself with the rubric at the end of the page.

Plan about 7 to 10 hours in total: 15–20 minutes for each of the 3 warm-ups, 30–45 minutes for each of the 6 core exercises and 60–75 minutes for each of the 3 challenges. You can split the work across several sessions.

Exercise Tier Type Modules
P6-01 Warm-up Predict the output 45, 46, 47, 48
P6-02 Warm-up Fix the bug 46, 48
P6-03 Warm-up Write the code 45
P6-04 Core Write the code 45, 46
P6-05 Core Interpret a result 46
P6-06 Core Write the code 46, 47
P6-07 Core Write the code 47, 48
P6-08 Core Fix the bug 48, 49
P6-09 Core Choose and justify 48, 49
P6-10 Challenge Write the code 45, 47
P6-11 Challenge Interpret a result 48
P6-12 Challenge Choose and justify 48, 49

Work in your course project folder with Python 3.12 or newer and the course virtual environment. Make sure the data/ folder from Get the data is present, because every path on this page is relative to it (data/customers.csv, data/sales.csv, and so on). Keep the data dictionary handy to sanity-check row counts and columns. Run each exercise as a standalone script, for example python p6_04.py.

Every exercise starts from this setup block. It imports the standard-library, scientific-computing and modeling packages used in Part 6 and fixes pandas table widths.

import hashlib
import heapq
import math
from collections import defaultdict
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
from scipy import integrate, optimize, spatial, special, stats
from sklearn.feature_selection import mutual_info_classif
from sklearn.linear_model import LogisticRegression, Ridge
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)

Each solution ends with assert checks. Add the same assertions to your own script: a silent exit confirms every numerical and structural invariant passed.

P6-01 · Predict the output: rank, Taylor error, KL asymmetry and DAG order

Section titled “P6-01 · Predict the output: rank, Taylor error, KL asymmetry and DAG order”
Warm-up

Predict the output: this six-part snippet checks matrix rank, a 2nd-order Taylor polynomial of exp⁡(x)\exp(x) around x=0x = 0, the asymmetry of KL divergence versus Jensen–Shannon divergence, lexicographic Kahn topological sort on a pipeline DAG, np.partition (Quickselect) median selection, and the zero-false-negative property of a Bloom filter. Write down all six printed lines before running the code.

Acceptance criteria:

  • Write your prediction for all 6 lines before running the script.
  • Your prediction matches the Output block in the solution line by line.
  • For any line you missed, identify the governing theorem or data-structure invariant and its module.
Starter
A = np.array([[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [1.0, 0.0, 1.0]])
print("rank:", np.linalg.matrix_rank(A))
x = 0.5
t2 = 1.0 + x + 0.5 * x**2
print("taylor_err:", round(math.exp(x) - t2, 4))
p = np.array([0.8, 0.2])
q = np.array([0.5, 0.5])
kl_pq = float(np.sum(p * np.log2(p / q)))
kl_qp = float(np.sum(q * np.log2(q / p)))
m = 0.5 * (p + q)
jsd = 0.5 * float(np.sum(p * np.log2(p / m)) + np.sum(q * np.log2(q / m)))
print(f"kl_asymm: {kl_pq:.4f} != {kl_qp:.4f} | jsd: {jsd:.4f}")
edges = [
("load", "clean"),
("load", "validate"),
("clean", "train"),
("validate", "train"),
]
nodes = ["load", "clean", "validate", "train"]
indeg = dict.fromkeys(nodes, 0)
adj: dict[str, list[str]] = defaultdict(list)
for u, v in edges:
adj[u].append(v)
indeg[v] += 1
heap = [n for n, d in indeg.items() if d == 0]
heapq.heapify(heap)
order = []
while heap:
u = heapq.heappop(heap)
order.append(u)
for v in adj[u]:
indeg[v] -= 1
if indeg[v] == 0:
heapq.heappush(heap, v)
print("topo:", " -> ".join(order))
vals = np.array([42, 15, 88, 7, 29, 63, 19])
k = len(vals) // 2
part = np.partition(vals, k)
print(
"quickselect_median:",
int(part[k]),
"sorted_match:",
bool(part[k] == np.sort(vals)[k]),
)
bits = [0] * 16
for key in ["earbuds", "laptop"]:
for salt in (0, 1):
digest = hashlib.blake2b(f"{salt}:{key}".encode(), digest_size=4)
bits[int(digest.hexdigest(), 16) % 16] = 1
present = all(
bits[
int(hashlib.blake2b(f"{s}:earbuds".encode(), digest_size=4).hexdigest(), 16)
% 16
]
for s in (0, 1)
)
print("bloom_inserted_present:", present)
# TODO: write your prediction for all 6 printed lines before running
Hint 1

Check the rows of A: row 2 is twice row 1, so only two rows are linearly independent. For the Taylor error, the leading omitted term of exp⁡(x)\exp(x) is x3/6≈0.125/6≈0.0208x^3 / 6 \approx 0.125 / 6 \approx 0.0208 plus x4/24≈0.0026x^4 / 24 \approx 0.0026.

Hint 2

A min-heap breaks ties alphabetically between "clean" and "validate". A Bloom filter sets bits to 1 and never clears them, so querying a previously inserted item can never return False.

Solution
A = np.array([[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [1.0, 0.0, 1.0]])
print("rank:", np.linalg.matrix_rank(A))
x = 0.5
t2 = 1.0 + x + 0.5 * x**2
print("taylor_err:", round(math.exp(x) - t2, 4))
p = np.array([0.8, 0.2])
q = np.array([0.5, 0.5])
kl_pq = float(np.sum(p * np.log2(p / q)))
kl_qp = float(np.sum(q * np.log2(q / p)))
m = 0.5 * (p + q)
jsd = 0.5 * float(np.sum(p * np.log2(p / m)) + np.sum(q * np.log2(q / m)))
print(f"kl_asymm: {kl_pq:.4f} != {kl_qp:.4f} | jsd: {jsd:.4f}")
edges = [
("load", "clean"),
("load", "validate"),
("clean", "train"),
("validate", "train"),
]
nodes = ["load", "clean", "validate", "train"]
indeg = dict.fromkeys(nodes, 0)
adj: dict[str, list[str]] = defaultdict(list)
for u, v in edges:
adj[u].append(v)
indeg[v] += 1
heap = [n for n, d in indeg.items() if d == 0]
heapq.heapify(heap)
order = []
while heap:
u = heapq.heappop(heap)
order.append(u)
for v in adj[u]:
indeg[v] -= 1
if indeg[v] == 0:
heapq.heappush(heap, v)
print("topo:", " -> ".join(order))
vals = np.array([42, 15, 88, 7, 29, 63, 19])
k = len(vals) // 2
part = np.partition(vals, k)
print(
"quickselect_median:",
int(part[k]),
"sorted_match:",
bool(part[k] == np.sort(vals)[k]),
)
bits = [0] * 16
for key in ["earbuds", "laptop"]:
for salt in (0, 1):
digest = hashlib.blake2b(f"{salt}:{key}".encode(), digest_size=4)
bits[int(digest.hexdigest(), 16) % 16] = 1
present = all(
bits[
int(hashlib.blake2b(f"{s}:earbuds".encode(), digest_size=4).hexdigest(), 16)
% 16
]
for s in (0, 1)
)
print("bloom_inserted_present:", present)
assert np.linalg.matrix_rank(A) == 2
assert abs((math.exp(x) - t2) - 0.0237) < 1e-3
assert not math.isclose(kl_pq, kl_qp)
assert order == ["load", "clean", "validate", "train"]
assert int(part[k]) == 29
assert present is True
Output
rank: 2
taylor_err: 0.0237
kl_asymm: 0.2781 != 0.3219 | jsd: 0.0731
topo: load -> clean -> validate -> train
quickselect_median: 29 sorted_match: True
bloom_inserted_present: True

How it works:

  1. Row 2 of A is 2 * row 1, and row 3 is independent of row 1, so the rank is 2 (Module 46).
  2. The 2nd-order Taylor polynomial of exe^x at 0 is 1+x+x2/2=1.6251 + x + x^2/2 = 1.625, whereas e0.5≈1.6487e^{0.5} \approx 1.6487, leaving remainder 0.0237≈0.53/6+0.54/240.0237 \approx 0.5^3 / 6 + 0.5^4 / 24 (Module 47).
  3. KL divergence is directional: DKL(P∥Q)=0.2781D_{\mathrm{KL}}(P \| Q) = 0.2781 bits differs from DKL(Q∥P)=0.3219D_{\mathrm{KL}}(Q \| P) = 0.3219 bits. Jensen–Shannon divergence averages both against M=(P+Q)/2M = (P + Q)/2, giving a symmetric bounded score in [0,1][0, 1] bits (Module 48).
  4. After "load" runs, both "clean" and "validate" reach in-degree 0; heapq pops "clean" first alphabetically, and "train" waits until both finish (Module 45).
  5. np.partition(vals, k) implements Quickselect (Introselect): index k holds the exact k-th smallest element (29) in expected O(n)O(n) time without fully sorting the array (Module 45).
  6. Bloom filters allow false positives from hash collisions, never false negatives: every bit set for "earbuds" stays 1, so membership is guaranteed True (Module 45).

P6-02 · Fix the bug: collinear normal equations and QR orthogonal projection

Section titled “P6-02 · Fix the bug: collinear normal equations and QR orthogonal projection”
Warm-up

Fix the bug: an analyst wants to predict total_charges from monthly_charges and tenure_months on data/customers.csv (dropping the 10 rows with missing total_charges), and also compare a Gaussian-prior MAP regression (λ=50\lambda = 50) against sklearn.linear_model.Ridge. Their script has three bugs:

  1. It appends a near-duplicate column monthly_cents = 100 * monthly_charges + 1e-6 * tenure_months without checking matrix rank or condition number.
  2. It solves OLS via explicit np.linalg.inv(X.T @ X) @ X.T @ y instead of reduced QR factorization, losing numerical stability.
  3. In the MAP Ridge equation (X⊤X+λD)w=X⊤y(X^\top X + \lambda D) w = X^\top y, it penalizes the intercept (np.eye(3)) instead of leaving the intercept unpenalized (np.diag([0.0, lam, lam])), so its weights disagree with Ridge(alpha=50.0, fit_intercept=True).

Fix all three issues: report rank and condition number before and after removing the collinear column, solve OLS with np.linalg.qr, verify residual orthogonality max⁡∣X⊤r∣<10−5\max |X^\top r| < 10^{-5}, and verify exact agreement between closed-form MAP and scikit-learn Ridge.

Expected output
collinear: rank=3/4, cond=2.09e+17
cleaned: rank=3/3, cond=211.26
beta_qr: [-1351.53, 22.43, 59.37]
max |X^T r|: 1.28e-06
MAP vs Ridge max diff: 5.23e-12
Starter
df = pd.read_csv("data/customers.csv").dropna(subset=["total_charges"])
y = df["total_charges"].to_numpy()
m = df["monthly_charges"].to_numpy()
t = df["tenure_months"].to_numpy()
m_cents = 100.0 * m + 1e-6 * t
# BUG 1 & 2: collinear column + unstable normal equations
X_bad = np.column_stack([np.ones(len(df)), m, t, m_cents])
beta_bad = np.linalg.inv(X_bad.T @ X_bad) @ X_bad.T @ y
# BUG 3: penalizes the intercept in Gaussian MAP
X_feat = np.column_stack([m, t])
X_std = (X_feat - X_feat.mean(axis=0)) / X_feat.std(axis=0)
lam = 50.0
X_aug = np.column_stack([np.ones(len(df)), X_std])
w_map = np.linalg.solve(X_aug.T @ X_aug + lam * np.eye(3), X_aug.T @ y)
# TODO: diagnose rank/cond, drop m_cents, solve via QR, fix MAP penalty, assert match
Hint 1

Use np.linalg.matrix_rank(X) and np.linalg.cond(X) on both X_bad and X_clean = np.column_stack([np.ones(len(df)), m, t]). With Q, R = np.linalg.qr(X_clean, mode="reduced"), the OLS projection satisfies Rβ=Q⊤yR \beta = Q^\top y.

Hint 2

In scikit-learn, Ridge(alpha=lam, fit_intercept=True) shrinks only the feature slopes, never the intercept. Use pen = np.diag([0.0, lam, lam]) in (X_aug.T @ X_aug + pen).

Solution
df = pd.read_csv("data/customers.csv").dropna(subset=["total_charges"])
y = df["total_charges"].to_numpy()
m = df["monthly_charges"].to_numpy()
t = df["tenure_months"].to_numpy()
m_cents = 100.0 * m + 1e-6 * t
X_bad = np.column_stack([np.ones(len(df)), m, t, m_cents])
cond_bad = np.linalg.cond(X_bad)
rank_bad = np.linalg.matrix_rank(X_bad)
X_clean = np.column_stack([np.ones(len(df)), m, t])
cond_clean = np.linalg.cond(X_clean)
rank_clean = np.linalg.matrix_rank(X_clean)
Q, R = np.linalg.qr(X_clean, mode="reduced")
beta_qr = np.linalg.solve(R, Q.T @ y)
resid = y - X_clean @ beta_qr
max_orth = float(np.max(np.abs(X_clean.T @ resid)))
X_feat = np.column_stack([m, t])
X_std = (X_feat - X_feat.mean(axis=0)) / X_feat.std(axis=0)
lam = 50.0
X_aug = np.column_stack([np.ones(len(df)), X_std])
pen = np.diag([0.0, lam, lam])
w_map = np.linalg.solve(X_aug.T @ X_aug + pen, X_aug.T @ y)
ridge = Ridge(alpha=lam, fit_intercept=True).fit(X_std, y)
w_ridge = np.concatenate([[ridge.intercept_], ridge.coef_])
max_diff = float(np.max(np.abs(w_map - w_ridge)))
print(f"collinear: rank={rank_bad}/{X_bad.shape[1]}, cond={cond_bad:.2e}")
print(f"cleaned: rank={rank_clean}/{X_clean.shape[1]}, cond={cond_clean:.2f}")
print(f"beta_qr: [{beta_qr[0]:.2f}, {beta_qr[1]:.2f}, {beta_qr[2]:.2f}]")
print(f"max |X^T r|: {max_orth:.2e}")
print(f"MAP vs Ridge max diff: {max_diff:.2e}")
assert rank_bad == 3 and cond_bad > 1e8
assert rank_clean == 3 and cond_clean < 500
assert max_orth < 1e-5
assert max_diff < 1e-9
Output
collinear: rank=3/4, cond=2.09e+17
cleaned: rank=3/3, cond=211.26
beta_qr: [-1351.53, 22.43, 59.37]
max |X^T r|: 1.28e-06
MAP vs Ridge max diff: 5.23e-12

How it works:

  1. X_bad has 4 columns but numerical rank 3 and a condition number of 2.09e+17; squaring it into X.T @ X makes the normal matrix numerically singular (Module 46).
  2. Dropping m_cents restores full column rank (3/3) and cuts the condition number to 211.26. Reduced QR projects yy onto col⁡(X)\operatorname{col}(X) directly via Q⊤yQ^\top y without forming X⊤XX^\top X, leaving residuals orthogonal to every column (X⊤r≈0X^\top r \approx 0).
  3. Putting a zero-mean Gaussian prior N(0,τ2I)\mathcal{N}(0, \tau^2 I) on the standardized slopes (and a flat prior on the intercept) adds λ=σ2/τ2\lambda = \sigma^2 / \tau^2 to the non-intercept diagonal of X⊤XX^\top X, matching sklearn.linear_model.Ridge to machine precision (Module 48).

P6-03 · Write the code: Trie catalog autocomplete with Levenshtein typo rescue

Section titled “P6-03 · Write the code: Trie catalog autocomplete with Levenshtein typo rescue”
Warm-up

Write the code: combine three text and streaming data structures from Module 45 on data/products.csv and data/reviews.csv:

  1. Build a Trie class over all 30 product names in data/products.csv (case-insensitive matching, returning original product names in alphabetical order) and query prefixes "m" and "wi".
  2. Write a space-optimized dynamic-programming levenshtein(a, b) function and correct five real review typos ("recieved", "definately", "qualty", "batery", "recomend") against the vocabulary ["received", "definitely", "quality", "battery", "delivery", "recommend"] by picking the minimum edit distance (tie-breaking alphabetically).
  3. Implement a bit-array BloomFilter(size=16384, k=3) using deterministic hashlib.blake2b hashes, insert the first 1,500 review_id values from data/reviews.csv, and measure the false-negative count on those 1,500 IDs and the false-positive rate on the remaining 1,500 IDs.
Expected output
prefix 'm': ['Merino Wool Sweater', 'Mineral Sunscreen SPF 50']
prefix 'wi': ['Wireless Earbuds']
recieved -> received (d=2)
definately -> definitely (d=1)
qualty -> quality (d=1)
batery -> battery (d=1)
recomend -> recommend (d=1)
bloom: fn=0, fp=21/1500 (1.400%)
Starter
products = pd.read_csv("data/products.csv")
reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)
vocab = ["received", "definitely", "quality", "battery", "delivery", "recommend"]
typos = ["recieved", "definately", "qualty", "batery", "recomend"]
# TODO: implement Trie, levenshtein(a, b), and BloomFilter(size=16384, k=3)
# TODO: print autocomplete results, typo corrections + distances, and Bloom fn/fp stats
Hint 1

Store the original product name at a terminal marker such as node["$"] = word inside the Trie, and traverse child characters in sorted() order during DFS so output order is deterministic.

Hint 2

For BloomFilter, hash f"{seed}:{item}".encode() with hashlib.blake2b(..., digest_size=8) for seed in range(k) and take int.from_bytes(digest, "big") % self.size. That avoids Python’s salted built-in hash(), which changes across runs.

Solution
products = pd.read_csv("data/products.csv")
reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)
class Trie:
def __init__(self) -> None:
self.root: dict = {}
def insert(self, word: str) -> None:
node = self.root
for ch in word.lower():
node = node.setdefault(ch, {})
node["$"] = word
def starts_with(self, prefix: str) -> list[str]:
node = self.root
for ch in prefix.lower():
if ch not in node:
return []
node = node[ch]
results: list[str] = []
def dfs(cur: dict) -> None:
if "$" in cur:
results.append(cur["$"])
for ch in sorted(k for k in cur if k != "$"):
dfs(cur[ch])
dfs(node)
return results
def levenshtein(a: str, b: str) -> int:
m, n = len(a), len(b)
dp = list(range(n + 1))
for i in range(1, m + 1):
prev = dp[0]
dp[0] = i
for j in range(1, n + 1):
cur = dp[j]
cost = 0 if a[i - 1] == b[j - 1] else 1
dp[j] = min(dp[j] + 1, dp[j - 1] + 1, prev + cost)
prev = cur
return dp[n]
class BloomFilter:
def __init__(self, size: int = 16384, k: int = 3) -> None:
self.size = size
self.k = k
self.bits = bytearray(size)
def _hashes(self, item: str) -> list[int]:
out = []
for seed in range(self.k):
digest = hashlib.blake2b(f"{seed}:{item}".encode(), digest_size=8).digest()
out.append(int.from_bytes(digest, "big") % self.size)
return out
def add(self, item: str) -> None:
for idx in self._hashes(item):
self.bits[idx] = 1
def __contains__(self, item: str) -> bool:
return all(self.bits[idx] == 1 for idx in self._hashes(item))
trie = Trie()
for name in products["product"]:
trie.insert(name)
hits_m = trie.starts_with("m")
hits_w = trie.starts_with("wi")
vocab = ["received", "definitely", "quality", "battery", "delivery", "recommend"]
typos = ["recieved", "definately", "qualty", "batery", "recomend"]
corrections = {t: min(vocab, key=lambda w: (levenshtein(t, w), w)) for t in typos}
dists = {t: levenshtein(t, corrections[t]) for t in typos}
bf = BloomFilter(size=16384, k=3)
seen_ids = reviews["review_id"].iloc[:1500].tolist()
unseen_ids = reviews["review_id"].iloc[1500:].tolist()
for rid in seen_ids:
bf.add(rid)
false_neg = sum(rid not in bf for rid in seen_ids)
false_pos = sum(rid in bf for rid in unseen_ids)
print("prefix 'm':", hits_m)
print("prefix 'wi':", hits_w)
for typo in typos:
print(f"{typo} -> {corrections[typo]} (d={dists[typo]})")
print(
f"bloom: fn={false_neg}, fp={false_pos}/{len(unseen_ids)} "
f"({false_pos / len(unseen_ids):.3%})"
)
assert hits_m == ["Merino Wool Sweater", "Mineral Sunscreen SPF 50"]
assert hits_w == ["Wireless Earbuds"]
assert corrections["recieved"] == "received" and dists["recieved"] == 2
assert corrections["batery"] == "battery" and dists["batery"] == 1
assert false_neg == 0
assert false_pos / len(unseen_ids) < 0.05
Output
prefix 'm': ['Merino Wool Sweater', 'Mineral Sunscreen SPF 50']
prefix 'wi': ['Wireless Earbuds']
recieved -> received (d=2)
definately -> definitely (d=1)
qualty -> quality (d=1)
batery -> battery (d=1)
recomend -> recommend (d=1)
bloom: fn=0, fp=21/1500 (1.400%)

How it works:

  1. Prefix lookup in a Trie takes O(L)O(L) steps in the prefix length LL, independent of catalog size, and DFS from the matched subtree yields all completions in alphabetical order.
  2. Rolling a single 1D row dp computes exact Levenshtein distance in O(mn)O(mn) time and O(min⁡(m,n))O(\min(m, n)) memory. Notice "recieved" needs 2 single-character edits (delete/insert or two substitutions) because standard Levenshtein counts transpositions as two edits.
  3. With m=16,384m = 16{,}384 bits, k=3k = 3 hashes and n=1,500n = 1{,}500 inserted keys, the theoretical false-positive rate is (1−e−kn/m)k≈(1−e−0.275)3≈1.4%(1 - e^{-kn/m})^k \approx (1 - e^{-0.275})^3 \approx 1.4\%, matching the observed 1.400% with zero false negatives.
Section titled “P6-04 · Write the code: weighted store routing (Dijkstra) and KD-tree neighbor search”
Core

Write the code: combine graph search, spatial indexing and linear-time order statistics across data/stores.csv and data/houses.csv:

  1. Using the undirected store-to-store highway graph given in the starter, implement Dijkstra’s shortest-path algorithm with heapq and find the shortest distance and route from S07 (New York) to S10 (Seattle) and S11 (San Francisco). Print both routes and the city sequence for S07 -> S10.
  2. Standardize ["sqft", "distance_to_center_km", "condition"] on data/houses.csv, build a scipy.spatial.KDTree, query the 5 nearest neighbors (excluding itself) to house H0001, and verify both the neighbor IDs and Euclidean distances match a brute-force NumPy scan to machine precision.
  3. Write an in-place 3-way-partition quickselect(arr, k) function (no sort() or np.median()) to compute the exact median house price in O(n)O(n) expected time, and assert it equals np.median.
Expected output
S07->S10: 4865 km via S07 -> S09 -> S03 -> S01 -> S02 -> S10
cities: New York -> Philadelphia -> Detroit -> Chicago -> Minneapolis -> Seattle
S07->S11: 5175 km via S07 -> S09 -> S03 -> S01 -> S12 -> S11
H0001 5-NN IDs: ['H0157', 'H1105', 'H1299', 'H0315', 'H1850']
max_dist_diff: 0.00e+00
quickselect median price: 376,000 (np.median: 376,000)
Starter
stores = pd.read_csv("data/stores.csv").set_index("store_id")
edges = [
("S07", "S08", 345), ("S07", "S09", 150), ("S09", "S05", 1250),
("S09", "S03", 940), ("S08", "S03", 1140), ("S03", "S01", 455),
("S01", "S02", 655), ("S01", "S05", 1150), ("S01", "S12", 1615),
("S05", "S06", 1065), ("S05", "S04", 1275), ("S04", "S12", 1640),
("S02", "S12", 1475), ("S02", "S10", 2665), ("S12", "S10", 2110),
("S12", "S11", 2015), ("S10", "S11", 1300),
]
houses = pd.read_csv("data/houses.csv")
# TODO: implement dijkstra(start, goal), KDTree vs brute-force 5-NN, and quickselect
Hint 1

In Dijkstra’s loop, skip stale heap entries whenever d > dist.get(u, math.inf) and record prev[v] = u whenever you relax an edge. Because all weights are positive, the first time goal is popped its distance is optimal.

Hint 2

KDTree.query(Z[0], k=6) returns H0001 itself at index 0 (distance 0.0), so slice [1:] for the 5 other neighbors. Because len(houses) is even (3,000), the median averages quickselect(prices, n // 2 - 1) and quickselect(prices, n // 2).

Solution
stores = pd.read_csv("data/stores.csv").set_index("store_id")
edges = [
("S07", "S08", 345),
("S07", "S09", 150),
("S09", "S05", 1250),
("S09", "S03", 940),
("S08", "S03", 1140),
("S03", "S01", 455),
("S01", "S02", 655),
("S01", "S05", 1150),
("S01", "S12", 1615),
("S05", "S06", 1065),
("S05", "S04", 1275),
("S04", "S12", 1640),
("S02", "S12", 1475),
("S02", "S10", 2665),
("S12", "S10", 2110),
("S12", "S11", 2015),
("S10", "S11", 1300),
]
graph: dict[str, list[tuple[str, int]]] = defaultdict(list)
for u, v, w in edges:
graph[u].append((v, w))
graph[v].append((u, w))
def dijkstra(start: str, goal: str) -> tuple[int, list[str]]:
dist = {start: 0}
prev: dict[str, str] = {}
pq: list[tuple[int, str]] = [(0, start)]
while pq:
d, u = heapq.heappop(pq)
if d > dist.get(u, math.inf):
continue
if u == goal:
break
for v, w in graph[u]:
nd = d + w
if nd < dist.get(v, math.inf):
dist[v] = nd
prev[v] = u
heapq.heappush(pq, (nd, v))
path = [goal]
while path[-1] != start:
path.append(prev[path[-1]])
return dist[goal], list(reversed(path))
d_sea, p_sea = dijkstra("S07", "S10")
d_sf, p_sf = dijkstra("S07", "S11")
cities_sea = [stores.loc[s, "city"] for s in p_sea]
houses = pd.read_csv("data/houses.csv")
cols = ["sqft", "distance_to_center_km", "condition"]
X = houses[cols].to_numpy(dtype=float)
Z = (X - X.mean(axis=0)) / X.std(axis=0)
tree = spatial.KDTree(Z)
kd_dists, kd_idx = tree.query(Z[0], k=6)
kd_neighbors = kd_idx[1:].tolist()
brute_dists = np.linalg.norm(Z - Z[0], axis=1)
brute_neighbors = np.argsort(brute_dists)[1:6].tolist()
def quickselect(arr: list[int], k: int) -> int:
a = list(arr)
lo, hi = 0, len(a) - 1
while lo <= hi:
pivot = a[(lo + hi) // 2]
lt, i, gt = lo, lo, hi
while i <= gt:
if a[i] < pivot:
a[lt], a[i] = a[i], a[lt]
lt += 1
i += 1
elif a[i] > pivot:
a[i], a[gt] = a[gt], a[i]
gt -= 1
else:
i += 1
if k < lt:
hi = lt - 1
elif k > gt:
lo = gt + 1
else:
return a[k]
raise RuntimeError("index out of range")
prices = houses["price"].tolist()
n = len(prices)
med_qs = 0.5 * (quickselect(prices, n // 2 - 1) + quickselect(prices, n // 2))
max_diff = float(np.max(np.abs(kd_dists[1:] - brute_dists[brute_neighbors])))
print(f"S07->S10: {d_sea} km via {' -> '.join(p_sea)}")
print(f"cities: {' -> '.join(cities_sea)}")
print(f"S07->S11: {d_sf} km via {' -> '.join(p_sf)}")
print("H0001 5-NN IDs:", houses.loc[kd_neighbors, "house_id"].tolist())
print(f"max_dist_diff: {max_diff:.2e}")
print(f"quickselect median price: {med_qs:,.0f} (np.median: {np.median(prices):,.0f})")
assert p_sea[0] == "S07" and p_sea[-1] == "S10"
assert d_sea == 4865 and d_sf == 5175
assert kd_neighbors == brute_neighbors
assert max_diff < 1e-12
assert med_qs == float(np.median(prices))
Output
S07->S10: 4865 km via S07 -> S09 -> S03 -> S01 -> S02 -> S10
cities: New York -> Philadelphia -> Detroit -> Chicago -> Minneapolis -> Seattle
S07->S11: 5175 km via S07 -> S09 -> S03 -> S01 -> S12 -> S11
H0001 5-NN IDs: ['H0157', 'H1105', 'H1299', 'H0315', 'H1850']
max_dist_diff: 0.00e+00
quickselect median price: 376,000 (np.median: 376,000)

How it works:

  1. Dijkstra runs in O((V+E)log⁡V)O((V + E)\log V) time with non-negative highway distances, finding the northern corridor through Minneapolis (4,865 km) to Seattle and the central corridor through Denver (5,175 km) to San Francisco (Module 45).
  2. Standardizing features before building the KDTree prevents sqft (range ~5,000) from drowning out condition (range 1–5) in Euclidean distance (Modules 45 and 46). In 3D space the tree prunes most subtrees while returning the exact same 5 nearest houses as brute force.
  3. Three-way (Dutch National Flag) partitioning handles duplicate house prices (multiples of USD 500) without quadratic degradation and returns 376,000, matching np.median.

P6-05 · Interpret a result: SVD store-month compression and eigen-PCA loadings

Section titled “P6-05 · Interpret a result: SVD store-month compression and eigen-PCA loadings”
Core

Interpret a result: run two matrix factorizations from Module 46 and explain what their spectra tell you about the business data:

  1. Pivot data/sales.csv into a 12 × 24 revenue matrix MM (store_id × YYYY-MM, filling months before store S12 opened with 0.0). Compute np.linalg.svd(M, full_matrices=False) and report cumulative squared singular value energy ∑i≤kσi2/∑iσi2\sum_{i \le k} \sigma_i^2 / \sum_i \sigma_i^2 and relative Frobenius error ∥M−Mk∥F/∥M∥F\|M - M_k\|_F / \|M\|_F for ranks k=1,2,3,4k = 1, 2, 3, 4.
  2. Standardize ["sqft", "bedrooms", "bathrooms", "year_built", "garage_spaces", "condition", "distance_to_center_km"] on data/houses.csv, compute the correlation matrix C=Z⊤Z/nC = Z^\top Z / n, run np.linalg.eigh(C), verify positive definiteness (λmin⁡>0\lambda_{\min} > 0), verify eigenvalues equal σi2/n\sigma_i^2 / n and PC1 aligns with Vt[0] from np.linalg.svd(Z) up to sign, and list the top 3 absolute loadings of PC1.
  3. In 2–3 sentences, explain why rank 2 already captures over 96% of store-month revenue energy and what physical concept PC1 captures on houses.csv.
Expected output
rank 1: energy=0.9540, rel_frob_err=0.2145
rank 2: energy=0.9653, rel_frob_err=0.1863
rank 3: energy=0.9729, rel_frob_err=0.1646
rank 4: energy=0.9789, rel_frob_err=0.1454
corr min_eig=0.1035, pc1_var_share=0.4098
PC1 eig vs SVD |dot|=1.000000
PC1 top |loadings|: [('bedrooms', 0.545), ('bathrooms', 0.544), ('sqft', 0.539)]
Starter
sales = pd.read_csv("data/sales.csv")
houses = pd.read_csv("data/houses.csv")
feat_cols = [
"sqft",
"bedrooms",
"bathrooms",
"year_built",
"garage_spaces",
"condition",
"distance_to_center_km",
]
# TODO: pivot store x month revenue matrix, compute rank 1..4 SVD energy and Frobenius error
# TODO: eigen-decompose standardized house correlation matrix, check SVD equivalence
Hint 1

np.linalg.eigh returns eigenvalues in ascending order. Reverse them with order = np.argsort(eigvals)[::-1] before comparing eigvals against s_h**2 / len(Z).

Hint 2

The Eckart–Young theorem guarantees that ∥M−Mk∥F2=∑i>kσi2\|M - M_k\|_F^2 = \sum_{i > k} \sigma_i^2, so rel_frob_err2+energy=1\text{rel\_frob\_err}^2 + \text{energy} = 1.

Solution
sales = pd.read_csv("data/sales.csv")
sales["month"] = sales["order_date"].str.slice(0, 7)
mat = (
sales.pivot_table(
index="store_id",
columns="month",
values="revenue",
aggfunc="sum",
fill_value=0.0,
)
.sort_index()
.sort_index(axis=1)
)
M = mat.to_numpy()
U, s, Vt = np.linalg.svd(M, full_matrices=False)
total_energy = float(np.sum(s**2))
norm_M = float(np.linalg.norm(M, "fro"))
for k in (1, 2, 3, 4):
Mk = (U[:, :k] * s[:k]) @ Vt[:k, :]
rel_err = float(np.linalg.norm(M - Mk, "fro") / norm_M)
cum_var = float(np.sum(s[:k] ** 2) / total_energy)
print(f"rank {k}: energy={cum_var:.4f}, rel_frob_err={rel_err:.4f}")
houses = pd.read_csv("data/houses.csv")
feat_cols = [
"sqft",
"bedrooms",
"bathrooms",
"year_built",
"garage_spaces",
"condition",
"distance_to_center_km",
]
H = houses[feat_cols].to_numpy(dtype=float)
Z = (H - H.mean(axis=0)) / H.std(axis=0)
corr = (Z.T @ Z) / len(Z)
eigvals, eigvecs = np.linalg.eigh(corr)
order = np.argsort(eigvals)[::-1]
eigvals = eigvals[order]
eigvecs = eigvecs[:, order]
_, s_h, Vt_h = np.linalg.svd(Z, full_matrices=False)
pc1_align = float(abs(np.dot(eigvecs[:, 0], Vt_h[0])))
top_idx = np.argsort(np.abs(eigvecs[:, 0]))[::-1][:3]
top_loadings = [(feat_cols[i], round(float(abs(eigvecs[i, 0])), 3)) for i in top_idx]
pc1_share = eigvals[0] / eigvals.sum()
print(f"corr min_eig={eigvals.min():.4f}, pc1_var_share={pc1_share:.4f}")
print(f"PC1 eig vs SVD |dot|={pc1_align:.6f}")
print("PC1 top |loadings|:", top_loadings)
assert np.sum(s[:2] ** 2) / total_energy > 0.96
assert eigvals.min() > 0
assert abs(pc1_align - 1.0) < 1e-10
assert np.allclose(eigvals, (s_h**2) / len(Z))
Output
rank 1: energy=0.9540, rel_frob_err=0.2145
rank 2: energy=0.9653, rel_frob_err=0.1863
rank 3: energy=0.9729, rel_frob_err=0.1646
rank 4: energy=0.9789, rel_frob_err=0.1454
corr min_eig=0.1035, pc1_var_share=0.4098
PC1 eig vs SVD |dot|=1.000000
PC1 top |loadings|: [('bedrooms', 0.545), ('bathrooms', 0.544), ('sqft', 0.539)]

How it works:

  1. Rank 1 alone explains 95.4% of store-month revenue energy because every store shares almost the same company-wide monthly seasonality and growth curve, scaled by store floor area (size_sqm). Rank 2 adds the structural break from store S12 (Denver), which has zero sales before June 2023 and ramps up afterward, pushing cumulative energy to 96.5%.
  2. On houses.csv, all 7 correlation eigenvalues are strictly positive (min_eig = 0.1035), confirming the correlation matrix is symmetric positive definite (no exact multicollinearity). Because Z⊤Z/n=V(Σ2/n)V⊤Z^\top Z / n = V (\Sigma^2 / n) V^\top, the eigenvectors of the correlation matrix equal the right singular vectors of ZZ up to sign (|dot| = 1.000000).
  3. PC1 explains 41.0% of total standardized feature variance with nearly equal loadings on bedrooms (0.545), bathrooms (0.544) and sqft (0.539): it is a single composite “house size” axis.

P6-06 · Write the code: Hessian Newton solver vs. L-BFGS and Adam on churn logistic regression

Section titled “P6-06 · Write the code: Hessian Newton solver vs. L-BFGS and Adam on churn logistic regression”
Core

Write the code: fit L2-regularized logistic regression (λ=1.0\lambda = 1.0, intercept unpenalized) on data/customers.csv using standardized features ["tenure_months", "monthly_charges", "support_tickets", "logins_last_30d"] to predict churned, and compare three optimizers from Module 47:

  1. Implement the exact average binary cross-entropy loss + L2 penalty, analytical gradient g(w)g(w), and analytical Hessian H(w)=1nX⊤diag⁡(p(1−p))X+λnDH(w) = \frac{1}{n} X^\top \operatorname{diag}(p(1 - p)) X + \frac{\lambda}{n} D.
  2. Run 8 steps of Newton’s method (w←w−H(w)−1g(w)w \leftarrow w - H(w)^{-1} g(w) solved with np.linalg.solve), confirm strict convexity at the optimum (min_eig(H) > 0), and verify ∥g(w)∥2<10−10\|g(w)\|_2 < 10^{-10}.
  3. Compare against scipy.optimize.minimize(..., method="L-BFGS-B", jac=True) and 200 steps of Adam (lr=0.1, b1=0.9, b2=0.999, eps=1e-8), asserting all three reach the same global minimum.
Expected output
Newton (8 steps): loss=0.406365, ||grad||=2.20e-17, min_eig(H)=0.0359
L-BFGS-B (9 iters): loss=0.406365
Adam (200 steps): loss=0.406365
max |w_newton - w_lbfgs|: 9.73e-06
Starter
df = pd.read_csv("data/customers.csv")
cols = ["tenure_months", "monthly_charges", "support_tickets", "logins_last_30d"]
X_raw = df[cols].to_numpy(dtype=float)
X_std = (X_raw - X_raw.mean(axis=0)) / X_raw.std(axis=0)
X = np.column_stack([np.ones(len(df)), X_std])
y = df["churned"].to_numpy(dtype=float)
lam = 1.0
# TODO: define loss_and_grad(w) and hessian(w)
# TODO: run 8 Newton steps, L-BFGS-B, and 200 Adam steps from zeros, then compare
Hint 1

Use np.logaddexp(0.0, z) - y * z for overflow-safe logistic loss and special.expit(z) for probabilities pp. Form X⊤diag⁡(p(1−p))XX^\top \operatorname{diag}(p(1-p)) X without allocating an n×nn \times n diagonal matrix via (X.T * (p * (1 - p))) @ X.

Hint 2

In Adam, remember bias correction at step t = 1..200: m_hat = m / (1 - b1**t) and v_hat = v / (1 - b2**t) before updating w -= lr * m_hat / (np.sqrt(v_hat) + eps).

Solution
df = pd.read_csv("data/customers.csv")
cols = ["tenure_months", "monthly_charges", "support_tickets", "logins_last_30d"]
X_raw = df[cols].to_numpy(dtype=float)
X_std = (X_raw - X_raw.mean(axis=0)) / X_raw.std(axis=0)
X = np.column_stack([np.ones(len(df)), X_std])
y = df["churned"].to_numpy(dtype=float)
n, d = X.shape
lam = 1.0
reg_mask = np.array([0.0] + [1.0] * (d - 1))
def loss_and_grad(w: np.ndarray) -> tuple[float, np.ndarray]:
z = X @ w
reg = 0.5 * (lam / n) * float(np.sum(reg_mask * w**2))
loss = float(np.mean(np.logaddexp(0.0, z) - y * z)) + reg
p = special.expit(z)
grad = (X.T @ (p - y)) / n + (lam / n) * reg_mask * w
return loss, grad
def hessian(w: np.ndarray) -> np.ndarray:
p = special.expit(X @ w)
weights = p * (1.0 - p)
return (X.T * weights) @ X / n + np.diag((lam / n) * reg_mask)
w_newt = np.zeros(d)
for _ in range(8):
_, g_n = loss_and_grad(w_newt)
H = hessian(w_newt)
w_newt = w_newt - np.linalg.solve(H, g_n)
loss_n, g_n = loss_and_grad(w_newt)
min_eig_H = float(np.linalg.eigvalsh(hessian(w_newt)).min())
res = optimize.minimize(loss_and_grad, np.zeros(d), method="L-BFGS-B", jac=True)
loss_lbfgs, _ = loss_and_grad(res.x)
w_adam = np.zeros(d)
m_v = np.zeros(d)
v_v = np.zeros(d)
lr, b1, b2, eps = 0.1, 0.9, 0.999, 1e-8
for t in range(1, 201):
_, g_a = loss_and_grad(w_adam)
m_v = b1 * m_v + (1.0 - b1) * g_a
v_v = b2 * v_v + (1.0 - b2) * (g_a**2)
m_hat = m_v / (1.0 - b1**t)
v_hat = v_v / (1.0 - b2**t)
w_adam = w_adam - lr * m_hat / (np.sqrt(v_hat) + eps)
loss_adam, _ = loss_and_grad(w_adam)
print(
f"Newton (8 steps): loss={loss_n:.6f}, ||grad||={np.linalg.norm(g_n):.2e}, "
f"min_eig(H)={min_eig_H:.4f}"
)
print(f"L-BFGS-B ({res.nit} iters): loss={loss_lbfgs:.6f}")
print(f"Adam (200 steps): loss={loss_adam:.6f}")
print(f"max |w_newton - w_lbfgs|: {np.max(np.abs(w_newt - res.x)):.2e}")
assert min_eig_H > 0
assert np.linalg.norm(g_n) < 1e-10
assert abs(loss_n - loss_lbfgs) < 1e-8
assert abs(loss_adam - loss_n) < 1e-5
Output
Newton (8 steps): loss=0.406365, ||grad||=2.20e-17, min_eig(H)=0.0359
L-BFGS-B (9 iters): loss=0.406365
Adam (200 steps): loss=0.406365
max |w_newton - w_lbfgs|: 9.73e-06

How it works:

  1. Because p(1−p)>0p(1 - p) > 0 everywhere and λ>0\lambda > 0, the Hessian is strictly positive definite (min_eig(H) = 0.0359), proving the objective is strictly convex with a unique global minimum (Modules 46 and 47).
  2. Newton’s method uses exact second-order curvature and achieves quadratic convergence, driving the gradient norm to 2.20e-17 in 8 iterations.
  3. L-BFGS-B approximates the inverse Hessian from gradient history in 9 iterations without ever forming HH, while first-order Adam reaches the same optimal loss (0.406365) in 200 adaptive steps.

P6-07 · Write the code: numerical vs. Monte Carlo integration and Beta–Binomial Bayesian A/B test

Section titled “P6-07 · Write the code: numerical vs. Monte Carlo integration and Beta–Binomial Bayesian A/B test”
Core

Write the code: analyze data/ab_test.csv using Bayesian conjugate updating (Module 48) and continuous expectation integrals (Module 47):

  1. Place a uniform Beta⁡(1,1)\operatorname{Beta}(1, 1) prior on the conversion rates θC\theta_C (control) and θT\theta_T (treatment). Draw 50,000 posterior samples (rng = np.random.default_rng(42)) to compute P(θT>θC)P(\theta_T > \theta_C), the expected loss E[max⁡(θC−θT,0)]\mathbb{E}[\max(\theta_C - \theta_T, 0)] of shipping treatment, and the 95% credible interval for the lift θT−θC\theta_T - \theta_C.
  2. Fit a log-normal distribution (stats.lognorm.fit(buyers, floc=0)) to positive buyer revenues (revenue > 0). Compute both P(20≤R≤80)P(20 \le R \le 80) and the capped expected order value E[min⁡(R,100)]\mathbb{E}[\min(R, 100)] using scipy.integrate.quad and 100,000 Monte Carlo draws from the fitted distribution. Verify ∫2080f(x) dx=F(80)−F(20)\int_{20}^{80} f(x)\,dx = F(80) - F(20) and close agreement between quadrature and Monte Carlo.
Expected output
P(treatment > control) = 0.9937, expected loss = 0.000013
95% lift CI: [0.0034, 0.0277]
P(20<=R<=80): quad=0.7066, cdf=0.7066, mc=0.7060
E[min(R,100)]: quad=40.71, mc=40.67
Starter
ab = pd.read_csv("data/ab_test.csv")
rng = np.random.default_rng(42)
# TODO: Beta(1, 1) posterior sampling for control vs treatment conversion
# TODO: fit lognorm(floc=0) to positive revenues, compute P(20<=R<=80) and E[min(R, 100)]
# via scipy.integrate.quad and 100,000 Monte Carlo samples
Hint 1

With a Beta⁡(1,1)\operatorname{Beta}(1, 1) prior, observing kk conversions out of nn users gives posterior Beta⁡(1+k,1+n−k)\operatorname{Beta}(1 + k, 1 + n - k). Sample post_c first and post_t second from rng to match the exact output.

Hint 2

For the capped expectation integral, pass lambda x: min(x, 100.0) * dist.pdf(x) to integrate.quad(..., 0.0, 1000.0) and pass random_state=rng to dist.rvs(size=100_000, random_state=rng).

Solution
ab = pd.read_csv("data/ab_test.csv")
rng = np.random.default_rng(42)
ctrl = ab.loc[ab["group"] == "control", "converted"]
trt = ab.loc[ab["group"] == "treatment", "converted"]
post_c = rng.beta(1 + ctrl.sum(), 1 + len(ctrl) - ctrl.sum(), size=50_000)
post_t = rng.beta(1 + trt.sum(), 1 + len(trt) - trt.sum(), size=50_000)
prob_t_better = float(np.mean(post_t > post_c))
exp_loss_ship_t = float(np.mean(np.maximum(post_c - post_t, 0.0)))
lift_ci = np.quantile(post_t - post_c, [0.025, 0.975])
buyers = ab.loc[ab["revenue"] > 0, "revenue"].to_numpy()
shape, loc, scale = stats.lognorm.fit(buyers, floc=0)
dist = stats.lognorm(s=shape, loc=loc, scale=scale)
prob_quad, _ = integrate.quad(dist.pdf, 20.0, 80.0)
prob_cdf = float(dist.cdf(80.0) - dist.cdf(20.0))
ev_cap_quad, _ = integrate.quad(
lambda x: min(x, 100.0) * dist.pdf(x), 0.0, 1000.0
)
mc_draws = dist.rvs(size=100_000, random_state=rng)
prob_mc = float(np.mean((mc_draws >= 20.0) & (mc_draws <= 80.0)))
ev_cap_mc = float(np.mean(np.minimum(mc_draws, 100.0)))
print(
f"P(treatment > control) = {prob_t_better:.4f}, "
f"expected loss = {exp_loss_ship_t:.6f}"
)
print(f"95% lift CI: [{lift_ci[0]:.4f}, {lift_ci[1]:.4f}]")
print(f"P(20<=R<=80): quad={prob_quad:.4f}, cdf={prob_cdf:.4f}, mc={prob_mc:.4f}")
print(f"E[min(R,100)]: quad={ev_cap_quad:.2f}, mc={ev_cap_mc:.2f}")
assert prob_t_better > 0.99
assert abs(prob_quad - prob_cdf) < 1e-8
assert abs(prob_quad - prob_mc) < 0.005
assert abs(ev_cap_quad - ev_cap_mc) < 0.3
Output
P(treatment > control) = 0.9937, expected loss = 0.000013
95% lift CI: [0.0034, 0.0277]
P(20<=R<=80): quad=0.7066, cdf=0.7066, mc=0.7060
E[min(R,100)]: quad=40.71, mc=40.67

How it works:

  1. Conjugate Beta–Binomial updating gives a direct probability statement: there is a 99.37% posterior probability that treatment beats control, with an expected conversion-rate regret of just 0.000013 (0.0013 percentage points) if we ship treatment (Module 48).
  2. By the fundamental theorem of calculus, numerical quadrature quad(dist.pdf, 20, 80) matches cdf(80) - cdf(20) to 1e-8 (0.7066), and 100,000 Monte Carlo draws agree within O(1/N)≈0.001O(1/\sqrt{N}) \approx 0.001 (Module 47).
  3. Evaluating E[min⁡(R,100)]\mathbb{E}[\min(R, 100)] by both quadrature (USD 40.71) and Monte Carlo (USD 40.67) shows how expectation integrals handle kinked business payoffs (like loyalty caps or rebate limits) cleanly.

P6-08 · Fix the bug: SRM audit, peeking inflation, and CUPED variance reduction

Section titled “P6-08 · Fix the bug: SRM audit, peeking inflation, and CUPED variance reduction”
Core

Fix the bug: an experimentation diagnostics script from Module 49 has three serious methodological bugs:

  1. It skips the Sample Ratio Mismatch (SRM) chi-square test on data/ab_test.csv (50/50 expected split) and on a broken traffic split ([5200, 4800]).
  2. In a 1,000-trial null A/A simulation peeking every 200 users per arm up to 2,000 (10 looks), it only checks z_vals[:, -1] > 1.96 instead of tracking whether any look crossed 1.96 (np.any(z_vals > 1.96, axis=1)), hiding the peeking false-positive inflation.
  3. Its CUPED adjustment uses y_cuped = y + theta * x_pre (wrong sign and uncentered!), which inflates variance instead of shrinking it, and it never checks whether time_on_page_s in data/ab_test.csv is balanced between arms before using it as a covariate.

Fix all three bugs: run both SRM tests, compare fixed-horizon vs. 10-look peeking false-positive rates, fix CUPED to YCUPED=Y−θ(Xpre−Xˉpre)Y_{\mathrm{CUPED}} = Y - \theta (X_{\mathrm{pre}} - \bar{X}_{\mathrm{pre}}) showing variance drops below 50%, and prove via a Welch t-test that time_on_page_s in data/ab_test.csv is affected by treatment and therefore invalid as a CUPED covariate.

Expected output
SRM ab_test.csv: p=0.9681 | broken 5200/4800: p=6.33e-05
Null FPR: fixed_horizon=0.039, peeking_10_looks=0.183
CUPED: raw_ate=1.84, cuped_ate=2.07, var_kept=0.409
time_on_page_s balance p=2.55e-17 (post-treatment -> invalid for CUPED)
Starter
ab = pd.read_csv("data/ab_test.csv")
rng = np.random.default_rng(42)
# BUG 1: no SRM chi-square test on ab_test.csv or broken [5200, 4800] split
# BUG 2: peeking simulation checks only the final look
n_sims, n_max = 1000, 2000
looks = np.arange(200, n_max + 1, 200)
x_c = rng.binomial(1, 0.10, size=(n_sims, n_max))
x_t = rng.binomial(1, 0.10, size=(n_sims, n_max))
cum_c = np.cumsum(x_c, axis=1)[:, looks - 1]
cum_t = np.cumsum(x_t, axis=1)[:, looks - 1]
p_c, p_t = cum_c / looks, cum_t / looks
p_pool = 0.5 * (p_c + p_t)
se = np.sqrt(2.0 * p_pool * (1.0 - p_pool) / looks)
z_vals = np.abs(p_t - p_c) / np.where(se > 0, se, 1.0)
fpr_final = float(np.mean(z_vals[:, -1] > 1.96))
# BUG 3: wrong sign and uncentered CUPED adjustment
n_arm = 2000
treat = np.array([0] * n_arm + [1] * n_arm)
x_pre = rng.normal(50.0, 15.0, size=2 * n_arm)
y = 10.0 + 0.8 * x_pre + 1.5 * treat + rng.normal(0.0, 10.0, size=2 * n_arm)
theta = float(np.cov(y, x_pre, ddof=1)[0, 1] / np.var(x_pre, ddof=1))
y_cuped_buggy = y + theta * x_pre
# TODO: add SRM checks, compute peeking_10_looks, fix y_cuped, test time_on_page_s balance
Hint 1

stats.chisquare(observed, f_exp=[5000, 5000]) runs the 1-df goodness-of-fit test for a 50/50 randomization ratio. In ab_test.csv, ab["group"].value_counts().sort_index() gives [5002, 4998].

Hint 2

Subtracting theta * (x_pre - x_pre.mean()) keeps the expectation E[YCUPED]=E[Y]\mathbb{E}[Y_{\mathrm{CUPED}}] = \mathbb{E}[Y] unchanged while reducing variance by a factor of 1−ρ2(Y,Xpre)1 - \rho^2(Y, X_{\mathrm{pre}}). A valid CUPED covariate must be measured before randomization (independent of treatment assignment).

Solution
ab = pd.read_csv("data/ab_test.csv")
counts = ab["group"].value_counts().sort_index().to_numpy()
srm_real = stats.chisquare(counts, f_exp=[len(ab) / 2, len(ab) / 2])
srm_bad = stats.chisquare([5200, 4800], f_exp=[5000, 5000])
rng = np.random.default_rng(42)
n_sims, n_max = 1000, 2000
looks = np.arange(200, n_max + 1, 200)
x_c = rng.binomial(1, 0.10, size=(n_sims, n_max))
x_t = rng.binomial(1, 0.10, size=(n_sims, n_max))
cum_c = np.cumsum(x_c, axis=1)[:, looks - 1]
cum_t = np.cumsum(x_t, axis=1)[:, looks - 1]
p_c, p_t = cum_c / looks, cum_t / looks
p_pool = 0.5 * (p_c + p_t)
se = np.sqrt(2.0 * p_pool * (1.0 - p_pool) / looks)
z_vals = np.abs(p_t - p_c) / np.where(se > 0, se, 1.0)
fpr_final = float(np.mean(z_vals[:, -1] > 1.96))
fpr_peek = float(np.mean(np.any(z_vals > 1.96, axis=1)))
n_arm = 2000
treat = np.array([0] * n_arm + [1] * n_arm)
x_pre = rng.normal(50.0, 15.0, size=2 * n_arm)
y = 10.0 + 0.8 * x_pre + 1.5 * treat + rng.normal(0.0, 10.0, size=2 * n_arm)
theta = float(np.cov(y, x_pre, ddof=1)[0, 1] / np.var(x_pre, ddof=1))
y_cuped = y - theta * (x_pre - x_pre.mean())
raw_diff = float(y[treat == 1].mean() - y[treat == 0].mean())
cuped_diff = float(y_cuped[treat == 1].mean() - y_cuped[treat == 0].mean())
var_ratio = float(np.var(y_cuped, ddof=1) / np.var(y, ddof=1))
t_ctrl = ab.loc[ab["group"] == "control", "time_on_page_s"]
t_trt = ab.loc[ab["group"] == "treatment", "time_on_page_s"]
t_pval = float(stats.ttest_ind(t_trt, t_ctrl, equal_var=False).pvalue)
print(
f"SRM ab_test.csv: p={srm_real.pvalue:.4f} | "
f"broken 5200/4800: p={srm_bad.pvalue:.2e}"
)
print(f"Null FPR: fixed_horizon={fpr_final:.3f}, peeking_10_looks={fpr_peek:.3f}")
print(
f"CUPED: raw_ate={raw_diff:.2f}, cuped_ate={cuped_diff:.2f}, "
f"var_kept={var_ratio:.3f}"
)
print(f"time_on_page_s balance p={t_pval:.2e} (post-treatment -> invalid for CUPED)")
assert srm_real.pvalue > 0.05 and srm_bad.pvalue < 0.001
assert fpr_peek > 0.14 and abs(fpr_final - 0.05) < 0.02
assert var_ratio < 0.50
assert t_pval < 1e-6
Output
SRM ab_test.csv: p=0.9681 | broken 5200/4800: p=6.33e-05
Null FPR: fixed_horizon=0.039, peeking_10_looks=0.183
CUPED: raw_ate=1.84, cuped_ate=2.07, var_kept=0.409
time_on_page_s balance p=2.55e-17 (post-treatment -> invalid for CUPED)

How it works:

  1. ab_test.csv (5,002 vs. 4,998) passes the SRM check cleanly (p = 0.9681), whereas a 5200/4800 split triggers a severe SRM alarm (p = 6.33e-05), meaning traffic routing or logging is broken and treatment estimates cannot be trusted (Module 49).
  2. Peeking 10 times with an unadjusted z>1.96z > 1.96 threshold inflates the Type I error rate from ~4%–5% to 18.3% — nearly 4× the nominal α=0.05\alpha = 0.05.
  3. Subtracting θ(Xpre−Xˉpre)\theta (X_{\mathrm{pre}} - \bar{X}_{\mathrm{pre}}) cuts metric variance to 40.9% of the original (equivalent to running the test with 2.4× as many users!). Adjusting on time_on_page_s would introduce post-treatment bias because treatment itself shifts time_on_page_s (p = 2.55e-17).

P6-09 · Choose and justify: Poisson vs. Negative Binomial GLM and Kaplan–Meier retention

Section titled “P6-09 · Choose and justify: Poisson vs. Negative Binomial GLM and Kaplan–Meier retention”
Core

Choose and justify: solve two real count-and-retention modeling decisions from Modules 48 and 49:

  1. Aggregate daily unique order counts (order_id) by order_date from data/sales.csv, add a linear year trend t (0..730 / 365) and day-of-week dow, and fit both a Poisson GLM and a Negative Binomial GLM (estimating α\alpha via smf.negativebinomial first, then passing alpha=alpha_hat to sm.families.NegativeBinomial). Compare sample variance vs. mean, Pearson dispersion (pearson_chi2 / df_resid), and AIC, and justify which GLM family to choose.
  2. On data/customers.csv, write a pure-NumPy Kaplan–Meier survival estimator handling right-censored active customers (churned == 0, tenure_months as time) separately for "month-to-month", "one-year" and "two-year" contracts. Print survival probabilities S(12)S(12), S(24)S(24) and S(36)S(36) and justify why Kaplan–Meier beats taking the raw average tenure of churned customers.
Expected output
daily orders: mean=20.35, var=104.04
Poisson: dispersion=3.09, AIC=5399.0
NegBin (alpha=0.072): dispersion=1.19, AIC=4842.0
KM month-to-month : S(12)=0.742, S(24)=0.628, S(36)=0.557
KM one-year : S(12)=0.974, S(24)=0.935, S(36)=0.888
KM two-year : S(12)=0.995, S(24)=0.988, S(36)=0.972
Starter
sales = pd.read_csv("data/sales.csv")
cust = pd.read_csv("data/customers.csv")
# TODO: aggregate daily unique orders, fit Poisson and Negative Binomial GLMs, compare
# TODO: implement kaplan_meier(times, events, checkpoints) by contract type
Hint 1

In a Poisson model Var⁡(Y)=μ\operatorname{Var}(Y) = \mu, so Pearson dispersion χ2/df\chi^2 / \text{df} should stay near 1.0. Values above 2.0 indicate severe overdispersion, which makes Poisson standard errors too narrow and inflates false positives.

Hint 2

At each unique event time uu, let did_i be the number of churned customers at time uu and nin_i be the total number of customers whose recorded tenure equals uu (both churned and censored). Update surv *= 1 - d_i / at_risk first, then subtract n_i from at_risk.

Solution
sales = pd.read_csv("data/sales.csv")
daily = (
sales.groupby("order_date")["order_id"]
.nunique()
.reset_index(name="orders")
.sort_values("order_date")
.reset_index(drop=True)
)
daily["dt"] = pd.to_datetime(daily["order_date"])
daily["t"] = np.arange(len(daily), dtype=float) / 365.0
daily["dow"] = daily["dt"].dt.day_name()
pois = smf.glm("orders ~ t + C(dow)", data=daily, family=sm.families.Poisson()).fit()
dispersion = float(pois.pearson_chi2 / pois.df_resid)
nb_mle = smf.negativebinomial("orders ~ t + C(dow)", data=daily).fit(disp=False)
alpha_hat = float(nb_mle.params["alpha"])
nb_glm = smf.glm(
"orders ~ t + C(dow)",
data=daily,
family=sm.families.NegativeBinomial(alpha=alpha_hat),
).fit()
mean_ord, var_ord = daily["orders"].mean(), daily["orders"].var()
print(f"daily orders: mean={mean_ord:.2f}, var={var_ord:.2f}")
print(f"Poisson: dispersion={dispersion:.2f}, AIC={pois.aic:.1f}")
print(
f"NegBin (alpha={alpha_hat:.3f}): "
f"dispersion={nb_glm.pearson_chi2 / nb_glm.df_resid:.2f}, AIC={nb_glm.aic:.1f}"
)
cust = pd.read_csv("data/customers.csv")
def kaplan_meier(
times: np.ndarray, events: np.ndarray, checkpoints: list[int]
) -> dict[int, float]:
order = np.argsort(times)
t_s = times[order]
e_s = events[order]
surv = 1.0
at_risk = len(t_s)
curve_t = [0]
curve_s = [1.0]
for u in np.unique(t_s):
mask = t_s == u
d_i = int(e_s[mask].sum())
n_i = int(mask.sum())
if d_i > 0:
surv *= 1.0 - d_i / at_risk
curve_t.append(int(u))
curve_s.append(surv)
at_risk -= n_i
out = {}
for cp in checkpoints:
idx = max(i for i, ct in enumerate(curve_t) if ct <= cp)
out[cp] = round(curve_s[idx], 3)
return out
km_summary = {}
for contract in ["month-to-month", "one-year", "two-year"]:
sub = cust.loc[cust["contract"] == contract]
km_summary[contract] = kaplan_meier(
sub["tenure_months"].to_numpy(),
sub["churned"].to_numpy(),
[12, 24, 36],
)
s12 = km_summary[contract][12]
s24 = km_summary[contract][24]
s36 = km_summary[contract][36]
print(f"KM {contract:15s}: S(12)={s12:.3f}, S(24)={s24:.3f}, S(36)={s36:.3f}")
assert dispersion > 2.0
assert nb_glm.aic < pois.aic - 200
assert (
km_summary["two-year"][24]
> km_summary["one-year"][24]
> km_summary["month-to-month"][24]
)
Output
daily orders: mean=20.35, var=104.04
Poisson: dispersion=3.09, AIC=5399.0
NegBin (alpha=0.072): dispersion=1.19, AIC=4842.0
KM month-to-month : S(12)=0.742, S(24)=0.628, S(36)=0.557
KM one-year : S(12)=0.974, S(24)=0.935, S(36)=0.888
KM two-year : S(12)=0.995, S(24)=0.988, S(36)=0.972

How it works and justification:

  1. Choose Negative Binomial over Poisson: daily orders have variance 104.04 versus mean 20.35 (over 5× the Poisson assumption), driven by seasonal peaks and promo days. Even after controlling for trend and day of week, the Poisson GLM has dispersion 3.09, whereas Negative Binomial (α=0.072\alpha = 0.072) brings dispersion to 1.19 and lowers AIC by 557 points (4842.0 vs. 5399.0), producing honest standard errors (Modules 48 and 49).
  2. Choose Kaplan–Meier for retention: 80.7% of rows in customers.csv are active right-censored customers whose true eventual lifetime is still unknown. Dropping censored customers or averaging raw tenure treats active 3-month signups as if they churned at 3 months, severely underestimating retention. Kaplan–Meier keeps censored users in the risk set ntn_t up to their observed tenure and cleanly separates contract retention (S(24) = 0.628 for month-to-month vs. 0.988 for two-year).

P6-10 · Write the code: reverse-mode autograd engine verified against PyTorch

Section titled “P6-10 · Write the code: reverse-mode autograd engine verified against PyTorch”
Challenge

Write the code: combine DAG topological sort (Module 45) with reverse-mode automatic differentiation (Module 47):

  1. Build a scalar Value class supporting +, -, *, **, .exp(), .log(), .tanh() and .backward() (building a reverse topological ordering of the computation graph via DFS).
  2. Take an 8-row slice pd.read_csv("data/customers.csv").iloc[::600].head(8), standardize ["tenure_months", "monthly_charges"], and evaluate a 2-input → 2-hidden (tanh) → 1-logit binary cross-entropy network using the 9 initial weights [0.3, -0.2, 0.1, -0.4, 0.2, 0.5, 0.4, -0.3, 0.1].
  3. Call .backward() and assert that all 9 gradients match both central finite differences (ϵ=10−6\epsilon = 10^{-6}, error <10−7< 10^{-7}) and torch.autograd in float64 (error <10−12< 10^{-12}).
  4. Run 5 steps of gradient descent (lr = 0.5) using your Value engine and assert the loss strictly decreases on every step.
Expected output
initial loss: 0.748048, after 5 GD steps: 0.474933
max |grad - finite_diff|: 1.00e-10
torch float64 match (< 1e-12): True
Starter
import torch
df = pd.read_csv("data/customers.csv").iloc[::600].head(8)
X_raw = df[["tenure_months", "monthly_charges"]].to_numpy(dtype=float)
X = (X_raw - X_raw.mean(axis=0)) / X_raw.std(axis=0)
y = df["churned"].to_numpy(dtype=float)
init_w = [0.3, -0.2, 0.1, -0.4, 0.2, 0.5, 0.4, -0.3, 0.1]
# TODO: implement scalar Value with +, -, *, **, exp, log, tanh, backward (topo sort)
# TODO: compute BCE loss and gradients, verify against finite differences and PyTorch
# TODO: run 5 gradient-descent steps (lr=0.5) and assert loss decreases each step
Hint 1

Inside every _backward closure, accumulate gradients with += (never =), because a parameter or intermediate node used in multiple branches receives the sum of upstream gradients by the multivariable chain rule.

Hint 2

Express binary cross-entropy directly in terms of logit zz as (1.0 + z.exp()).log() - yi * z (in PyTorch: torch.log1p(torch.exp(z_t)) - ty * z_t), and make sure you run DFS post-order traversal and iterate reversed(topo) inside .backward().

Solution
import torch
class Value:
def __init__(self, data: float, children: tuple["Value", ...] = ()) -> None:
self.data = float(data)
self.grad = 0.0
self._backward = lambda: None
self._prev = set(children)
def __add__(self, other: "Value | float") -> "Value":
o = other if isinstance(other, Value) else Value(other)
out = Value(self.data + o.data, (self, o))
def _backward() -> None:
self.grad += out.grad
o.grad += out.grad
out._backward = _backward
return out
def __radd__(self, other: float) -> "Value":
return self + other
def __neg__(self) -> "Value":
return self * -1.0
def __sub__(self, other: "Value | float") -> "Value":
return self + (-other)
def __mul__(self, other: "Value | float") -> "Value":
o = other if isinstance(other, Value) else Value(other)
out = Value(self.data * o.data, (self, o))
def _backward() -> None:
self.grad += o.data * out.grad
o.grad += self.data * out.grad
out._backward = _backward
return out
def __rmul__(self, other: float) -> "Value":
return self * other
def __pow__(self, power: float) -> "Value":
out = Value(self.data**power, (self,))
def _backward() -> None:
self.grad += (power * (self.data ** (power - 1.0))) * out.grad
out._backward = _backward
return out
def exp(self) -> "Value":
e = math.exp(self.data)
out = Value(e, (self,))
def _backward() -> None:
self.grad += e * out.grad
out._backward = _backward
return out
def log(self) -> "Value":
out = Value(math.log(self.data), (self,))
def _backward() -> None:
self.grad += (1.0 / self.data) * out.grad
out._backward = _backward
return out
def tanh(self) -> "Value":
t = math.tanh(self.data)
out = Value(t, (self,))
def _backward() -> None:
self.grad += (1.0 - t * t) * out.grad
out._backward = _backward
return out
def backward(self) -> None:
topo: list[Value] = []
visited: set[Value] = set()
def build(v: Value) -> None:
if v not in visited:
visited.add(v)
for child in v._prev:
build(child)
topo.append(v)
build(self)
self.grad = 1.0
for node in reversed(topo):
node._backward()
df = pd.read_csv("data/customers.csv").iloc[::600].head(8)
X_raw = df[["tenure_months", "monthly_charges"]].to_numpy(dtype=float)
X = (X_raw - X_raw.mean(axis=0)) / X_raw.std(axis=0)
y = df["churned"].to_numpy(dtype=float)
init_w = [0.3, -0.2, 0.1, -0.4, 0.2, 0.5, 0.4, -0.3, 0.1]
def bce_loss(params: list[Value]) -> Value:
w11, w12, b1, w21, w22, b2, v1, v2, bo = params
total = Value(0.0)
for (x1, x2), yi in zip(X, y, strict=True):
h1 = (w11 * x1 + w12 * x2 + b1).tanh()
h2 = (w21 * x1 + w22 * x2 + b2).tanh()
z = v1 * h1 + v2 * h2 + bo
total = total + ((1.0 + z.exp()).log() - yi * z)
return total * (1.0 / len(y))
params = [Value(val) for val in init_w]
loss0 = bce_loss(params)
loss0.backward()
grads_auto = np.array([p.grad for p in params])
eps = 1e-6
grads_fd = np.zeros(len(init_w))
for i in range(len(init_w)):
p_plus = [Value(v + (eps if j == i else 0.0)) for j, v in enumerate(init_w)]
p_minus = [Value(v - (eps if j == i else 0.0)) for j, v in enumerate(init_w)]
grads_fd[i] = (bce_loss(p_plus).data - bce_loss(p_minus).data) / (2.0 * eps)
t_params = torch.tensor(init_w, dtype=torch.float64, requires_grad=True)
tx = torch.tensor(X, dtype=torch.float64)
ty = torch.tensor(y, dtype=torch.float64)
h1_t = torch.tanh(t_params[0] * tx[:, 0] + t_params[1] * tx[:, 1] + t_params[2])
h2_t = torch.tanh(t_params[3] * tx[:, 0] + t_params[4] * tx[:, 1] + t_params[5])
z_t = t_params[6] * h1_t + t_params[7] * h2_t + t_params[8]
loss_t = torch.mean(torch.log1p(torch.exp(z_t)) - ty * z_t)
loss_t.backward()
grads_torch = t_params.grad.numpy()
losses = [loss0.data]
cur = list(init_w)
for _ in range(5):
ps = [Value(v) for v in cur]
lv = bce_loss(ps)
lv.backward()
cur = [v - 0.5 * p.grad for v, p in zip(cur, ps, strict=True)]
losses.append(bce_loss([Value(v) for v in cur]).data)
err_fd = float(np.max(np.abs(grads_auto - grads_fd)))
err_torch = float(np.max(np.abs(grads_auto - grads_torch)))
print(f"initial loss: {loss0.data:.6f}, after 5 GD steps: {losses[-1]:.6f}")
print(f"max |grad - finite_diff|: {err_fd:.2e}")
print(f"torch float64 match (< 1e-12): {err_torch < 1e-12}")
assert err_fd < 1e-7
assert err_torch < 1e-12
assert all(losses[i + 1] < losses[i] for i in range(5))
Output
initial loss: 0.748048, after 5 GD steps: 0.474933
max |grad - finite_diff|: 1.00e-10
torch float64 match (< 1e-12): True

How it works:

  1. Every arithmetic and activation operation appends a node to a dynamic DAG with pointers to its inputs (_prev) and its local derivative rule (_backward).
  2. DFS post-order traversal yields a topological ordering where every parent appears after all its children; walking reversed(topo) guarantees each node’s full upstream gradient out.grad is accumulated before propagating backward (Modules 45 and 47).
  3. Agreement with torch.autograd to machine precision (< 1e-12) and central finite differences to 1.00e-10 confirms exact reverse-mode differentiation, and 5 gradient-descent steps drop BCE loss from 0.748048 to 0.474933.

P6-11 · Interpret a result: Metropolis–Hastings Bayesian posterior and sensor drift (KL/JSD & MI)

Section titled “P6-11 · Interpret a result: Metropolis–Hastings Bayesian posterior and sensor drift (KL/JSD & MI)”
Challenge

Interpret a result: apply Bayesian MCMC and information-theoretic drift diagnostics from Module 48 on data/customers.csv and data/sensors.csv:

  1. Take every 10th customer from data/customers.csv (cust.iloc[::10], 500 rows) and standardize support_tickets. Implement a random-walk Metropolis–Hastings sampler (4,000 steps, 1,000 burn-in, start [-1.5, 0.5], isotropic Normal proposal σ=0.12\sigma = 0.12, seed 42) for a 2-parameter Bayesian logistic regression (intercept + standardized support_tickets) with N(0,22)\mathcal{N}(0, 2^2) priors. Report the acceptance rate, posterior mean, 95% credible interval for the slope β1\beta_1, and compare with statsmodels Logit MLE.
  2. On data/sensors.csv, split readings into Week 1 (timestamp < "2024-05-08") vs. Week 2 (timestamp >= "2024-05-08"). Compute 20-bin histogram Jensen–Shannon divergence (base 2, with 1e-9 smoothing) between Week 1 and Week 2 for temperature_c and vibration_mm_s across sensors S1–S4.
  3. Compute mutual information (mutual_info_classif(..., random_state=42)) between (status != "ok") and ["temperature_c", "humidity_pct", "vibration_mm_s"] on non-null rows, then interpret what the JSD table and MI scores diagnose about the four sensors.
Expected output
MCMC accept=0.521, post_mean=[-1.511, 0.603]
MLE params=[-1.517, 0.606], b1 95% CrI=[0.391, 0.817]
sensor jsd_temp jsd_vib
S1 0.005 0.004
S2 0.008 0.004
S3 0.303 0.007
S4 0.008 0.219
MI with non-ok status: {'temperature_c': 0.0335, 'humidity_pct': 0.008, 'vibration_mm_s': 0.1965}
Starter
cust = pd.read_csv("data/customers.csv")
sample = cust.iloc[::10].copy()
sensors = pd.read_csv("data/sensors.csv")
# TODO: write log_posterior(theta), run 4000-step Metropolis-Hastings (burn=1000)
# TODO: compare posterior mean vs statsmodels Logit MLE
# TODO: compute Week 1 vs Week 2 JSD per sensor and mutual_info_classif with status != 'ok'
Hint 1

Compute log-likelihood in log space using np.sum(y * z - np.logaddexp(0.0, z)) to avoid underflow, and accept a proposal when math.log(rng.random()) < prop_lp - cur_lp.

Hint 2

Build shared bin edges across Week 1 and Week 2 (np.linspace(min(a.min(), b.min()), max(a.max(), b.max()), 21)) before calling np.histogram so both distributions live on the same support.

Solution
cust = pd.read_csv("data/customers.csv")
sample = cust.iloc[::10].copy()
x = sample["support_tickets"].to_numpy(dtype=float)
x_std = (x - x.mean()) / x.std()
y = sample["churned"].to_numpy(dtype=float)
def log_posterior(theta: np.ndarray) -> float:
b0, b1 = theta
z = b0 + b1 * x_std
ll = float(np.sum(y * z - np.logaddexp(0.0, z)))
lp = float(-0.5 * (b0**2 + b1**2) / 4.0)
return ll + lp
rng = np.random.default_rng(42)
n_steps, burn = 4000, 1000
chain = np.zeros((n_steps, 2))
cur = np.array([-1.5, 0.5])
cur_lp = log_posterior(cur)
accepted = 0
for i in range(n_steps):
prop = cur + rng.normal(0.0, 0.12, size=2)
prop_lp = log_posterior(prop)
if math.log(rng.random()) < prop_lp - cur_lp:
cur, cur_lp = prop, prop_lp
accepted += 1
chain[i] = cur
post = chain[burn:]
acc_rate = accepted / n_steps
post_mean = post.mean(axis=0)
b1_ci = np.quantile(post[:, 1], [0.025, 0.975])
mle = sm.Logit(y, sm.add_constant(x_std)).fit(disp=False)
print(f"MCMC accept={acc_rate:.3f}, post_mean=[{post_mean[0]:.3f}, {post_mean[1]:.3f}]")
print(
f"MLE params=[{mle.params[0]:.3f}, {mle.params[1]:.3f}], "
f"b1 95% CrI=[{b1_ci[0]:.3f}, {b1_ci[1]:.3f}]"
)
sensors = pd.read_csv("data/sensors.csv")
sensors["week"] = np.where(sensors["timestamp"] < "2024-05-08", 1, 2)
def jsd_hist(a: np.ndarray, b: np.ndarray, bins: int = 20) -> float:
lo = min(float(a.min()), float(b.min()))
hi = max(float(a.max()), float(b.max()))
edges = np.linspace(lo, hi, bins + 1)
p, _ = np.histogram(a, bins=edges)
q, _ = np.histogram(b, bins=edges)
p = (p + 1e-9) / (p.sum() + bins * 1e-9)
q = (q + 1e-9) / (q.sum() + bins * 1e-9)
m = 0.5 * (p + q)
return float(0.5 * np.sum(p * np.log2(p / m)) + 0.5 * np.sum(q * np.log2(q / m)))
drift_rows = []
for sid in ["S1", "S2", "S3", "S4"]:
sub = sensors.loc[sensors["sensor_id"] == sid]
w1 = sub.loc[sub["week"] == 1]
w2 = sub.loc[sub["week"] == 2]
jsd_t = jsd_hist(
w1["temperature_c"].dropna().to_numpy(),
w2["temperature_c"].dropna().to_numpy(),
)
jsd_v = jsd_hist(
w1["vibration_mm_s"].dropna().to_numpy(),
w2["vibration_mm_s"].dropna().to_numpy(),
)
drift_rows.append({"sensor": sid, "jsd_temp": jsd_t, "jsd_vib": jsd_v})
drift_df = pd.DataFrame(drift_rows)
print(drift_df.round(3).to_string(index=False))
clean_s = sensors.dropna(subset=["temperature_c", "humidity_pct", "vibration_mm_s"])
feats = ["temperature_c", "humidity_pct", "vibration_mm_s"]
mi = mutual_info_classif(
clean_s[feats].to_numpy(),
(clean_s["status"] != "ok").to_numpy(dtype=int),
random_state=42,
)
mi_map = {f: round(float(v), 4) for f, v in zip(feats, mi, strict=True)}
print("MI with non-ok status:", mi_map)
assert 0.20 <= acc_rate <= 0.60
assert abs(post_mean[1] - mle.params[1]) < 0.08
assert drift_df.loc[drift_df["jsd_temp"].idxmax(), "sensor"] == "S3"
assert drift_df.loc[drift_df["jsd_vib"].idxmax(), "sensor"] == "S4"
assert mi_map["vibration_mm_s"] > mi_map["temperature_c"] > mi_map["humidity_pct"]
Output
MCMC accept=0.521, post_mean=[-1.511, 0.603]
MLE params=[-1.517, 0.606], b1 95% CrI=[0.391, 0.817]
sensor jsd_temp jsd_vib
S1 0.005 0.004
S2 0.008 0.004
S3 0.303 0.007
S4 0.008 0.219
MI with non-ok status: {'temperature_c': 0.0335, 'humidity_pct': 0.008, 'vibration_mm_s': 0.1965}

How it works and interpretation:

  1. With 500 observations and a weakly informative N(0,22)\mathcal{N}(0, 2^2) prior, the Metropolis–Hastings posterior mean ([-1.511, 0.603]) closely tracks the frequentist MLE ([-1.517, 0.606]), with mild shrinkage toward zero and a healthy 52.1% acceptance rate. The entire 95% credible interval for support_tickets ([0.391, 0.817]) lies well above zero, confirming a strong positive log-odds link with churn.
  2. Week-over-week Jensen–Shannon divergence isolates two distinct hardware faults automatically: S1 and S2 stay near zero (<= 0.008 bits), while S3 jumps to 0.303 bits on temperature_c alone (calibration drift) and S4 jumps to 0.219 bits on vibration_mm_s alone (mechanical wear).
  3. Mutual information shows vibration_mm_s (0.1965 nats) carries nearly 6× as much information about warn/fail status as temperature_c (0.0335) and 24× as much as humidity_pct (0.0080), pointing maintenance priority directly at S4 vibration before S3 calibration drift.

P6-12 · Choose and justify: observational causal inference (IPW, DiD) and Thompson sampling

Section titled “P6-12 · Choose and justify: observational causal inference (IPW, DiD) and Thompson sampling”
Challenge

Choose and justify: combine three causal and sequential decision tools from Modules 48 and 49 to answer three business questions and justify each method:

  1. Observational churn effect (Propensity Score IPW): On data/customers.csv, estimate the causal effect of has_autopay on churned. Fit a logistic propensity score model on standardized one-hot features ["age", "region", "plan", "contract", "payment_method", "tenure_months", "monthly_charges", "support_tickets", "logins_last_30d"], clip propensities to [0.05, 0.95], compute the Hájek (normalized) IPW ATE, and compare both the ATE and the maximum covariate standardized mean difference (SMD) before vs. after weighting.
  2. Campaign lift without randomization (Difference-in-Differences): On data/web_traffic.csv (interpolating the 5 missing visits values), estimate the causal daily-visits lift of the April 2024 marketing campaign (2024-04-08..2024-04-14 vs. pre-week 2024-04-01..2024-04-07) using the same calendar weeks in 2023 (2023-04-10..2023-04-16 vs. 2023-04-03..2023-04-09, when no campaign ran) as the control trend.
  3. Adaptive optimization (Thompson sampling vs. fixed A/B): Simulate 5,000 visitors (rng = np.random.default_rng(42)) across 3 checkout variants with true conversion rates [0.08, 0.11, 0.15], comparing Beta(1, 1) Thompson sampling against a fixed equal-split 1/3 A/B test on cumulative expected regret and traffic share sent to the best arm.
Expected output
IPW autopay: naive_ate=-0.0493, ipw_ate=-0.0278
covariate max SMD: before=1.136, after=0.020
DiD Apr-2024 lift: +5,236.0 visits/day (2024 +5,407.9 vs 2023 +171.9)
Bandit regret: TS=45.7 vs fixed_AB=183.4 | best-arm share=79.7%
Starter
cust = pd.read_csv("data/customers.csv")
wt = pd.read_csv("data/web_traffic.csv")
wt["visits"] = wt["visits"].interpolate()
# TODO: Part A — Propensity Score IPW for has_autopay -> churned + max SMD before/after
# TODO: Part B — 2x2 Difference-in-Differences for Apr-2024 campaign vs Apr-2023
# TODO: Part C — Beta-Binomial Thompson sampling vs fixed 1/3 A/B over 5,000 visitors
Hint 1

The Hájek IPW estimator normalizes weights within each arm: np.sum(w1 * y) / np.sum(w1) - np.sum(w0 * y) / np.sum(w0), where w1 = t / ps and w0 = (1 - t) / (1 - ps). It has lower variance than unnormalized Horvitz–Thompson IPW.

Hint 2

In Thompson sampling, maintain alpha = np.ones(3) and beta = np.ones(3). For each visitor, draw rng.beta(alpha, beta), pick arm = int(np.argmax(...)), simulate reward = int(rng.random() < true_rates[arm]), update alpha[arm] or beta[arm], and accumulate best_rate - true_rates[arm] into regret.

Solution
cust = pd.read_csv("data/customers.csv")
t = cust["has_autopay"].to_numpy(dtype=float)
y = cust["churned"].to_numpy(dtype=float)
naive_ate = float(y[t == 1].mean() - y[t == 0].mean())
X_df = pd.get_dummies(
cust[
[
"age",
"region",
"plan",
"contract",
"payment_method",
"tenure_months",
"monthly_charges",
"support_tickets",
"logins_last_30d",
]
],
drop_first=True,
dtype=float,
)
X_std = (X_df - X_df.mean()) / X_df.std()
prop_model = LogisticRegression(max_iter=1000).fit(X_std, t)
ps = np.clip(prop_model.predict_proba(X_std)[:, 1], 0.05, 0.95)
w1 = t / ps
w0 = (1.0 - t) / (1.0 - ps)
ipw_ate = float(np.sum(w1 * y) / np.sum(w1) - np.sum(w0 * y) / np.sum(w0))
def max_smd(
X_mat: np.ndarray, tr: np.ndarray, weights: np.ndarray | None = None
) -> float:
smds = []
for j in range(X_mat.shape[1]):
col = X_mat[:, j]
m1, m0 = tr == 1, tr == 0
if weights is None:
mu1, mu0 = col[m1].mean(), col[m0].mean()
v1, v0 = col[m1].var(), col[m0].var()
else:
w_1, w_0 = weights[m1], weights[m0]
mu1 = np.average(col[m1], weights=w_1)
mu0 = np.average(col[m0], weights=w_0)
v1 = np.average((col[m1] - mu1) ** 2, weights=w_1)
v0 = np.average((col[m0] - mu0) ** 2, weights=w_0)
smds.append(abs(mu1 - mu0) / math.sqrt(0.5 * (v1 + v0) + 1e-12))
return float(max(smds))
X_np = X_std.to_numpy()
smd_before = max_smd(X_np, t)
smd_after = max_smd(X_np, t, weights=w1 + w0)
wt = pd.read_csv("data/web_traffic.csv")
wt["visits"] = wt["visits"].interpolate()
def mean_visits(start: str, end: str) -> float:
mask = (wt["date"] >= start) & (wt["date"] <= end)
return float(wt.loc[mask, "visits"].mean())
pre_24 = mean_visits("2024-04-01", "2024-04-07")
post_24 = mean_visits("2024-04-08", "2024-04-14")
pre_23 = mean_visits("2023-04-03", "2023-04-09")
post_23 = mean_visits("2023-04-10", "2023-04-16")
did_lift = (post_24 - pre_24) - (post_23 - pre_23)
rng = np.random.default_rng(42)
true_rates = np.array([0.08, 0.11, 0.15])
best_rate = float(true_rates.max())
n_visitors = 5000
alpha = np.ones(3)
beta = np.ones(3)
ts_pulls = np.zeros(3, dtype=int)
ts_regret = 0.0
for _ in range(n_visitors):
arm = int(np.argmax(rng.beta(alpha, beta)))
reward = int(rng.random() < true_rates[arm])
alpha[arm] += reward
beta[arm] += 1 - reward
ts_pulls[arm] += 1
ts_regret += best_rate - true_rates[arm]
ab_arms = np.arange(n_visitors) % 3
ab_regret = float(np.sum(best_rate - true_rates[ab_arms]))
print(f"IPW autopay: naive_ate={naive_ate:+.4f}, ipw_ate={ipw_ate:+.4f}")
print(f"covariate max SMD: before={smd_before:.3f}, after={smd_after:.3f}")
print(
f"DiD Apr-2024 lift: +{did_lift:,.1f} visits/day "
f"(2024 {post_24 - pre_24:+,.1f} vs 2023 {post_23 - pre_23:+,.1f})"
)
print(
f"Bandit regret: TS={ts_regret:.1f} vs fixed_AB={ab_regret:.1f} | "
f"best-arm share={ts_pulls[2] / n_visitors:.1%}"
)
assert smd_after < 0.10 and smd_after < smd_before / 10
assert ipw_ate < 0 and abs(ipw_ate) < abs(naive_ate)
assert did_lift > 3000
assert ts_regret < ab_regret * 0.4
assert ts_pulls[2] / n_visitors > 0.75
Output
IPW autopay: naive_ate=-0.0493, ipw_ate=-0.0278
covariate max SMD: before=1.136, after=0.020
DiD Apr-2024 lift: +5,236.0 visits/day (2024 +5,407.9 vs 2023 +171.9)
Bandit regret: TS=45.7 vs fixed_AB=183.4 | best-arm share=79.7%

How it works and justification:

  1. IPW for observational autopay: a naive difference credits autopay with a -4.93 percentage-point drop in churn, but covariate balance reveals severe confounding (max SMD = 1.136, largely because electronic_check users rarely have autopay and churn heavily). IPW reduces maximum SMD to 0.020 (well under the 0.10 balance rule of thumb) and shrinks the estimated causal effect to -2.78 percentage points — still helpful, but nearly half of the naive gap was confounding.
  2. DiD for site-wide campaigns: when a campaign hits the whole site at once, a simple before/after comparison can confound the campaign with calendar seasonality. Differencing against the same April weeks of 2023 (+171.9 baseline drift) isolates +5,236.0 incremental visits per day under the parallel-trends assumption.
  3. Thompson sampling vs. fixed A/B: use a fixed-horizon A/B test when you need clean, unbiased inference on secondary metrics and long-term effects; choose Thompson sampling when maximizing conversions during a short promo window matters most. Here Thompson sampling cuts expected regret by 75% (45.7 vs. 183.4 lost conversions) by routing 79.7% of visitors to the winning arm.

Rate yourself on each Part 6 skill area based on what you completed without opening the solution.

Skill area Not yet Getting there Ready
45. Algorithms & data structures II: graphs, DP, tries, spatial & streaming You reach for brute-force loops or full sorts on every problem. You implement Tries, Dijkstra or DP, but miss edge cases, tie-breaking or space trade-offs. You pick the right structure by complexity (Trie, 2D DP, Dijkstra, Kahn topo sort, Quickselect, KD-tree, Bloom filter), state its invariants and verify exactness against baselines.
46. Linear algebra in depth: rank, QR, eigen & SVD You invert X⊤XX^\top X blindly without checking rank or conditioning. You call svd or eigh, but cannot connect singular values to variance, projection or PCA loadings. You diagnose collinearity via rank and condition numbers, solve OLS via QR with orthogonal residuals, check positive definiteness and compress matrices with truncated SVD.
47. Calculus & optimization: Taylor, Hessians, integration, optimizers & autograd You treat gradients and optimizers as black boxes. You write gradients, but struggle with Hessians, numerical integrals or backprop through branching DAGs. You bound approximations with Taylor terms, verify convexity via Hessian eigenvalues, compare Newton, L-BFGS and Adam, compute expectations via quad and Monte Carlo and build reverse-mode autograd verified against finite differences and PyTorch.
48. Probability, Bayesian & info theory: conjugate priors, MAP, MCMC & drift You report only point estimates and raw means. You fit conjugate priors or KL divergence, but forget MAP–Ridge equivalence, MCMC diagnostics or symmetry of JSD. You run Beta–Binomial A/B tests with expected loss, prove Gaussian MAP equals Ridge, diagnose Metropolis–Hastings acceptance and credible intervals and flag distribution drift with JSD and mutual information.
49. Causal inference, GLMs & experiments: SRM, CUPED, IPW, DiD, GLMs & survival You interpret observational correlations or peeked p-values as causal proof. You run IPW or GLMs, but skip covariate balance checks, overdispersion diagnostics or right-censoring. You guard experiments with SRM checks, prevent peeking inflation, apply valid pre-treatment CUPED, balance covariates with IPW (SMD < 0.10), estimate DiD and Thompson-sampling regret, choose Negative Binomial over overdispersed Poisson and compute Kaplan–Meier retention curves.

You are ready to tackle the Part 7 capstones when you can:

  • Solve at least 9 of the 12 exercises without opening the solution, including at least one Challenge exercise.
  • Predict all 6 lines of P6-01 and explain the theorem or invariant behind each one.
  • Spot rank deficiency with matrix_rank and cond, solve OLS via reduced QR, and prove Gaussian-prior MAP equals Ridge.
  • Implement a Trie, 2D DP Levenshtein distance, Dijkstra shortest path, Quickselect and a deterministic Bloom filter without copy-pasting.
  • Explain why low-rank SVD approximates structured business matrices and how correlation eigenvectors map to SVD loadings.
  • Verify strict convexity from Hessian eigenvalues and match Newton’s method, L-BFGS-B and Adam to the same minimum.
  • Compute continuous expectations with both scipy.integrate.quad and Monte Carlo sampling, and run a Bayesian Beta–Binomial decision analysis.
  • Catch SRM, peeking false-positive inflation and invalid post-treatment CUPED covariates before shipping an experiment.
  • Choose Negative Binomial over Poisson when dispersion exceeds 1, and handle right-censored customers with Kaplan–Meier survival curves.
  • Build a reverse-mode autograd Value graph from scratch and match torch.autograd to machine precision.
  • Run a Metropolis–Hastings sampler and diagnose data drift with Jensen–Shannon divergence and mutual information.
  • Reduce observational confounding with Propensity Score IPW, verify covariate balance (SMD), estimate DiD lift and compare Thompson sampling against fixed A/B splits.

Rated “Not yet” in any row? Revisit that module’s lesson and cheat sheet, work through two of its core exercises, and retry the matching checkpoint task. Once every row reads “Getting there” or “Ready”, put everything together in Part 7: Capstones.