Skip to content

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:

  1. Read the task and expected output (or acceptance criteria for predict-the-output exercises).
  2. 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.
  3. Run the script and compare your output line by line.
  4. 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 np
import pandas as pd
from scipy import stats
from scipy.spatial.distance import jensenshannon
from sklearn.feature_selection import mutual_info_regression
from sklearn.linear_model import LogisticRegression, Ridge
from 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")

M48-W01 · Law of total probability on churn by plan

Section titled “M48-W01 · Law of total probability on churn by plan”
Warm-up

Using customers, compute the share of each plan (P(plan)P(\text{plan})) and the conditional churn rate (P(churn∣plan)P(\text{churn} \mid \text{plan})). Combine them via the law of total probability and verify the sum equals the overall churn rate.

Expected output
basic share=0.406 churn=0.1736
premium share=0.198 churn=0.2960
standard share=0.396 churn=0.1604
total_prob=0.1926 | direct=0.1926
Starter
# 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 comparison
Hint 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)
Output
basic share=0.406 churn=0.1736
premium share=0.198 churn=0.2960
standard share=0.396 churn=0.1604
total_prob=0.1926 | direct=0.1926

How it works:

  1. The three plan tiers partition all 5,000 customers without overlap, so their shares sum to 1.0.
  2. 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”
Warm-up

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 P(flag)P(\text{flag}) and P(fault∣flag)P(\text{fault} \mid \text{flag}) 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 P(fault∣flag)P(\text{fault} \mid \text{flag}) is far below 0.92.
Starter
prior = 0.015
sens = 0.92
fpr = 0.04
p_flag = sens * prior + fpr * (1 - prior)
post = sens * prior / p_flag
# TODO: predict both printed values before running
print(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.015
sens = 0.92
fpr = 0.04
p_flag = sens * prior + fpr * (1 - prior)
post = sens * prior / p_flag
print(f"P(flag)={p_flag:.4f}")
print(f"P(fault | flag)={post:.4f}")
assert round(p_flag, 4) == 0.0532
assert round(post, 4) == 0.2594
Output
P(flag)=0.0532
P(fault | flag)=0.2594

How it works:

  1. Only 1.38% of all machines are true-positive flags, while 3.94% are false alarms from the huge healthy population.
  2. Dividing 0.0138 / 0.0532 gives 0.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”
Warm-up

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.

Expected output
P(online, Electronics): 0.0836
P(Electronics | online): 0.1991
P(Electronics | store): 0.1919
Starter
# TODO: build joint and conditional crosstabs on sales["channel"] and sales["category"]
# TODO: print the three requested probabilities rounded to 4 decimals
Hint 1

Pass normalize="all" to pd.crosstab for the joint table and normalize="index" for P(column∣row)P(\text{column} \mid \text{row}).

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)
Output
P(online, Electronics): 0.0836
P(Electronics | online): 0.1991
P(Electronics | store): 0.1919

How it works:

  1. normalize="all" divides every cell by the total row count (20,228), giving joint probabilities that sum to 1.
  2. normalize="index" divides each row by its row sum, yielding conditional probabilities given channel.
  3. 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”
Warm-up

Fix the bug: API requests arrive at rate λ=0.2\lambda = 0.2 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.

Expected output
Expon mean=5.00, P(X>10)=0.1353
Gamma mean=15.00, var=75.00
Starter
lam = 0.2
# BUG: SciPy expects scale = 1 / rate, not rate
exp_d = stats.expon(scale=lam)
gam_d = stats.gamma(a=3, scale=lam)
# TODO: fix both calls above and print the stats
Hint 1

For rate λ\lambda, the Exponential mean is 1/λ=5.01/\lambda = 5.0 and the Gamma(α=3,β=λ\alpha=3, \beta=\lambda) mean is α/β=15.0\alpha / \beta = 15.0.

Solution
lam = 0.2
exp_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)
Output
Expon mean=5.00, P(X>10)=0.1353
Gamma mean=15.00, var=75.00

How it works:

  1. SciPy parameterizes both expon and gamma by scale = 1 / rate.
  2. Waiting for 3 Poisson arrivals at rate 0.2/s is the sum of 3 independent Exponential(0.2) waits, giving mean 3×5=153 \times 5 = 15 s and variance 3×25=75 s23 \times 25 = 75\text{ s}^2.

M48-W05 · Beta–Binomial conjugate update

Section titled “M48-W05 · Beta–Binomial conjugate update”
Warm-up

You place a Beta(2,18)\text{Beta}(2, 18) 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.

Expected output
Beta(36, 234) mean=0.1333
95% CrI=[0.0955, 0.1763]
Starter
a0, b0 = 2, 18
clicks, sent = 34, 250
# TODO: build the conjugate Beta posterior, print its parameters, mean and 95% CrI
Hint 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, 18
clicks, sent = 34, 250
post = 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() < hi
Output
Beta(36, 234) mean=0.1333
95% CrI=[0.0955, 0.1763]

How it works:

  1. Adding successes to α\alpha and failures to β\beta gives Beta(36,234)\text{Beta}(36, 234).
  2. The posterior mean 0.1333 sits slightly below the raw rate 34 / 250 = 0.1360 because the prior pulled lightly toward 0.10.

M48-W06 · Gamma–Poisson sequential update on support tickets

Section titled “M48-W06 · Gamma–Poisson sequential update on support tickets”
Warm-up

An hourly ticket stream follows Poisson(λ)\text{Poisson}(\lambda) with conjugate prior Gamma(α0=4,β0=0.25)\text{Gamma}(\alpha_0=4, \beta_0=0.25) (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.

Expected output
Batch: Gamma(104.0, 6.25) | Seq: Gamma(104.0, 6.25)
Post mean=16.6400, 95% CrI=[13.596 19.987]
Starter
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% CrI
Hint 1

Each new count cc adds cc to α\alpha and 11 to β\beta.

Solution
counts = np.array([14, 19, 12, 21, 16, 18])
a0, b0 = 4.0, 0.25
a_batch, b_batch = a0 + counts.sum(), b0 + len(counts)
a_seq, b_seq = a0, b0
for 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_seq
assert np.isclose(post_g.mean(), 104.0 / 6.25)
Output
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:

  1. Bayesian updating is order-invariant: updating hour by hour yields the exact same Gamma(104.0,6.25)\text{Gamma}(104.0, 6.25) as updating on all six hours at once.
  2. Remember to pass scale=1 / b_seq to stats.gamma.

M48-W07 · Shannon entropy of customer regions and plans

Section titled “M48-W07 · Shannon entropy of customer regions and plans”
Warm-up

Compute the Shannon entropy in bits (base=2) of customers["region"] and customers["plan"], along with each column’s maximum possible entropy log⁡2K\log_2 K and the ratio H/Hmax⁡H / H_{\max}. Which column is closer to a uniform split?

Expected output
region H=1.9938 bits (max 2.0000, ratio 0.997)
plan H=1.5198 bits (max 1.5850, ratio 0.959)
Starter
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 KK.

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.0
Output
region H=1.9938 bits (max 2.0000, ratio 0.997)
plan H=1.5198 bits (max 1.5850, ratio 0.959)

How it works:

  1. Four equal regions have maximum entropy log⁡24=2.0\log_2 4 = 2.0 bits; region achieves 99.7% of that ceiling.
  2. plan has fewer premium customers (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”
Warm-up

Predict the output: given P=[0.8,0.2]P = [0.8, 0.2] and Q=[0.5,0.5]Q = [0.5, 0.5], 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 (≈0.8ln⁡(1.6)+0.2ln⁡(0.4)\approx 0.8 \ln(1.6) + 0.2 \ln(0.4)) before running the code.

Acceptance criteria:

  • Write your numerical predictions for KL(P||Q), KL(Q||P) and whether JS is symmetric, then run the code.
  • Explain why KL(Q||P) is larger than KL(P||Q) here.
Starter
p = np.array([0.8, 0.2])
q = np.array([0.5, 0.5])
# TODO: predict all three printed lines before running
print(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 ln⁡(0.5/0.2)=ln⁡(2.5)≈0.916\ln(0.5 / 0.2) = \ln(2.5) \approx 0.916, heavily penalizing PP‘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)
Output
KL(P||Q)=0.1927
KL(Q||P)=0.2231
JS(P||Q)=0.0507 | JS(Q||P)=0.0507

How it works:

  1. KL divergence weights log⁡(P/Q)\log(P/Q) by the first argument, so KL(P||Q) = 0.1927 differs from KL(Q||P) = 0.2231.
  2. Jensen–Shannon divergence averages both directions against the midpoint M=(P+Q)/2M = (P+Q)/2, guaranteeing exact symmetry (0.0507).

M48-C01 · Covariance matrix and multivariate normal density

Section titled “M48-C01 · Covariance matrix and multivariate normal density”
Core

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].

Expected output
n=2910 | corr(sqft, price)=0.7312
logpdf(mean)=-30.091 | logpdf([2500,9000,600000])=-30.578
Starter
# TODO: drop NaNs from houses[["sqft", "lot_sqft", "price"]]
# TODO: compute mean vector, covariance matrix, correlation matrix and multivariate_normal
# TODO: print the requested statistics
Hint 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) == 2910
assert lp_mean > lp_pt
assert np.allclose(cov_h, cov_h.T)
Output
n=2910 | corr(sqft, price)=0.7312
logpdf(mean)=-30.091 | logpdf([2500,9000,600000])=-30.578

How it works:

  1. lot_sqft has 90 missing rows in houses.csv, leaving 2,910 complete observations.
  2. The multivariate normal density peaks at mu_h, so logpdf(mean) is strictly greater than logpdf at 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”
Core

Select all converted buyers (ab["converted"] == 1) and extract their positive revenue. Estimate the log-scale parameters μ^=ln⁡x‾\hat{\mu} = \overline{\ln x} and σ^=sln⁡x\hat{\sigma} = s_{\ln x} (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.

Expected output
mu_log=3.5410, sigma_log=0.6430
Sample mean=42.36, median=35.03
LogNorm mean=42.42, median=34.50
Starter
buyers = 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 median
Hint 1

In SciPy, stats.lognorm(s=sigma, scale=np.exp(mu)) has median eμe^\mu and mean eμ+σ2/2e^{\mu + \sigma^2/2}.

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.5
Output
mu_log=3.5410, sigma_log=0.6430
Sample mean=42.36, median=35.03
LogNorm mean=42.42, median=34.50

How it works:

  1. Fitting a normal distribution on ln⁡(revenue)\ln(\text{revenue}) yields μ^=3.5410\hat{\mu} = 3.5410 and σ^=0.6430\hat{\sigma} = 0.6430.
  2. The fitted Log-normal closely reproduces both the right-skewed sample mean (42.42 vs 42.36 USD) and the sample median (34.50 vs 35.03 USD).

M48-C03 · Multinomial probabilities for category basket mixes

Section titled “M48-C03 · Multinomial probabilities for category basket mixes”
Core

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].

Expected output
Top share: Clothing (0.1984)
PMF balanced [2,2,2,2,2,2]: 0.003008
PMF heavy-elec [1,6,2,1,1,1]: 0.000309
Starter
cats = ["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 vectors
Hint 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_elec
Output
Top share: Clothing (0.1984)
PMF balanced [2,2,2,2,2,2]: 0.003008
PMF heavy-elec [1,6,2,1,1,1]: 0.000309

How it works:

  1. 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”
Core

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 P(tickets≥5)P(\text{tickets} \ge 5) against the observed share. Is overdispersion mild or severe here?

Expected output
mean=1.239, var=1.372, ratio=1.11
P(tickets>=5) obs=0.0106 | Pois=0.0088 | NB=0.0131
Starter
tix = 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 P(X≥5)P(X \ge 5), 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_t
assert pois_ge5 < obs_ge5 < nb_ge5
Output
mean=1.239, var=1.372, ratio=1.11
P(tickets>=5) obs=0.0106 | Pois=0.0088 | NB=0.0131

How it works:

  1. Unlike daily orders (variance/mean = 5.11), support tickets have only mild overdispersion (ratio 1.11).
  2. 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”
Core

Run a conjugate Beta–Binomial A/B test (prior Beta(1,1)\text{Beta}(1, 1)) 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 P(treatment>control)P(\text{treatment} > \text{control}) and the mean relative lift for each device.

Expected output
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%
Starter
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.95
assert probs_win["tablet"] < 0.5
Output
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%

How it works:

  1. Both desktop (98.2%) and mobile (96.8%) show strong evidence of a positive lift.
  2. tablet has 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”
Core

After observing 24 signups out of 200 trial visitors (prior Beta(1,1)\text{Beta}(1, 1)), 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 p=24/200p = 24 / 200.

Expected output
Posterior predictive 90%: [84.0, 168.0] (width 84.0)
Plug-in MLE 90%: [103.0, 137.0] (width 34.0)
Starter
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 widths
Hint 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)
Output
Posterior predictive 90%: [84.0, 168.0] (width 84.0)
Plug-in MLE 90%: [103.0, 137.0] (width 34.0)

How it works:

  1. Because pp was estimated from only 200 trials, parameter uncertainty dominates the forecast for 1,000 future visitors.
  2. The posterior predictive interval is more than twice as wide (84 vs 34), 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”
Core

Take the first 30 non-null temperature readings of sensor S1 in sensors. Assuming known reading noise σ=1.5\sigma = 1.5 °C and a Normal prior μ∼N(μ0=23.0,  τ02=2.02)\mu \sim \mathcal{N}(\mu_0=23.0,\; \tau_0^2=2.0^2), compute the exact Normal–Normal posterior mean and standard deviation using precision weighting:

1τn2=1τ02+nσ2,μn=τn2(μ0τ02+nxˉσ2)\frac{1}{\tau_n^2} = \frac{1}{\tau_0^2} + \frac{n}{\sigma^2}, \qquad \mu_n = \tau_n^2\left(\frac{\mu_0}{\tau_0^2} + \frac{n\bar{x}}{\sigma^2}\right)
Expected output
n=30, x_bar=19.727
Posterior N(19.787, 0.271^2)
Starter
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_post
Hint 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**2
tau_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 < mu0
assert tau_post < sigma / np.sqrt(n_obs)
Output
n=30, x_bar=19.727
Posterior N(19.787, 0.271^2)

How it works:

  1. Precision (inverse variance) adds cleanly: the prior precision 0.25 combines with the data precision 30 / 2.25 = 13.33.
  2. Because data precision is over 50× larger than prior precision, the posterior mean 19.787 sits right next to the sample mean 19.727 with a tiny posterior standard deviation of 0.271 °C.

M48-C08 · Empirical Bayes shrinkage of store-level online share

Section titled “M48-C08 · Empirical Bayes shrinkage of store-level online share”
Core

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.

Expected output
Prior Beta(281.2, 385.6) | mean=0.4217
Highest raw: S02 raw=0.4575 -> eb=0.4468
New store (3/4): raw=0.7500 -> eb=0.4237
Starter
# 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 lines
Hint 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 - 1
a0_s, b0_s = m_s * k_s, (1 - m_s) * k_s
st["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.01
Output
Prior Beta(281.2, 385.6) | mean=0.4217
Highest raw: S02 raw=0.4575 -> eb=0.4468
New store (3/4): raw=0.7500 -> eb=0.4237

How it works:

  1. All 12 stores cluster tightly around 42% online share, so the empirical prior is very concentrated (a0 + b0 ≈ 667 pseudo-orders).
  2. 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”
Core

Standardize ["sqft", "bedrooms", "bathrooms", "condition"] from houses and center y = np.log(houses["price"]). Fix noise variance σ2=0.05\sigma^2 = 0.05. For each prior standard deviation τ∈{0.02,0.1,0.5}\tau \in \{0.02, 0.1, 0.5\}, solve closed-form Gaussian MAP with λ=σ2/τ2\lambda = \sigma^2 / \tau^2 and assert it matches Ridge(alpha=lam, fit_intercept=True).coef_ to 1e-12. Notice how the weight norm grows as the prior loosens.

Expected output
tau=0.02 lam= 125.0 | ||w||=0.3233 | diff=7.22e-16
tau=0.1 lam= 5.0 | ||w||=0.3650 | diff=3.23e-16
tau=0.5 lam= 0.2 | ||w||=0.3671 | diff=8.33e-16
Starter
cols = ["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 Ridge
Hint 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]
Output
tau=0.02 lam= 125.0 | ||w||=0.3233 | diff=7.22e-16
tau=0.1 lam= 5.0 | ||w||=0.3650 | diff=3.23e-16
tau=0.5 lam= 0.2 | ||w||=0.3671 | diff=8.33e-16

How it works:

  1. Tightening the Gaussian prior standard deviation τ\tau from 0.5 to 0.02 raises λ=σ2/τ2\lambda = \sigma^2 / \tau^2 from 0.2 to 125.0 and shrinks ||w|| from 0.3671 to 0.3233.
  2. At every prior scale, the analytical MAP vector matches sklearn.linear_model.Ridge to 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”
Core

Fix the bug: the starter tries to sample the posterior rate λ\lambda of 80 Exponential observations under a Gamma(2,2)\text{Gamma}(2, 2) 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 λ≤0\lambda \le 0) and compare your MCMC posterior mean after 1,000 burn-in steps against the exact conjugate Gamma(2+n,2+∑xi)\text{Gamma}(2 + n, 2 + \sum x_i) mean.

Expected output
acc=0.556 | MH mean=0.4255 | exact=0.4228
Starter
rng = 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 mean
Hint 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.5
cur_lp = log_post_rate(cur)
chain = np.empty(5000)
acc = 0
for 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.01
assert 0.25 < acc / 5000 < 0.65
Output
acc=0.556 | MH mean=0.4255 | exact=0.4228

How it works:

  1. Summing log-densities avoids underflow completely, and returning -np.inf for λ≤0\lambda \le 0 automatically rejects invalid negative proposals.
  2. After 1,000 burn-in steps, the sampler recovers the exact conjugate posterior mean (0.4255 vs 0.4228).

M48-C11 · Cross-entropy loss equals entropy plus KL divergence

Section titled “M48-C11 · Cross-entropy loss equals entropy plus KL divergence”
Core

Perform two numerical checks: (1) for discrete distributions P=[0.6,0.25,0.15]P = [0.6, 0.25, 0.15] and Q=[0.5,0.30,0.20]Q = [0.5, 0.30, 0.20], verify that H(P)+DKL(P∥Q)=H(P,Q)H(P) + D_{\text{KL}}(P \Vert Q) = H(P, Q) 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 −1n∑[yiln⁡p^i+(1−yi)ln⁡(1−p^i)]-\frac{1}{n}\sum [y_i \ln \hat{p}_i + (1-y_i)\ln(1-\hat{p}_i)].

Expected output
H(P)=0.9376 + KL=0.0207 = 0.9583 | CE=0.9583
sklearn log_loss=0.424945 | manual=0.424945
Starter
p_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_loss
Hint 1

stats.entropy(p_t) returns H(P)H(P) in nats; stats.entropy(p_t, q_m) returns DKL(P∥Q)D_{\text{KL}}(P \Vert Q) 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)
Output
H(P)=0.9376 + KL=0.0207 = 0.9583 | CE=0.9583
sklearn log_loss=0.424945 | manual=0.424945

How it works:

  1. Cross-entropy decomposes cleanly into irreducible entropy H(P)H(P) plus avoidable divergence DKL(P∥Q)D_{\text{KL}}(P \Vert Q).
  2. Logistic regression’s log_loss is 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”
Core

Interpret a result: for ["sqft", "bedrooms", "bathrooms", "year_built", "condition", "distance_to_center_km"] in houses, compute both absolute Pearson correlation ∣r∣|r| 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 ∣r∣|r|.

Expected output
sqft |r|=0.730 MI=0.381
distance_to_center_km |r|=0.143 MI=0.343
bathrooms |r|=0.635 MI=0.258
bedrooms |r|=0.625 MI=0.251
year_built |r|=0.202 MI=0.030
condition |r|=0.213 MI=0.029
Starter
h_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 line
Hint 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"
Output
sqft |r|=0.730 MI=0.381
distance_to_center_km |r|=0.143 MI=0.343
bathrooms |r|=0.635 MI=0.258
bedrooms |r|=0.625 MI=0.251
year_built |r|=0.202 MI=0.030
condition |r|=0.213 MI=0.029

How it works:

  1. distance_to_center_km has the weakest linear correlation (|r| = 0.143) yet ranks #2 in mutual information (0.343).
  2. 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.

M48-X01 · Highest Posterior Density (HPD) interval vs. equal-tailed CrI

Section titled “M48-X01 · Highest Posterior Density (HPD) interval vs. equal-tailed CrI”
Challenge

Draw 50,000 samples from a heavily skewed posterior Beta(1.2,18.0)\text{Beta}(1.2, 18.0) 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.

Expected output
Equal-tailed 95%: [0.0028, 0.2031] width=0.2003
HPD 95%: [0.0000, 0.1701] width=0.1701
Starter
rng = 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_lo
Output
Equal-tailed 95%: [0.0028, 0.2031] width=0.2003
HPD 95%: [0.0000, 0.1701] width=0.1701

How it works:

  1. Because Beta(1.2,18.0)\text{Beta}(1.2, 18.0) 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.
  2. The HPD interval keeps the high-density region near 0.0000 and trims the sparse right tail instead, shrinking interval width by 15% (0.1701 vs 0.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)”
Challenge

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):

  1. Draw conversion rate p∼Beta(1+k,1+n−k)p \sim \text{Beta}(1 + k, 1 + n - k).
  2. On log-revenue of buyers (nbn_b buyers, sample mean yˉ\bar{y} and sample variance s2s^2), draw posterior variance σ2=(nb−1)s2/χnb−12\sigma^2 = (n_b - 1) s^2 / \chi^2_{n_b - 1} and mean μ∼N(yˉ,σ2/nb)\mu \sim \mathcal{N}(\bar{y}, \sigma^2 / n_b) (exact non-informative Normal posterior), then compute average order value AOV=exp⁡(μ+σ2/2)\text{AOV} = \exp(\mu + \sigma^2 / 2).
  3. Multiply RPU=p×AOV\text{RPU} = p \times \text{AOV} and print both arms’ posterior mean RPU, P(RPUT>RPUC)P(\text{RPU}_T > \text{RPU}_C), the 95% CrI for RPUT−RPUC\text{RPU}_T - \text{RPU}_C, and expected USD loss per user if shipping treatment.
Expected output
RPU control mean=4.405 | treatment mean=4.860
P(RPU_T > RPU_C)=0.9170 | 95% CrI=[-0.191 1.1 ]
Expected loss if shipping T: USD 0.0125 per user
Starter
rng = np.random.default_rng(42)
n_mc = 40_000
rpu_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 user
Hint 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_000
rpu_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.98
assert loss_t < 0.05
Output
RPU control mean=4.405 | treatment mean=4.860
P(RPU_T > RPU_C)=0.9170 | 95% CrI=[-0.191 1.1 ]
Expected loss if shipping T: USD 0.0125 per user

How it works:

  1. 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.
  2. Expected downside risk is only USD 0.0125 per user compared with an expected gain of about USD 0.455 per 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”
Challenge

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 N(0,22)\mathcal{N}(0, 2^2), 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.

Expected output
acc=0.522 | mean=[-1.8658 -1.192 ]
half1=[-1.8584 -1.1851] | half2=[-1.8733 -1.199 ] | max_diff=0.0148
Starter
def 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 diagnostic
Hint 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) // 2
m1 = 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.65
assert max_diff < 0.05
Output
acc=0.522 | mean=[-1.8658 -1.192 ]
half1=[-1.8584 -1.1851] | half2=[-1.8733 -1.199 ] | max_diff=0.0148

How it works:

  1. Passing log_post as a callable decouples the sampler from any specific model.
  2. 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”
Challenge

Star ratings in reviews take discrete values 1 through 5. Placing a uniform Dirichlet(1,1,1,1,1)\text{Dirichlet}(1, 1, 1, 1, 1) prior on the 5-star probability vector p\mathbf{p} yields a conjugate Dirichlet(1+c1,…,1+c5)\text{Dirichlet}(1 + c_1, \dots, 1 + c_5) 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 p⋅[1,2,3,4,5]\mathbf{p} \cdot [1, 2, 3, 4, 5], print each product’s posterior mean and 95% CrI, and compute P(E[RP018]>E[RP007])P(\mathbb{E}[R_{\text{P018}}] > \mathbb{E}[R_{\text{P007}}]).

Expected output
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.0000
Starter
rng = 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.999
assert exp_ratings["P018"].mean() > exp_ratings["P007"].mean() + 0.8
Output
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.0000

How it works:

  1. Unlike a Normal approximation on ratings, the Dirichlet–Multinomial model respects the exact discrete 1–5 star scale.
  2. The two 95% credible intervals do not even overlap ([2.73, 3.431] vs [3.85, 4.444]), confirming P018 is decisively higher rated than P007.

M48-X05 · Sliding-window Jensen–Shannon drift detector on sensors

Section titled “M48-X05 · Sliding-window Jensen–Shannon drift detector on sensors”
Challenge

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.

Expected output
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)
Starter
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 divergence
Hint 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"
Output
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:

  1. S3 drifts steadily from day 1, so by May 4 its daily temperature distribution already diverges past 0.08 and climbs to 0.5060.
  2. S4 stays healthy through May 11, then jumps straight to JS = 0.4484 on May 12—the exact onset of mechanical wear—making JS divergence an effective zero-label production monitor.