48. Probability, Bayesian statistics and information theory — Exercises
These exercises practice every topic from the Probability, Bayesian statistics and information theory lesson. They reuse the course datasets: customers.csv, houses.csv, ab_test.csv, sales.csv, reviews.csv and sensors.csv (see the data dictionary).
How to work:
- Read the task and expected output (or acceptance criteria for predict-the-output exercises).
- Place the setup block below at the top of your script, then copy the starter code under it and fill in the to-do comments.
- Run the script and compare your output line by line.
- Open one hint at a time when stuck; read the full solution only after a genuine attempt.
Every exercise runs after this setup block:
import numpy as npimport pandas as pdfrom scipy import statsfrom scipy.spatial.distance import jensenshannonfrom sklearn.feature_selection import mutual_info_regressionfrom sklearn.linear_model import LogisticRegression, Ridgefrom sklearn.metrics import log_loss
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)
customers = pd.read_csv("data/customers.csv")houses = pd.read_csv("data/houses.csv")ab = pd.read_csv("data/ab_test.csv")sales = pd.read_csv("data/sales.csv")reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)sensors = pd.read_csv("data/sensors.csv")Warm-up
Section titled “Warm-up”M48-W01 · Law of total probability on churn by plan
Section titled “M48-W01 · Law of total probability on churn by plan”Using customers, compute the share of each plan () and the conditional churn rate (). Combine them via the law of total probability and verify the sum equals the overall churn rate.
basic share=0.406 churn=0.1736premium share=0.198 churn=0.2960standard share=0.396 churn=0.1604total_prob=0.1926 | direct=0.1926# TODO: group customers by "plan" to get count and churn mean# TODO: compute share = count / len(customers) and weighted sum# TODO: print each plan line and the total_prob vs direct comparisonHint 1
customers.groupby("plan")["churned"].agg(["count", "mean"]) gives both counts and conditional churn rates in sorted plan order (basic, premium, standard).
Hint 2
Multiply by_plan["share"] by by_plan["mean"] and sum the result.
Solution
by_plan = customers.groupby("plan")["churned"].agg(["count", "mean"])by_plan["share"] = by_plan["count"] / len(customers)total_p = float((by_plan["share"] * by_plan["mean"]).sum())direct_p = float(customers["churned"].mean())
for plan, row in by_plan.iterrows(): print(f"{plan:<8} share={row['share']:.3f} churn={row['mean']:.4f}")print(f"total_prob={total_p:.4f} | direct={direct_p:.4f}")
assert np.isclose(total_p, direct_p, atol=1e-12)basic share=0.406 churn=0.1736premium share=0.198 churn=0.2960standard share=0.396 churn=0.1604total_prob=0.1926 | direct=0.1926How it works:
- The three plan tiers partition all 5,000 customers without overlap, so their shares sum to 1.0.
- Weighting each conditional churn rate by its plan share recovers the exact global churn rate
0.1926.
M48-W02 · Predict the output: Bayes’ theorem with a rare fault
Section titled “M48-W02 · Predict the output: Bayes’ theorem with a rare fault”Predict the output: a sensor alert detects 92% of real machine faults (sens = 0.92) and falsely triggers on 4% of healthy machines (fpr = 0.04). Only 1.5% of machines have a fault (prior = 0.015). Before running the code, calculate and by hand to four decimals.
Acceptance criteria:
- Write down your predicted two lines (both rounded to 4 decimals), then run the code.
- Explain in one sentence why is far below 0.92.
prior = 0.015sens = 0.92fpr = 0.04p_flag = sens * prior + fpr * (1 - prior)post = sens * prior / p_flag# TODO: predict both printed values before runningprint(f"P(flag)={p_flag:.4f}")print(f"P(fault | flag)={post:.4f}")Hint 1
Compute the true-positive rate 0.92 * 0.015 = 0.0138 and the false-positive rate 0.04 * 0.985 = 0.0394.
Solution
prior = 0.015sens = 0.92fpr = 0.04p_flag = sens * prior + fpr * (1 - prior)post = sens * prior / p_flagprint(f"P(flag)={p_flag:.4f}")print(f"P(fault | flag)={post:.4f}")
assert round(p_flag, 4) == 0.0532assert round(post, 4) == 0.2594P(flag)=0.0532P(fault | flag)=0.2594How it works:
- Only 1.38% of all machines are true-positive flags, while 3.94% are false alarms from the huge healthy population.
- Dividing
0.0138 / 0.0532gives0.2594: nearly three-quarters of alerts are false alarms because the base rate is low.
M48-W03 · Marginal and conditional tables for channel and category
Section titled “M48-W03 · Marginal and conditional tables for channel and category”Using sales, build both the joint distribution P(channel, category) and the conditional distribution P(category | channel). Print P(online, Electronics), P(Electronics | online) and P(Electronics | store) rounded to four decimals.
P(online, Electronics): 0.0836P(Electronics | online): 0.1991P(Electronics | store): 0.1919# TODO: build joint and conditional crosstabs on sales["channel"] and sales["category"]# TODO: print the three requested probabilities rounded to 4 decimalsHint 1
Pass normalize="all" to pd.crosstab for the joint table and normalize="index" for .
Solution
joint = pd.crosstab(sales["channel"], sales["category"], normalize="all")cond = pd.crosstab(sales["channel"], sales["category"], normalize="index")
p_joint = float(joint.loc["online", "Electronics"])p_on = float(cond.loc["online", "Electronics"])p_st = float(cond.loc["store", "Electronics"])
print("P(online, Electronics):", round(p_joint, 4))print("P(Electronics | online):", round(p_on, 4))print("P(Electronics | store): ", round(p_st, 4))
p_online = float((sales["channel"] == "online").mean())assert np.isclose(p_joint, p_on * p_online, atol=1e-12)P(online, Electronics): 0.0836P(Electronics | online): 0.1991P(Electronics | store): 0.1919How it works:
normalize="all"divides every cell by the total row count (20,228), giving joint probabilities that sum to 1.normalize="index"divides each row by its row sum, yielding conditional probabilities givenchannel.- Electronics accounts for roughly 19%–20% of order lines in both channels.
M48-W04 · Fix the bug: Exponential and Gamma scale parameters
Section titled “M48-W04 · Fix the bug: Exponential and Gamma scale parameters”Fix the bug: API requests arrive at rate per second (mean wait time 5 seconds). The starter code passes lam directly as scale to stats.expon and stats.gamma(a=3, ...) instead of 1 / lam. Fix both distributions so they have the right mean, survival probability and variance.
Expon mean=5.00, P(X>10)=0.1353Gamma mean=15.00, var=75.00lam = 0.2# BUG: SciPy expects scale = 1 / rate, not rateexp_d = stats.expon(scale=lam)gam_d = stats.gamma(a=3, scale=lam)# TODO: fix both calls above and print the statsHint 1
For rate , the Exponential mean is and the Gamma() mean is .
Solution
lam = 0.2exp_d = stats.expon(scale=1 / lam)gam_d = stats.gamma(a=3, scale=1 / lam)
print(f"Expon mean={exp_d.mean():.2f}, P(X>10)={exp_d.sf(10):.4f}")print(f"Gamma mean={gam_d.mean():.2f}, var={gam_d.var():.2f}")
assert np.isclose(exp_d.mean(), 5.0)assert np.isclose(gam_d.mean(), 15.0)assert np.isclose(gam_d.var(), 75.0)Expon mean=5.00, P(X>10)=0.1353Gamma mean=15.00, var=75.00How it works:
- SciPy parameterizes both
exponandgammabyscale = 1 / rate. - Waiting for 3 Poisson arrivals at rate 0.2/s is the sum of 3 independent Exponential(0.2) waits, giving mean s and variance .
M48-W05 · Beta–Binomial conjugate update
Section titled “M48-W05 · Beta–Binomial conjugate update”You place a prior on an email campaign’s click rate, then observe 34 clicks out of 250 recipients. Compute the exact Beta posterior, its mean, and its 95% equal-tailed credible interval.
Beta(36, 234) mean=0.133395% CrI=[0.0955, 0.1763]a0, b0 = 2, 18clicks, sent = 34, 250# TODO: build the conjugate Beta posterior, print its parameters, mean and 95% CrIHint 1
Posterior parameters are a0 + clicks and b0 + (sent - clicks).
Hint 2
Use post.ppf([0.025, 0.975]) for the 95% equal-tailed credible interval.
Solution
a0, b0 = 2, 18clicks, sent = 34, 250post = stats.beta(a0 + clicks, b0 + sent - clicks)lo, hi = post.ppf([0.025, 0.975])
print(f"Beta({int(post.args[0])}, {int(post.args[1])}) mean={post.mean():.4f}")print(f"95% CrI=[{lo:.4f}, {hi:.4f}]")
assert np.isclose(post.mean(), 36 / 270)assert lo < post.mean() < hiBeta(36, 234) mean=0.133395% CrI=[0.0955, 0.1763]How it works:
- Adding successes to and failures to gives .
- The posterior mean
0.1333sits slightly below the raw rate34 / 250 = 0.1360because the prior pulled lightly toward0.10.
M48-W06 · Gamma–Poisson sequential update on support tickets
Section titled “M48-W06 · Gamma–Poisson sequential update on support tickets”An hourly ticket stream follows with conjugate prior (rate parameterization). You observe six hourly counts: [14, 19, 12, 21, 16, 18]. Update the prior both in one batch and sequentially one hour at a time, confirm both give the identical Gamma posterior, and print its mean and 95% credible interval.
Batch: Gamma(104.0, 6.25) | Seq: Gamma(104.0, 6.25)Post mean=16.6400, 95% CrI=[13.596 19.987]counts = np.array([14, 19, 12, 21, 16, 18])a0, b0 = 4.0, 0.25# TODO: compute batch posterior (a0 + sum(counts), b0 + len(counts))# TODO: compute sequential posterior in a loop and verify equality# TODO: build stats.gamma(..., scale=1 / b_seq) and print mean and 95% CrIHint 1
Each new count adds to and to .
Solution
counts = np.array([14, 19, 12, 21, 16, 18])a0, b0 = 4.0, 0.25a_batch, b_batch = a0 + counts.sum(), b0 + len(counts)
a_seq, b_seq = a0, b0for c in counts: a_seq += c b_seq += 1
post_g = stats.gamma(a=a_seq, scale=1 / b_seq)cri = np.round(post_g.ppf([0.025, 0.975]), 3)print( f"Batch: Gamma({a_batch:.1f}, {b_batch:.2f})" f" | Seq: Gamma({a_seq:.1f}, {b_seq:.2f})")print(f"Post mean={post_g.mean():.4f}, 95% CrI={cri}")
assert a_batch == a_seq and b_batch == b_seqassert np.isclose(post_g.mean(), 104.0 / 6.25)Batch: Gamma(104.0, 6.25) | Seq: Gamma(104.0, 6.25)Post mean=16.6400, 95% CrI=[13.596 19.987]How it works:
- Bayesian updating is order-invariant: updating hour by hour yields the exact same as updating on all six hours at once.
- Remember to pass
scale=1 / b_seqtostats.gamma.
M48-W07 · Shannon entropy of customer regions and plans
Section titled “M48-W07 · Shannon entropy of customer regions and plans”Compute the Shannon entropy in bits (base=2) of customers["region"] and customers["plan"], along with each column’s maximum possible entropy and the ratio . Which column is closer to a uniform split?
region H=1.9938 bits (max 2.0000, ratio 0.997)plan H=1.5198 bits (max 1.5850, ratio 0.959)for col in ["region", "plan"]: # TODO: get normalized value counts, compute entropy in bits, max entropy and ratio ...Hint 1
customers[col].value_counts(normalize=True).to_numpy() returns the probability vector probs, and len(probs) is .
Solution
ratios = {}for col in ["region", "plan"]: probs = customers[col].value_counts(normalize=True).to_numpy() h_bits = float(stats.entropy(probs, base=2)) h_max = float(np.log2(len(probs))) ratios[col] = h_bits / h_max print(f"{col:<7} H={h_bits:.4f} bits (max {h_max:.4f}, ratio {ratios[col]:.3f})")
assert ratios["region"] > ratios["plan"]assert 0.99 < ratios["region"] <= 1.0region H=1.9938 bits (max 2.0000, ratio 0.997)plan H=1.5198 bits (max 1.5850, ratio 0.959)How it works:
- Four equal regions have maximum entropy bits;
regionachieves 99.7% of that ceiling. planhas fewerpremiumcustomers (about 20% vs 40%/40%), so its normalized entropy is lower (0.959).
M48-W08 · Predict the output: KL divergence asymmetry
Section titled “M48-W08 · Predict the output: KL divergence asymmetry”Predict the output: given and , predict whether KL(P||Q) equals KL(Q||P) and whether JS(P||Q) equals JS(Q||P). Compute KL(P||Q) in nats by hand () before running the code.
Acceptance criteria:
- Write your numerical predictions for
KL(P||Q),KL(Q||P)and whetherJSis symmetric, then run the code. - Explain why
KL(Q||P)is larger thanKL(P||Q)here.
p = np.array([0.8, 0.2])q = np.array([0.5, 0.5])# TODO: predict all three printed lines before runningprint(f"KL(P||Q)={stats.entropy(p, q):.4f}")print(f"KL(Q||P)={stats.entropy(q, p):.4f}")print(f"JS(P||Q)={jensenshannon(p, q) ** 2:.4f} | JS(Q||P)={jensenshannon(q, p) ** 2:.4f}")Hint 1
In KL(Q||P), the weight 0.5 multiplies , heavily penalizing ‘s low probability 0.2.
Solution
p = np.array([0.8, 0.2])q = np.array([0.5, 0.5])kl_pq = float(stats.entropy(p, q))kl_qp = float(stats.entropy(q, p))js_pq = float(jensenshannon(p, q) ** 2)js_qp = float(jensenshannon(q, p) ** 2)
print(f"KL(P||Q)={kl_pq:.4f}")print(f"KL(Q||P)={kl_qp:.4f}")print(f"JS(P||Q)={js_pq:.4f} | JS(Q||P)={js_qp:.4f}")
assert not np.isclose(kl_pq, kl_qp)assert np.isclose(js_pq, js_qp)KL(P||Q)=0.1927KL(Q||P)=0.2231JS(P||Q)=0.0507 | JS(Q||P)=0.0507How it works:
- KL divergence weights by the first argument, so
KL(P||Q) = 0.1927differs fromKL(Q||P) = 0.2231. - Jensen–Shannon divergence averages both directions against the midpoint , guaranteeing exact symmetry (
0.0507).
M48-C01 · Covariance matrix and multivariate normal density
Section titled “M48-C01 · Covariance matrix and multivariate normal density”Drop missing values in houses[["sqft", "lot_sqft", "price"]], compute the sample mean vector, covariance matrix (ddof=1) and correlation matrix, and fit a stats.multivariate_normal. Print the valid row count, the correlation between sqft and price, and the log-density at the mean vs. at [2500, 9000, 600000].
n=2910 | corr(sqft, price)=0.7312logpdf(mean)=-30.091 | logpdf([2500,9000,600000])=-30.578# TODO: drop NaNs from houses[["sqft", "lot_sqft", "price"]]# TODO: compute mean vector, covariance matrix, correlation matrix and multivariate_normal# TODO: print the requested statisticsHint 1
Use np.cov(sub_h, rowvar=False, ddof=1) and np.corrcoef(sub_h, rowvar=False).
Hint 2
mvn = stats.multivariate_normal(mean=mu_h, cov=cov_h) exposes mvn.logpdf(...).
Solution
sub_h = houses[["sqft", "lot_sqft", "price"]].dropna().to_numpy(dtype=float)mu_h = sub_h.mean(axis=0)cov_h = np.cov(sub_h, rowvar=False, ddof=1)corr_h = np.corrcoef(sub_h, rowvar=False)mvn = stats.multivariate_normal(mean=mu_h, cov=cov_h)
lp_mean = float(mvn.logpdf(mu_h))lp_pt = float(mvn.logpdf([2500, 9000, 600000]))print(f"n={len(sub_h)} | corr(sqft, price)={corr_h[0, 2]:.4f}")print(f"logpdf(mean)={lp_mean:.3f} | logpdf([2500,9000,600000])={lp_pt:.3f}")
assert len(sub_h) == 2910assert lp_mean > lp_ptassert np.allclose(cov_h, cov_h.T)n=2910 | corr(sqft, price)=0.7312logpdf(mean)=-30.091 | logpdf([2500,9000,600000])=-30.578How it works:
lot_sqfthas 90 missing rows inhouses.csv, leaving2,910complete observations.- The multivariate normal density peaks at
mu_h, sologpdf(mean)is strictly greater thanlogpdfat any other point.
M48-C02 · Fit a Log-normal distribution to A/B buyer revenue
Section titled “M48-C02 · Fit a Log-normal distribution to A/B buyer revenue”Select all converted buyers (ab["converted"] == 1) and extract their positive revenue. Estimate the log-scale parameters and (ddof=1), construct stats.lognorm(s=sig_hat, scale=np.exp(mu_hat)), and compare the model’s mean and median against the empirical sample mean and median.
mu_log=3.5410, sigma_log=0.6430Sample mean=42.36, median=35.03LogNorm mean=42.42, median=34.50buyers = ab.loc[ab["converted"] == 1, "revenue"].to_numpy(dtype=float)# TODO: take np.log(buyers), compute mu_hat and sig_hat (ddof=1)# TODO: build stats.lognorm and print sample vs model mean and medianHint 1
In SciPy, stats.lognorm(s=sigma, scale=np.exp(mu)) has median and mean .
Solution
buyers = ab.loc[ab["converted"] == 1, "revenue"].to_numpy(dtype=float)log_rev = np.log(buyers)mu_hat = float(log_rev.mean())sig_hat = float(log_rev.std(ddof=1))ln_dist = stats.lognorm(s=sig_hat, scale=np.exp(mu_hat))
print(f"mu_log={mu_hat:.4f}, sigma_log={sig_hat:.4f}")print(f"Sample mean={buyers.mean():.2f}, median={np.median(buyers):.2f}")print(f"LogNorm mean={ln_dist.mean():.2f}, median={ln_dist.median():.2f}")
assert np.isclose(ln_dist.mean(), np.exp(mu_hat + 0.5 * sig_hat**2))assert abs(ln_dist.mean() - buyers.mean()) < 0.5mu_log=3.5410, sigma_log=0.6430Sample mean=42.36, median=35.03LogNorm mean=42.42, median=34.50How it works:
- Fitting a normal distribution on yields and .
- The fitted Log-normal closely reproduces both the right-skewed sample mean (
42.42vs42.36USD) and the sample median (34.50vs35.03USD).
M48-C03 · Multinomial probabilities for category basket mixes
Section titled “M48-C03 · Multinomial probabilities for category basket mixes”Estimate the 6 category probabilities in sales in the fixed order ["Clothing", "Electronics", "Sports", "Home", "Beauty", "Books"]. Using stats.multinomial(n=12, p=probs), compare the probability of a balanced 12-item sample [2, 2, 2, 2, 2, 2] with an Electronics-heavy sample [1, 6, 2, 1, 1, 1].
Top share: Clothing (0.1984)PMF balanced [2,2,2,2,2,2]: 0.003008PMF heavy-elec [1,6,2,1,1,1]: 0.000309cats = ["Clothing", "Electronics", "Sports", "Home", "Beauty", "Books"]# TODO: compute category probabilities in the order of cats# TODO: build stats.multinomial(n=12, p=probs) and evaluate both count vectorsHint 1
sales["category"].value_counts(normalize=True).reindex(cats).to_numpy() ensures the probability vector matches cats order.
Solution
cats = ["Clothing", "Electronics", "Sports", "Home", "Beauty", "Books"]probs = sales["category"].value_counts(normalize=True).reindex(cats).to_numpy()mn = stats.multinomial(n=12, p=probs)
p_bal = float(mn.pmf([2, 2, 2, 2, 2, 2]))p_elec = float(mn.pmf([1, 6, 2, 1, 1, 1]))
print(f"Top share: {cats[int(np.argmax(probs))]} ({probs.max():.4f})")print(f"PMF balanced [2,2,2,2,2,2]: {p_bal:.6f}")print(f"PMF heavy-elec [1,6,2,1,1,1]: {p_elec:.6f}")
assert np.isclose(probs.sum(), 1.0)assert p_bal > 9 * p_elecTop share: Clothing (0.1984)PMF balanced [2,2,2,2,2,2]: 0.003008PMF heavy-elec [1,6,2,1,1,1]: 0.000309How it works:
- Because all six categories have shares between 13% and 20%, a balanced draw
[2, 2, 2, 2, 2, 2]has far more multinomial arrangements and is nearly 10× more likely than[1, 6, 2, 1, 1, 1].
M48-C04 · Overdispersion check on customer support tickets
Section titled “M48-C04 · Overdispersion check on customer support tickets”Choose a method and justify it: inspect customers["support_tickets"]. Compute its mean, variance (ddof=1) and variance-to-mean ratio. Fit both a Poisson model and a method-of-moments Negative Binomial model, then compare their predicted probability against the observed share. Is overdispersion mild or severe here?
mean=1.239, var=1.372, ratio=1.11P(tickets>=5) obs=0.0106 | Pois=0.0088 | NB=0.0131tix = customers["support_tickets"].to_numpy()# TODO: compute mean, variance (ddof=1), ratio, and MoM Negative Binomial r and p# TODO: compare observed, Poisson and NB P(tickets >= 5)Hint 1
Method of moments gives r_hat = m_t**2 / (v_t - m_t) and p_hat = r_hat / (r_hat + m_t).
Hint 2
For discrete , use sf(4).
Solution
tix = customers["support_tickets"].to_numpy()m_t = float(tix.mean())v_t = float(tix.var(ddof=1))r_hat = m_t**2 / (v_t - m_t)p_hat = r_hat / (r_hat + m_t)
obs_ge5 = float((tix >= 5).mean())pois_ge5 = float(stats.poisson.sf(4, mu=m_t))nb_ge5 = float(stats.nbinom.sf(4, n=r_hat, p=p_hat))
print(f"mean={m_t:.3f}, var={v_t:.3f}, ratio={v_t / m_t:.2f}")print(f"P(tickets>=5) obs={obs_ge5:.4f} | Pois={pois_ge5:.4f} | NB={nb_ge5:.4f}")
assert v_t > m_tassert pois_ge5 < obs_ge5 < nb_ge5mean=1.239, var=1.372, ratio=1.11P(tickets>=5) obs=0.0106 | Pois=0.0088 | NB=0.0131How it works:
- Unlike daily orders (variance/mean = 5.11), support tickets have only mild overdispersion (ratio
1.11). - Both Poisson (
0.0088) and Negative Binomial (0.0131) bracket the observed tail (0.0106) closely; Poisson is already a reasonable baseline, with Negative Binomial useful if you want conservative tail coverage.
M48-C05 · Bayesian A/B test by device segment
Section titled “M48-C05 · Bayesian A/B test by device segment”Run a conjugate Beta–Binomial A/B test (prior ) separately for each device (desktop, mobile, tablet, in alphabetical order) in ab. Using one shared rng = np.random.default_rng(42) and 30,000 draws per arm (control first, then treatment), print and the mean relative lift for each device.
desktop P(T>C)=0.9824 | mean rel lift=+21.0%mobile P(T>C)=0.9684 | mean rel lift=+17.4%tablet P(T>C)=0.2924 | mean rel lift=-7.6%rng = np.random.default_rng(42)for dev in ["desktop", "mobile", "tablet"]: # TODO: filter ab to dev, build Beta(1+k, 1+n-k) posteriors for control and treatment # TODO: draw 30_000 samples (control then treatment) and print P(T>C) and mean rel lift ...Hint 1
Compute g = sub_d.groupby("group")["converted"].agg(["sum", "count"]) inside the loop to extract kc, nc and kt, nt.
Solution
rng = np.random.default_rng(42)probs_win = {}for dev in ["desktop", "mobile", "tablet"]: sub_d = ab[ab["device"] == dev] g = sub_d.groupby("group")["converted"].agg(["sum", "count"]) kc, nc = int(g.loc["control", "sum"]), int(g.loc["control", "count"]) kt, nt = int(g.loc["treatment", "sum"]), int(g.loc["treatment", "count"]) dc = stats.beta(1 + kc, 1 + nc - kc).rvs(30_000, random_state=rng) dt = stats.beta(1 + kt, 1 + nt - kt).rvs(30_000, random_state=rng) p_win = float((dt > dc).mean()) lift = float(((dt - dc) / dc).mean()) probs_win[dev] = p_win print(f"{dev:<8} P(T>C)={p_win:.4f} | mean rel lift={lift:+.1%}")
assert probs_win["desktop"] > 0.95 and probs_win["mobile"] > 0.95assert probs_win["tablet"] < 0.5desktop P(T>C)=0.9824 | mean rel lift=+21.0%mobile P(T>C)=0.9684 | mean rel lift=+17.4%tablet P(T>C)=0.2924 | mean rel lift=-7.6%How it works:
- Both
desktop(98.2%) andmobile(96.8%) show strong evidence of a positive lift. tablethas fewer than 1,000 users total, so its posterior is wide and inconclusive (P(T>C) = 0.2924)—not strong enough to conclude the page hurts tablet users without collecting more data.
M48-C06 · Posterior predictive check vs. plug-in forecast
Section titled “M48-C06 · Posterior predictive check vs. plug-in forecast”After observing 24 signups out of 200 trial visitors (prior ), forecast signups in the next 1,000 visitors using 25,000 draws from rng = np.random.default_rng(42). Compare the 90% posterior predictive interval (5th to 95th percentile) against the plug-in MLE interval that fixes .
Posterior predictive 90%: [84.0, 168.0] (width 84.0)Plug-in MLE 90%: [103.0, 137.0] (width 34.0)rng = np.random.default_rng(42)# TODO: draw 25_000 posterior p values from Beta(25, 177), then simulate Binomial(1000, p_draws)# TODO: simulate 25_000 plug-in draws from Binomial(1000, 24/200)# TODO: print both 90% intervals and their widthsHint 1
rng.binomial(1000, p_draws) accepts an array of probabilities and returns one simulated count per draw.
Solution
rng = np.random.default_rng(42)post_b = stats.beta(1 + 24, 1 + 200 - 24)p_draws = post_b.rvs(25_000, random_state=rng)y_pp = rng.binomial(1000, p_draws)y_pi = rng.binomial(1000, 24 / 200, size=25_000)
pp_lo, pp_hi = np.quantile(y_pp, [0.05, 0.95])pi_lo, pi_hi = np.quantile(y_pi, [0.05, 0.95])print( f"Posterior predictive 90%: [{pp_lo:.1f}, {pp_hi:.1f}]" f" (width {pp_hi - pp_lo:.1f})")print( f"Plug-in MLE 90%: [{pi_lo:.1f}, {pi_hi:.1f}]" f" (width {pi_hi - pi_lo:.1f})")
assert (pp_hi - pp_lo) > 2 * (pi_hi - pi_lo)Posterior predictive 90%: [84.0, 168.0] (width 84.0)Plug-in MLE 90%: [103.0, 137.0] (width 34.0)How it works:
- Because was estimated from only 200 trials, parameter uncertainty dominates the forecast for 1,000 future visitors.
- The posterior predictive interval is more than twice as wide (
84vs34), preventing overconfident capacity or revenue planning.
M48-C07 · Normal–Normal conjugate updating on sensor temperature
Section titled “M48-C07 · Normal–Normal conjugate updating on sensor temperature”Take the first 30 non-null temperature readings of sensor S1 in sensors. Assuming known reading noise °C and a Normal prior , compute the exact Normal–Normal posterior mean and standard deviation using precision weighting:
n=30, x_bar=19.727Posterior N(19.787, 0.271^2)s1_temp = sensors.loc[sensors["sensor_id"] == "S1", "temperature_c"].dropna().iloc[:30]sigma, mu0, tau0 = 1.5, 23.0, 2.0# TODO: compute posterior precision, tau_post and mu_postHint 1
prec_post = 1 / tau0**2 + n_obs / sigma**2, then tau_post = np.sqrt(1 / prec_post).
Solution
s1_temp = sensors.loc[sensors["sensor_id"] == "S1", "temperature_c"].dropna().iloc[:30]x_bar = float(s1_temp.mean())n_obs = len(s1_temp)sigma, mu0, tau0 = 1.5, 23.0, 2.0
prec_post = 1 / tau0**2 + n_obs / sigma**2tau_post = float(np.sqrt(1 / prec_post))mu_post = float((mu0 / tau0**2 + n_obs * x_bar / sigma**2) / prec_post)
print(f"n={n_obs}, x_bar={x_bar:.3f}")print(f"Posterior N({mu_post:.3f}, {tau_post:.3f}^2)")
assert x_bar < mu_post < mu0assert tau_post < sigma / np.sqrt(n_obs)n=30, x_bar=19.727Posterior N(19.787, 0.271^2)How it works:
- Precision (inverse variance) adds cleanly: the prior precision
0.25combines with the data precision30 / 2.25 = 13.33. - Because data precision is over 50× larger than prior precision, the posterior mean
19.787sits right next to the sample mean19.727with a tiny posterior standard deviation of0.271°C.
M48-C08 · Empirical Bayes shrinkage of store-level online share
Section titled “M48-C08 · Empirical Bayes shrinkage of store-level online share”Group sales by store_id and compute each store’s online order-line share (channel == "online"). Fit an empirical Beta prior across the 12 stores via method of moments, compute each store’s shrunk online share, and print: (1) the fitted prior, (2) the highest raw-share store before and after shrinkage, and (3) what a hypothetical brand-new store with 3 online lines out of 4 shrinks to.
Prior Beta(281.2, 385.6) | mean=0.4217Highest raw: S02 raw=0.4575 -> eb=0.4468New store (3/4): raw=0.7500 -> eb=0.4237# TODO: aggregate sales by store_id: total count n and online count# TODO: estimate empirical Beta(a0, b0) from mean and variance (ddof=1) of raw shares# TODO: compute shrunk eb = (online + a0) / (n + a0 + b0) and print the three linesHint 1
strength = m_s * (1 - m_s) / v_s - 1, then a0 = m_s * strength and b0 = (1 - m_s) * strength.
Solution
st = ( sales.groupby("store_id")["channel"] .agg(n="count", online=lambda s: int((s == "online").sum())) .reset_index())st["raw"] = st["online"] / st["n"]m_s = float(st["raw"].mean())v_s = float(st["raw"].var(ddof=1))k_s = m_s * (1 - m_s) / v_s - 1a0_s, b0_s = m_s * k_s, (1 - m_s) * k_sst["eb"] = (st["online"] + a0_s) / (st["n"] + a0_s + b0_s)
top_st = st.sort_values("raw", ascending=False).iloc[0]new_eb = (3 + a0_s) / (4 + a0_s + b0_s)print(f"Prior Beta({a0_s:.1f}, {b0_s:.1f}) | mean={m_s:.4f}")print( f"Highest raw: {top_st['store_id']} raw={top_st['raw']:.4f}" f" -> eb={top_st['eb']:.4f}")print(f"New store (3/4): raw=0.7500 -> eb={new_eb:.4f}")
assert top_st["eb"] < top_st["raw"]assert abs(new_eb - m_s) < 0.01Prior Beta(281.2, 385.6) | mean=0.4217Highest raw: S02 raw=0.4575 -> eb=0.4468New store (3/4): raw=0.7500 -> eb=0.4237How it works:
- All 12 stores cluster tightly around 42% online share, so the empirical prior is very concentrated (
a0 + b0 ≈ 667pseudo-orders). - A new store with just 3/4 online orders (
0.7500) is pulled almost completely back to the chain norm (0.4237) until real volume accumulates.
M48-C09 · Verify Gaussian MAP matches Ridge across three prior scales
Section titled “M48-C09 · Verify Gaussian MAP matches Ridge across three prior scales”Standardize ["sqft", "bedrooms", "bathrooms", "condition"] from houses and center y = np.log(houses["price"]). Fix noise variance . For each prior standard deviation , solve closed-form Gaussian MAP with and assert it matches Ridge(alpha=lam, fit_intercept=True).coef_ to 1e-12. Notice how the weight norm grows as the prior loosens.
tau=0.02 lam= 125.0 | ||w||=0.3233 | diff=7.22e-16tau=0.1 lam= 5.0 | ||w||=0.3650 | diff=3.23e-16tau=0.5 lam= 0.2 | ||w||=0.3671 | diff=8.33e-16cols = ["sqft", "bedrooms", "bathrooms", "condition"]# TODO: standardize X, compute y_l = log(price) and centered y_c# TODO: loop over tau in [0.02, 0.1, 0.5], solve Gaussian MAP and compare with RidgeHint 1
Solve (X_s.T @ X_s + lam * np.eye(X_s.shape[1])) w = X_s.T @ y_c with np.linalg.solve.
Solution
cols = ["sqft", "bedrooms", "bathrooms", "condition"]X_r = houses[cols].to_numpy(dtype=float)X_s = (X_r - X_r.mean(axis=0)) / X_r.std(axis=0)y_l = np.log(houses["price"].to_numpy(dtype=float))y_c = y_l - y_l.mean()sigma2 = 0.05
norms = []for tau in [0.02, 0.1, 0.5]: lam = sigma2 / tau**2 w_map = np.linalg.solve(X_s.T @ X_s + lam * np.eye(X_s.shape[1]), X_s.T @ y_c) w_ridge = Ridge(alpha=lam, fit_intercept=True).fit(X_s, y_l).coef_ diff = float(np.max(np.abs(w_map - w_ridge))) norm_w = float(np.linalg.norm(w_map)) norms.append(norm_w) print(f"tau={tau:<4} lam={lam:>6.1f} | ||w||={norm_w:.4f} | diff={diff:.2e}") assert diff < 1e-12
assert norms[0] < norms[1] < norms[2]tau=0.02 lam= 125.0 | ||w||=0.3233 | diff=7.22e-16tau=0.1 lam= 5.0 | ||w||=0.3650 | diff=3.23e-16tau=0.5 lam= 0.2 | ||w||=0.3671 | diff=8.33e-16How it works:
- Tightening the Gaussian prior standard deviation from
0.5to0.02raises from0.2to125.0and shrinks||w||from0.3671to0.3233. - At every prior scale, the analytical MAP vector matches
sklearn.linear_model.Ridgeto floating-point precision.
M48-C10 · Fix the bug: underflowing Metropolis–Hastings acceptance ratio
Section titled “M48-C10 · Fix the bug: underflowing Metropolis–Hastings acceptance ratio”Fix the bug: the starter tries to sample the posterior rate of 80 Exponential observations under a prior by multiplying raw PDFs (np.prod(...)), which underflows to 0.0 / 0.0. Rewrite log_post_rate in log-space (logpdf summed, returning -np.inf for ) and compare your MCMC posterior mean after 1,000 burn-in steps against the exact conjugate mean.
acc=0.556 | MH mean=0.4255 | exact=0.4228rng = np.random.default_rng(42)obs_x = rng.exponential(scale=1 / 0.4, size=80)
def post_rate_buggy(lam_val: float) -> float: # BUG: raw product of 80 densities underflows to 0.0 if lam_val <= 0: return 0.0 lik = np.prod(stats.expon(scale=1 / lam_val).pdf(obs_x)) prior = stats.gamma(a=2.0, scale=1 / 2.0).pdf(lam_val) return float(lik * prior)
# TODO: rewrite in log-space, run 5000 MH steps (step_sd=0.08, start=0.5, burn=1000)# TODO: print acc, MH mean, and exact conjugate meanHint 1
Replace np.prod(...pdf(...)) with stats.expon(scale=1 / lam_val).logpdf(obs_x).sum() and add stats.gamma(a=2.0, scale=1 / 2.0).logpdf(lam_val).
Hint 2
Accept when np.log(rng.random()) < prop_lp - cur_lp.
Solution
rng = np.random.default_rng(42)obs_x = rng.exponential(scale=1 / 0.4, size=80)
def log_post_rate(lam_val: float) -> float: if lam_val <= 0: return -np.inf ll = stats.expon(scale=1 / lam_val).logpdf(obs_x).sum() lp = stats.gamma(a=2.0, scale=1 / 2.0).logpdf(lam_val) return float(ll + lp)
cur = 0.5cur_lp = log_post_rate(cur)chain = np.empty(5000)acc = 0for t in range(5000): prop = cur + rng.normal(0.0, 0.08) prop_lp = log_post_rate(prop) if np.log(rng.random()) < prop_lp - cur_lp: cur, cur_lp = prop, prop_lp acc += 1 chain[t] = cur
exact = stats.gamma(a=2.0 + len(obs_x), scale=1 / (2.0 + obs_x.sum()))mh_mean = float(chain[1000:].mean())print(f"acc={acc / 5000:.3f} | MH mean={mh_mean:.4f} | exact={exact.mean():.4f}")
assert abs(mh_mean - exact.mean()) < 0.01assert 0.25 < acc / 5000 < 0.65acc=0.556 | MH mean=0.4255 | exact=0.4228How it works:
- Summing log-densities avoids underflow completely, and returning
-np.inffor automatically rejects invalid negative proposals. - After 1,000 burn-in steps, the sampler recovers the exact conjugate posterior mean (
0.4255vs0.4228).
M48-C11 · Cross-entropy loss equals entropy plus KL divergence
Section titled “M48-C11 · Cross-entropy loss equals entropy plus KL divergence”Perform two numerical checks: (1) for discrete distributions and , verify that in nats; (2) fit LogisticRegression() on customers[["tenure_months", "support_tickets"]] predicting churned, and verify that scikit-learn’s log_loss equals the manual binary cross-entropy formula .
H(P)=0.9376 + KL=0.0207 = 0.9583 | CE=0.9583sklearn log_loss=0.424945 | manual=0.424945p_t = np.array([0.6, 0.25, 0.15])q_m = np.array([0.5, 0.30, 0.20])# TODO: verify H(P) + KL(P||Q) == CE(P, Q)# TODO: fit LogisticRegression on tenure_months and support_tickets and check log_lossHint 1
stats.entropy(p_t) returns in nats; stats.entropy(p_t, q_m) returns in nats.
Solution
p_t = np.array([0.6, 0.25, 0.15])q_m = np.array([0.5, 0.30, 0.20])h_p = float(stats.entropy(p_t))ce = float(-np.sum(p_t * np.log(q_m)))kl = float(stats.entropy(p_t, q_m))
X_c = customers[["tenure_months", "support_tickets"]].to_numpy(dtype=float)y_c_bin = customers["churned"].to_numpy()clf = LogisticRegression().fit(X_c, y_c_bin)probs_c = clf.predict_proba(X_c)[:, 1]sk_ll = float(log_loss(y_c_bin, probs_c))manual_ll = float( -np.mean(y_c_bin * np.log(probs_c) + (1 - y_c_bin) * np.log(1 - probs_c)))
print(f"H(P)={h_p:.4f} + KL={kl:.4f} = {h_p + kl:.4f} | CE={ce:.4f}")print(f"sklearn log_loss={sk_ll:.6f} | manual={manual_ll:.6f}")
assert np.isclose(h_p + kl, ce, atol=1e-12)assert np.isclose(sk_ll, manual_ll, atol=1e-12)H(P)=0.9376 + KL=0.0207 = 0.9583 | CE=0.9583sklearn log_loss=0.424945 | manual=0.424945How it works:
- Cross-entropy decomposes cleanly into irreducible entropy plus avoidable divergence .
- Logistic regression’s
log_lossis literally average binary cross-entropy in nats.
M48-C12 · Rank features with mutual information vs. Pearson correlation
Section titled “M48-C12 · Rank features with mutual information vs. Pearson correlation”Interpret a result: for ["sqft", "bedrooms", "bathrooms", "year_built", "condition", "distance_to_center_km"] in houses, compute both absolute Pearson correlation with price and mutual_info_regression(..., random_state=42). Sort features from highest to lowest mutual information and explain why distance_to_center_km ranks so much higher under MI than under .
sqft |r|=0.730 MI=0.381distance_to_center_km |r|=0.143 MI=0.343bathrooms |r|=0.635 MI=0.258bedrooms |r|=0.625 MI=0.251year_built |r|=0.202 MI=0.030condition |r|=0.213 MI=0.029h_cols = [ "sqft", "bedrooms", "bathrooms", "year_built", "condition", "distance_to_center_km",]# TODO: compute mutual_info_regression and |corr| with houses["price"]# TODO: sort by MI descending and print each lineHint 1
mutual_info_regression(houses[h_cols], houses["price"], random_state=42) returns an array aligned with h_cols.
Solution
h_cols = [ "sqft", "bedrooms", "bathrooms", "year_built", "condition", "distance_to_center_km",]mi_h = mutual_info_regression(houses[h_cols], houses["price"], random_state=42)rows = []for col, mv in zip(h_cols, mi_h, strict=True): rows.append((col, abs(float(houses[col].corr(houses["price"]))), float(mv)))rows.sort(key=lambda item: -item[2])
for col, r_v, m_v in rows: print(f"{col:<22} |r|={r_v:.3f} MI={m_v:.3f}")
assert rows[0][0] == "sqft"assert rows[1][0] == "distance_to_center_km"sqft |r|=0.730 MI=0.381distance_to_center_km |r|=0.143 MI=0.343bathrooms |r|=0.635 MI=0.258bedrooms |r|=0.625 MI=0.251year_built |r|=0.202 MI=0.030condition |r|=0.213 MI=0.029How it works:
distance_to_center_kmhas the weakest linear correlation (|r| = 0.143) yet ranks #2 in mutual information (0.343).- Price varies sharply and non-monotonically by neighborhood distance (some high-end neighborhoods like Lakeview and Oak Hill sit mid-distance rather than right at distance 0), so Pearson correlation cancels out while MI detects the strong non-linear dependence.
Challenge
Section titled “Challenge”M48-X01 · Highest Posterior Density (HPD) interval vs. equal-tailed CrI
Section titled “M48-X01 · Highest Posterior Density (HPD) interval vs. equal-tailed CrI”Draw 50,000 samples from a heavily skewed posterior using rng = np.random.default_rng(42). Compute both the 95% equal-tailed credible interval and the 95% Highest Posterior Density (HPD) interval—the narrowest interval containing 95% of sorted draws—and verify that the HPD interval is strictly narrower.
Equal-tailed 95%: [0.0028, 0.2031] width=0.2003HPD 95%: [0.0000, 0.1701] width=0.1701rng = np.random.default_rng(42)draws = stats.beta(1.2, 18.0).rvs(50_000, random_state=rng)# TODO: compute 95% equal-tailed interval# TODO: sort draws and slide a window of size int(np.floor(0.95 * len(draws)))# to find the shortest 95% interval (HPD)Hint 1
With sorted array s and n_keep = int(np.floor(0.95 * len(s))), every contiguous 95% interval has width s[i + n_keep] - s[i] for i in 0 .. len(s) - n_keep - 1.
Hint 2
Vectorize the scan in one line: widths = s[n_keep:] - s[: len(s) - n_keep], then take best = int(np.argmin(widths)).
Solution
rng = np.random.default_rng(42)draws = stats.beta(1.2, 18.0).rvs(50_000, random_state=rng)
et_lo, et_hi = np.quantile(draws, [0.025, 0.975])s = np.sort(draws)n_keep = int(np.floor(0.95 * len(s)))widths = s[n_keep:] - s[: len(s) - n_keep]best = int(np.argmin(widths))hpd_lo, hpd_hi = float(s[best]), float(s[best + n_keep])
print(f"Equal-tailed 95%: [{et_lo:.4f}, {et_hi:.4f}] width={et_hi - et_lo:.4f}")print(f"HPD 95%: [{hpd_lo:.4f}, {hpd_hi:.4f}] width={hpd_hi - hpd_lo:.4f}")
assert (hpd_hi - hpd_lo) < (et_hi - et_lo)assert hpd_lo < et_loEqual-tailed 95%: [0.0028, 0.2031] width=0.2003HPD 95%: [0.0000, 0.1701] width=0.1701How it works:
- Because piles mass near 0 with a long right tail, chopping 2.5% from the dense left side forces the equal-tailed interval far out to
0.2031. - The HPD interval keeps the high-density region near
0.0000and trims the sparse right tail instead, shrinking interval width by 15% (0.1701vs0.2003).
M48-X02 · Bayesian revenue-per-user A/B test (Beta × Log-normal)
Section titled “M48-X02 · Bayesian revenue-per-user A/B test (Beta × Log-normal)”Combine conversion probability and buyer order value on ab to run a Bayesian revenue-per-user (RPU) A/B test. For each arm (control, then treatment, using one shared rng = np.random.default_rng(42) and 40,000 draws):
- Draw conversion rate .
- On log-revenue of buyers ( buyers, sample mean and sample variance ), draw posterior variance and mean (exact non-informative Normal posterior), then compute average order value .
- Multiply and print both arms’ posterior mean RPU, , the 95% CrI for , and expected USD loss per user if shipping treatment.
RPU control mean=4.405 | treatment mean=4.860P(RPU_T > RPU_C)=0.9170 | 95% CrI=[-0.191 1.1 ]Expected loss if shipping T: USD 0.0125 per userrng = np.random.default_rng(42)n_mc = 40_000rpu_draws = {}for grp in ["control", "treatment"]: # TODO: draw Beta conversion posterior p_s # TODO: draw posterior sig2_s and mu_s on log buyer revenue, compute aov_s # TODO: store rpu_draws[grp] = p_s * aov_s ...# TODO: print arm means, P(RPU_T > RPU_C), 95% CrI and expected loss per userHint 1
sig2_s = (n_b - 1) * s2_b / rng.chisquare(df=n_b - 1, size=n_mc) and mu_s = rng.normal(m_b, np.sqrt(sig2_s / n_b)).
Hint 2
Expected loss of shipping treatment is np.maximum(rpu_draws["control"] - rpu_draws["treatment"], 0.0).mean().
Solution
rng = np.random.default_rng(42)n_mc = 40_000rpu_draws = {}for grp in ["control", "treatment"]: g_df = ab[ab["group"] == grp] k_g = int(g_df["converted"].sum()) n_g = len(g_df) p_s = stats.beta(1 + k_g, 1 + n_g - k_g).rvs(n_mc, random_state=rng) y_log = np.log(g_df.loc[g_df["converted"] == 1, "revenue"].to_numpy()) n_b = len(y_log) m_b = float(y_log.mean()) s2_b = float(y_log.var(ddof=1)) sig2_s = (n_b - 1) * s2_b / rng.chisquare(df=n_b - 1, size=n_mc) mu_s = rng.normal(m_b, np.sqrt(sig2_s / n_b)) aov_s = np.exp(mu_s + 0.5 * sig2_s) rpu_draws[grp] = p_s * aov_s
diff_rpu = rpu_draws["treatment"] - rpu_draws["control"]p_rpu_win = float((diff_rpu > 0).mean())loss_t = float(np.maximum(-diff_rpu, 0.0).mean())cri_rpu = np.quantile(diff_rpu, [0.025, 0.975]).round(3)
c_mean = rpu_draws["control"].mean()t_mean = rpu_draws["treatment"].mean()print(f"RPU control mean={c_mean:.3f} | treatment mean={t_mean:.3f}")print(f"P(RPU_T > RPU_C)={p_rpu_win:.4f} | 95% CrI={cri_rpu}")print(f"Expected loss if shipping T: USD {loss_t:.4f} per user")
assert 0.85 < p_rpu_win < 0.98assert loss_t < 0.05RPU control mean=4.405 | treatment mean=4.860P(RPU_T > RPU_C)=0.9170 | 95% CrI=[-0.191 1.1 ]Expected loss if shipping T: USD 0.0125 per userHow it works:
- Although conversion beats control with 99.4% probability, buyer order values are noisy and slightly lower in treatment, so revenue-per-user wins with 91.7% probability.
- Expected downside risk is only
USD 0.0125per user compared with an expected gain of aboutUSD 0.455per user—a compelling risk–reward trade-off.
M48-X03 · Refactor a Metropolis–Hastings sampler with a split-half check
Section titled “M48-X03 · Refactor a Metropolis–Hastings sampler with a split-half check”Refactor: encapsulate random-walk Metropolis–Hastings in a clean reusable function metropolis_hastings(log_post, x0, step_scale, n_steps, burn, rng) returning (samples, acceptance_rate). Run it on a 2-parameter Bayesian logistic regression (intercept and standardized tenure_months) on customers.sample(n=500, random_state=42) with prior , x0=[0.0, 0.0], step_scale=[0.16, 0.16], n_steps=6000, burn=1500. Verify convergence by checking that the first-half and second-half posterior means differ by less than 0.05.
acc=0.522 | mean=[-1.8658 -1.192 ]half1=[-1.8584 -1.1851] | half2=[-1.8733 -1.199 ] | max_diff=0.0148def metropolis_hastings(log_post, x0, step_scale, n_steps, burn, rng): # TODO: implement generic random-walk MH returning (chain[burn:], acc_rate) ...
# TODO: sample 500 customers, standardize tenure_months, define lp_2d, run sampler# TODO: print acceptance rate, overall mean, and split-half diagnosticHint 1
Accept a proposal vector prop = x + rng.normal(0.0, step_scale) whenever np.log(rng.random()) < prop_lp - cur_lp.
Solution
def metropolis_hastings(log_post, x0, step_scale, n_steps, burn, rng): x = np.asarray(x0, dtype=float).copy() cur_lp = float(log_post(x)) chain = np.empty((n_steps, len(x))) accepted = 0 for t in range(n_steps): prop = x + rng.normal(0.0, step_scale) prop_lp = float(log_post(prop)) if np.log(rng.random()) < prop_lp - cur_lp: x, cur_lp = prop, prop_lp accepted += 1 chain[t] = x return chain[burn:], accepted / n_steps
sub_c = customers.sample(n=500, random_state=42)ten = sub_c["tenure_months"].to_numpy(dtype=float)ten_std = (ten - ten.mean()) / ten.std()X2 = np.column_stack([np.ones(len(sub_c)), ten_std])y2 = sub_c["churned"].to_numpy(dtype=float)
def lp_2d(b: np.ndarray) -> float: z = X2 @ b return float(np.sum(y2 * z - np.logaddexp(0.0, z)) - 0.5 * np.sum((b / 2.0) ** 2))
samples2, acc2 = metropolis_hastings( lp_2d, [0.0, 0.0], [0.16, 0.16], 6000, 1500, np.random.default_rng(42))half = len(samples2) // 2m1 = samples2[:half].mean(axis=0)m2 = samples2[half:].mean(axis=0)max_diff = float(np.max(np.abs(m1 - m2)))
print(f"acc={acc2:.3f} | mean={samples2.mean(axis=0).round(4)}")print(f"half1={m1.round(4)} | half2={m2.round(4)} | max_diff={max_diff:.4f}")
assert 0.25 < acc2 < 0.65assert max_diff < 0.05acc=0.522 | mean=[-1.8658 -1.192 ]half1=[-1.8584 -1.1851] | half2=[-1.8733 -1.199 ] | max_diff=0.0148How it works:
- Passing
log_postas a callable decouples the sampler from any specific model. - Splitting the post-burn-in chain in half is a fast stationarity check: both halves agree to
0.0148, confirming the chain has settled around the true posterior.
M48-X04 · Dirichlet–Multinomial posterior for review star ratings
Section titled “M48-X04 · Dirichlet–Multinomial posterior for review star ratings”Star ratings in reviews take discrete values 1 through 5. Placing a uniform prior on the 5-star probability vector yields a conjugate posterior. For P007 (Robot Vacuum) and P018 (Adjustable Dumbbells), draw 20,000 posterior probability vectors each using one shared rng = np.random.default_rng(42), compute the expected star rating , print each product’s posterior mean and 95% CrI, and compute .
P007: post mean=3.084, 95% CrI=[2.73 3.431]P018: post mean=4.172, 95% CrI=[3.85 4.444]P(E[P018] > E[P007])=1.0000rng = np.random.default_rng(42)stars = np.arange(1, 6, dtype=float)# TODO: for pid in ["P007", "P018"], count ratings 1..5, draw 20_000 Dirichlet samples# TODO: compute expected rating draws @ stars, print posterior mean, 95% CrI, and P(P018 > P007)Hint 1
Use .value_counts().reindex([1, 2, 3, 4, 5], fill_value=0) so any missing star level still gets count 0.
Hint 2
rng.dirichlet(alpha_post, size=20_000) returns a (20000, 5) array; multiplying by stars (draws_dir @ stars) gives 20,000 expected-rating draws.
Solution
rng = np.random.default_rng(42)stars = np.arange(1, 6, dtype=float)exp_ratings = {}
for pid in ["P007", "P018"]: vc = ( reviews.loc[reviews["product_id"] == pid, "rating"] .value_counts() .reindex([1, 2, 3, 4, 5], fill_value=0) ) alpha_post = 1.0 + vc.to_numpy(dtype=float) draws_dir = rng.dirichlet(alpha_post, size=20_000) exp_r = draws_dir @ stars exp_ratings[pid] = exp_r cri = np.quantile(exp_r, [0.025, 0.975]).round(3) print(f"{pid}: post mean={exp_r.mean():.3f}, 95% CrI={cri}")
p_better = float((exp_ratings["P018"] > exp_ratings["P007"]).mean())print(f"P(E[P018] > E[P007])={p_better:.4f}")
assert p_better > 0.999assert exp_ratings["P018"].mean() > exp_ratings["P007"].mean() + 0.8P007: post mean=3.084, 95% CrI=[2.73 3.431]P018: post mean=4.172, 95% CrI=[3.85 4.444]P(E[P018] > E[P007])=1.0000How it works:
- Unlike a Normal approximation on ratings, the Dirichlet–Multinomial model respects the exact discrete 1–5 star scale.
- The two 95% credible intervals do not even overlap (
[2.73, 3.431]vs[3.85, 4.444]), confirmingP018is decisively higher rated thanP007.
M48-X05 · Sliding-window Jensen–Shannon drift detector on sensors
Section titled “M48-X05 · Sliding-window Jensen–Shannon drift detector on sensors”Build a daily drift monitor on sensors. Treat May 1–3 (2024-05-01 through 2024-05-03) as the healthy reference baseline. For S3 (temperature_c, bins np.linspace(18, 45, 28)) and S4 (vibration_mm_s, bins np.linspace(1, 20, 20)), compute the smoothed Jensen–Shannon divergence (eps = 1e-6) of every day’s readings against the baseline, and report the first date each sensor crosses the alert threshold JS > 0.08 along with its maximum daily JS divergence.
S3 temperature_c : first JS>0.08 on 2024-05-04 (JS=0.0926, max=0.5060)S4 vibration_mm_s: first JS>0.08 on 2024-05-12 (JS=0.4484, max=0.6890)sens = sensors.copy()sens["date"] = pd.to_datetime(sens["timestamp"]).dt.strftime("%Y-%m-%d")base_dates = {"2024-05-01", "2024-05-02", "2024-05-03"}# TODO: for (S3, temperature_c) and (S4, vibration_mm_s), build baseline histogram# TODO: loop over dates in chronological order, compute daily JS divergence# TODO: print first date crossing JS > 0.08 and maximum JS divergenceHint 1
df_s.groupby("date") iterates over dates in sorted chronological order because dates are ISO YYYY-MM-DD.
Hint 2
Remember to square jensenshannon(p_base, q_day) to get JS divergence rather than JS distance.
Solution
sens = sensors.copy()sens["date"] = pd.to_datetime(sens["timestamp"]).dt.strftime("%Y-%m-%d")base_dates = {"2024-05-01", "2024-05-02", "2024-05-03"}alerts = {}
for sid, col, bins in [ ("S3", "temperature_c", np.linspace(18, 45, 28)), ("S4", "vibration_mm_s", np.linspace(1, 20, 20)),]: df_s = sens[sens["sensor_id"] == sid] base_vals = df_s.loc[df_s["date"].isin(base_dates), col].dropna() p_base, _ = np.histogram(base_vals, bins=bins) p_base = (p_base + 1e-6) / (p_base.sum() + 1e-6 * len(p_base))
first_alert = None max_js = 0.0 for dt, grp in df_s.groupby("date"): q_day, _ = np.histogram(grp[col].dropna(), bins=bins) q_day = (q_day + 1e-6) / (q_day.sum() + 1e-6 * len(q_day)) js = float(jensenshannon(p_base, q_day) ** 2) max_js = max(max_js, js) if first_alert is None and js > 0.08: first_alert = (dt, js)
alerts[sid] = first_alert[0] print( f"{sid} {col:<14}: first JS>0.08 on {first_alert[0]}" f" (JS={first_alert[1]:.4f}, max={max_js:.4f})" )
assert alerts["S3"] == "2024-05-04"assert alerts["S4"] == "2024-05-12"S3 temperature_c : first JS>0.08 on 2024-05-04 (JS=0.0926, max=0.5060)S4 vibration_mm_s: first JS>0.08 on 2024-05-12 (JS=0.4484, max=0.6890)How it works:
S3drifts steadily from day 1, so by May 4 its daily temperature distribution already diverges past0.08and climbs to0.5060.S4stays healthy through May 11, then jumps straight toJS = 0.4484on May 12—the exact onset of mechanical wear—making JS divergence an effective zero-label production monitor.