Skip to content

48. Probability, Bayesian statistics and information theory — Mini-project

Your analytics engineering team maintains three recurring probabilistic decisions every week:

  1. Experimentation: decide whether a new checkout flow improves both conversion rate and revenue per user, quantifying the exact probability of winning and the expected cost of a wrong launch.
  2. Catalog ranking: rank products by positive-review rate without letting low-volume items jump to the top or bottom on luck.
  3. Monitoring: detect silent sensor drift in production streams before hardware failures occur, without needing labeled failure events.

Write a clean, reusable Python script, bayesian_toolkit.py, with three modular functions—bayesian_ab_report, empirical_bayes_ratings and sensor_drift_audit—plus a three-panel summary figure showing posterior uncertainty and drift alerts across the course datasets.

You will use three datasets from your data/ folder (documented in the data dictionary):

File Rows Role in the toolkit
data/ab_test.csv 10,000 Control vs. treatment checkout conversion (converted) and buyer revenue (revenue)
data/reviews.csv 3,000 Product ratings (1–5) across 30 products (product_id, product, rating)
data/sensors.csv 8,064 10-minute readings (temperature_c, humidity_pct, vibration_mm_s) for sensors S1–S4 over May 1–14, 2024

Your script must:

  1. Implement bayesian_ab_report(ab_df, n_draws=40_000, seed=42) using a conjugate Beta(1,1)\text{Beta}(1, 1) prior for conversion and a non-informative Normal–Inverse-χ2\chi^2 posterior on ln⁡(revenue)\ln(\text{revenue}) for buyers. Return P(treatment>control)P(\text{treatment} > \text{control}), 95% credible intervals, and expected loss of shipping treatment for both conversion rate and revenue per user (RPU = conversion ×\times expected buyer value).
  2. Implement empirical_bayes_ratings(reviews_df) that defines a positive review as rating >= 4, estimates a catalog-wide Beta(α0,β0)\text{Beta}(\alpha_0, \beta_0) prior via method of moments across the 30 products, and returns a ranked DataFrame containing n, raw_rate, eb_rate, 95% credible interval bounds (cri_lo, cri_hi), raw_rank and eb_rank.
  3. Implement sensor_drift_audit(sensors_df, cutoff="2024-05-08", js_thresh=0.05) that splits readings into Week 1 (before cutoff) and Week 2 (on/after cutoff) and computes smoothed KL divergence DKL(Week 2∥Week 1)D_{\text{KL}}(\text{Week 2} \Vert \text{Week 1}) and Jensen–Shannon divergence DJSD_{\text{JS}} across all 4 sensors and all 3 numeric metrics (temperature_c, humidity_pct, vibration_mm_s), flagging rows where js_div > js_thresh.
  4. Print concise, readable tables (every output line at most 100 characters) for all three modules, plus the list of flagged sensor alerts.
  5. Produce a three-panel Matplotlib figure displaying: (a) the posterior RPU lift histogram with a vertical line at 0, (b) top-5 and bottom-3 empirical-Bayes product rates with 95% credible error bars, and (c) a grouped bar chart of sensor JS divergence across the three metrics with the 0.05 alert threshold.
  6. End with assert checks verifying key mathematical invariants (credible intervals bracket means, all JS divergences lie in [0,ln⁡2][0, \ln 2], shrinkage moves extreme products toward the prior mean, and the expected alerts fire).
  7. Summarize your executive findings in 4–6 sentences covering the launch decision, ranking stability and sensor maintenance priorities.
  1. Build bayesian_ab_report. For each group (control, treatment), draw n_draws Beta conversion samples, then 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) on ln⁡(revenue)\ln(\text{revenue}) of buyers. Combine via RPU=p⋅exp⁡(μ+σ2/2)\text{RPU} = p \cdot \exp(\mu + \sigma^2 / 2) and compute win probabilities, 95% credible intervals and expected losses.

  2. Build empirical_bayes_ratings. Aggregate n and pos = (rating >= 4).sum() per (product_id, product). Fit (α0,β0)(\alpha_0, \beta_0) from the mean and sample variance (ddof=1) of raw_rate, then compute posterior means and stats.beta.ppf 95% credible intervals.

  3. Build sensor_drift_audit. Parse timestamp, split on cutoff, bin each metric on a fixed grid (temperature_c, humidity_pct, vibration_mm_s), add 1e-6 Laplace smoothing, and compute stats.entropy(q, p) for KL and jensenshannon(p, q) ** 2 for JS divergence.

  4. Print the report. Format the A/B summary, top-5 empirical-Bayes product rankings and full 12-row sensor drift table within 100 characters per line.

  5. Plot the three-panel dashboard. Render the RPU posterior lift, empirical-Bayes credible intervals and sensor JS divergence chart side by side with clear axis labels and reference lines.

  6. Verify invariants and write findings. Run assert checks on probabilities, bounds and alerts, then write a concise recommendation for stakeholders.

A starter skeleton to guide your implementation:

bayesian_toolkit.py (starter)
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats
from scipy.spatial.distance import jensenshannon
def bayesian_ab_report(
ab_df: pd.DataFrame, n_draws: int = 40_000, seed: int = 42
) -> dict:
# TODO: draw Beta conversion posteriors and Log-normal buyer AOV posteriors
# TODO: return win probabilities, 95% CrIs, expected losses and rpu_diff
...
def empirical_bayes_ratings(
reviews_df: pd.DataFrame,
) -> tuple[pd.DataFrame, float, float]:
# TODO: aggregate positive rates, fit MoM Beta(a0, b0), compute posterior mean + 95% CrI
...
def sensor_drift_audit(
sensors_df: pd.DataFrame, cutoff: str = "2024-05-08", js_thresh: float = 0.05
) -> pd.DataFrame:
# TODO: split Week 1 vs Week 2, compute smoothed KL and JS divergence per sensor/metric
...
# TODO: load CSVs, run all three functions, print report, plot 3-panel figure and assert
Criterion Points Full points when
Bayesian A/B test 4 Correct Beta conversion + Log-normal RPU posteriors, win probabilities, 95% CrIs and expected losses
Empirical Bayes ratings 3 Accurate MoM Beta prior, posterior means, 95% credible intervals and rank-change tracking
Sensor drift audit 3 Shared grids with smoothing, accurate KL and JS divergence across all 12 sensor–metric pairs, threshold alerting
Diagnostic visualization 2 Clear three-panel figure with uncertainty bands, zero/threshold reference lines and readable labels
Output formatting & code clarity 2 Modular typed functions, lines ≤ 100 chars, reproducible seed, zero warnings
Self-checks & findings 2 Meaningful assert invariants plus a concise 4–6 sentence executive summary
Total 16 13 or more: you are ready for module 49
  1. Prior sensitivity check: re-run bayesian_ab_report with a skeptical prior Beta(10,90)\text{Beta}(10, 90) and compare how much P(treatment>control)P(\text{treatment} > \text{control}) changes.
  2. Exact HPD intervals: replace the equal-tailed credible intervals in empirical_bayes_ratings with shortest 95% HPD intervals from Monte Carlo draws.
  3. Daily drift timeline: extend sensor_drift_audit to compute a rolling 24-hour JS divergence curve against May 1–3 so maintenance teams see the exact hour an anomaly begins.
  4. CLI export: wrap the script with argparse so running python bayesian_toolkit.py --js-thresh 0.04 writes the tables to output/toolkit_report.md and saves the figure to output/toolkit_dashboard.png.
Reference solution
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats
from scipy.spatial.distance import jensenshannon
def bayesian_ab_report(
ab_df: pd.DataFrame, n_draws: int = 40_000, seed: int = 42
) -> dict:
rng = np.random.default_rng(seed)
conv_draws, rpu_draws = {}, {}
for grp in ["control", "treatment"]:
sub = ab_df[ab_df["group"] == grp]
k, n = int(sub["converted"].sum()), len(sub)
p_s = stats.beta(1 + k, 1 + n - k).rvs(n_draws, random_state=rng)
y_log = np.log(sub.loc[sub["converted"] == 1, "revenue"].to_numpy())
nb = len(y_log)
mu_b = float(y_log.mean())
s2_b = float(y_log.var(ddof=1))
sig2_s = (nb - 1) * s2_b / rng.chisquare(df=nb - 1, size=n_draws)
mu_s = rng.normal(mu_b, np.sqrt(sig2_s / nb))
aov_s = np.exp(mu_s + 0.5 * sig2_s)
conv_draws[grp] = p_s
rpu_draws[grp] = p_s * aov_s
conv_diff = conv_draws["treatment"] - conv_draws["control"]
rpu_diff = rpu_draws["treatment"] - rpu_draws["control"]
return {
"p_conv_win": float((conv_diff > 0).mean()),
"conv_cri": np.quantile(conv_diff, [0.025, 0.975]),
"conv_loss_t": float(np.maximum(-conv_diff, 0.0).mean()),
"p_rpu_win": float((rpu_diff > 0).mean()),
"rpu_cri": np.quantile(rpu_diff, [0.025, 0.975]),
"rpu_loss_t": float(np.maximum(-rpu_diff, 0.0).mean()),
"rpu_diff": rpu_diff,
}
def empirical_bayes_ratings(
reviews_df: pd.DataFrame,
) -> tuple[pd.DataFrame, float, float]:
agg = (
reviews_df.groupby(["product_id", "product"])
.agg(n=("rating", "count"), pos=("rating", lambda s: int((s >= 4).sum())))
.reset_index()
)
agg["raw_rate"] = agg["pos"] / agg["n"]
m = float(agg["raw_rate"].mean())
v = float(agg["raw_rate"].var(ddof=1))
strength = m * (1 - m) / v - 1
a0, b0 = m * strength, (1 - m) * strength
a_post = agg["pos"] + a0
b_post = (agg["n"] - agg["pos"]) + b0
agg["eb_rate"] = a_post / (a_post + b_post)
agg["cri_lo"] = stats.beta.ppf(0.025, a_post, b_post)
agg["cri_hi"] = stats.beta.ppf(0.975, a_post, b_post)
agg["raw_rank"] = agg["raw_rate"].rank(ascending=False).astype(int)
agg["eb_rank"] = agg["eb_rate"].rank(ascending=False).astype(int)
ranked = agg.sort_values("eb_rate", ascending=False).reset_index(drop=True)
return ranked, a0, b0
def sensor_drift_audit(
sensors_df: pd.DataFrame, cutoff: str = "2024-05-08", js_thresh: float = 0.05
) -> pd.DataFrame:
df = sensors_df.copy()
df["ts"] = pd.to_datetime(df["timestamp"])
w1 = df[df["ts"] < cutoff]
w2 = df[df["ts"] >= cutoff]
metric_bins = {
"temperature_c": np.linspace(18.0, 45.0, 28),
"humidity_pct": np.linspace(42.0, 64.0, 23),
"vibration_mm_s": np.linspace(1.0, 20.0, 20),
}
rows = []
for sid in sorted(df["sensor_id"].unique()):
for metric, bins in metric_bins.items():
b_vals = w1.loc[w1["sensor_id"] == sid, metric].dropna()
c_vals = w2.loc[w2["sensor_id"] == sid, metric].dropna()
p, _ = np.histogram(b_vals, bins=bins)
q, _ = np.histogram(c_vals, bins=bins)
p = (p + 1e-6) / (p.sum() + 1e-6 * len(p))
q = (q + 1e-6) / (q.sum() + 1e-6 * len(q))
kl = float(stats.entropy(q, p))
js = float(jensenshannon(p, q) ** 2)
rows.append(
{
"sensor": sid,
"metric": metric,
"kl_div": kl,
"js_div": js,
"alert": js > js_thresh,
}
)
return pd.DataFrame(rows)
ab = pd.read_csv("data/ab_test.csv")
reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)
sensors = pd.read_csv("data/sensors.csv")
ab_res = bayesian_ab_report(ab)
print("=== 1. Bayesian A/B Test (ab_test.csv) ===")
print(
f"Conversion: P(T>C)={ab_res['p_conv_win']:.4f}"
f" | 95% CrI=[{ab_res['conv_cri'][0]:+.4f}, {ab_res['conv_cri'][1]:+.4f}]"
f" | loss(T)={ab_res['conv_loss_t']:.6f}"
)
print(
f"Rev / user: P(T>C)={ab_res['p_rpu_win']:.4f}"
f" | 95% CrI=[{ab_res['rpu_cri'][0]:+.3f}, {ab_res['rpu_cri'][1]:+.3f}]"
f" | loss(T)=USD {ab_res['rpu_loss_t']:.4f}"
)
eb_df, a0, b0 = empirical_bayes_ratings(reviews)
print(f"\n=== 2. Empirical Bayes Ratings (prior Beta({a0:.2f}, {b0:.2f})) ===")
show_cols = [
"product_id",
"product",
"n",
"raw_rate",
"eb_rate",
"cri_lo",
"cri_hi",
"raw_rank",
"eb_rank",
]
print(eb_df[show_cols].head(5).round(3).to_string(index=False))
drift_df = sensor_drift_audit(sensors)
print("\n=== 3. Sensor Drift Audit (Week 1 vs. Week 2, alert if JS > 0.05) ===")
print(drift_df.round(4).to_string(index=False))
alerts = drift_df[drift_df["alert"]]
flagged = list(zip(alerts["sensor"], alerts["metric"], strict=True))
print(f"\nFlagged alerts: {len(alerts)} -> {flagged}")
# Three-panel diagnostic dashboard
fig, axes = plt.subplots(1, 3, figsize=(12.5, 3.8))
# Panel 1: Bayesian RPU lift posterior
axes[0].hist(ab_res["rpu_diff"], bins=45, density=True, alpha=0.7)
axes[0].axvline(0.0, color="crimson", ls="--", lw=1.5, label="Break-even (0)")
axes[0].set_title(f"RPU lift posterior (P>0: {ab_res['p_rpu_win']:.1%})")
axes[0].set_xlabel("Treatment - Control (USD/user)")
axes[0].legend()
axes[0].grid(alpha=0.25)
# Panel 2: Top 5 and bottom 3 products with 95% CrI
show_prod = pd.concat([eb_df.head(5), eb_df.tail(3)]).iloc[::-1]
y_pos = np.arange(len(show_prod))
err_lo = show_prod["eb_rate"] - show_prod["cri_lo"]
err_hi = show_prod["cri_hi"] - show_prod["eb_rate"]
axes[1].errorbar(
show_prod["eb_rate"],
y_pos,
xerr=[err_lo, err_hi],
fmt="o",
capsize=3,
label="EB 95% CrI",
)
axes[1].scatter(show_prod["raw_rate"], y_pos, marker="x", color="crimson", label="Raw")
axes[1].axvline(a0 / (a0 + b0), color="gray", ls=":", lw=1.2, label="Prior mean")
axes[1].set_yticks(y_pos)
axes[1].set_yticklabels(show_prod["product_id"])
axes[1].set_title("Empirical Bayes ratings (top 5 & bottom 3)")
axes[1].set_xlabel("Positive review rate")
axes[1].legend(fontsize=8)
axes[1].grid(alpha=0.25)
# Panel 3: Sensor JS divergence grouped bar chart
piv = drift_df.pivot(index="sensor", columns="metric", values="js_div")
x_idx = np.arange(len(piv))
bar_w = 0.25
for idx, col in enumerate(["temperature_c", "humidity_pct", "vibration_mm_s"]):
axes[2].bar(x_idx + (idx - 1) * bar_w, piv[col], width=bar_w, label=col)
axes[2].axhline(0.05, color="crimson", ls="--", lw=1.4, label="Alert (0.05)")
axes[2].set_xticks(x_idx)
axes[2].set_xticklabels(piv.index)
axes[2].set_title("Sensor drift (JS divergence)")
axes[2].set_ylabel("JS divergence (nats)")
axes[2].legend(fontsize=8)
axes[2].grid(alpha=0.25)
fig.tight_layout()
plt.show()
# Invariant self-checks
assert ab_res["p_conv_win"] > 0.99
assert ab_res["p_rpu_win"] > 0.90
assert (eb_df["cri_lo"] < eb_df["eb_rate"]).all()
assert (eb_df["eb_rate"] < eb_df["cri_hi"]).all()
assert eb_df.loc[0, "product_id"] == "P021"
assert ((drift_df["js_div"] >= 0.0) & (drift_df["js_div"] <= np.log(2))).all()
assert set(flagged) == {
("S3", "temperature_c"),
("S3", "humidity_pct"),
("S4", "vibration_mm_s"),
}
Output
=== 1. Bayesian A/B Test (ab_test.csv) ===
Conversion: P(T>C)=0.9933 | 95% CrI=[+0.0032, +0.0276] | loss(T)=0.000014
Rev / user: P(T>C)=0.9170 | 95% CrI=[-0.191, +1.100] | loss(T)=USD 0.0125
=== 2. Empirical Bayes Ratings (prior Beta(28.85, 13.00)) ===
product_id product n raw_rate eb_rate cri_lo cri_hi raw_rank eb_rank
P021 Harbor Lane Mysteries 115 0.809 0.777 0.709 0.838 2 1
P018 Adjustable Dumbbells 53 0.830 0.768 0.679 0.847 1 2
P008 Chef's Knife Set 117 0.769 0.748 0.678 0.812 3 3
P010 Cotton Bed Sheet Set 166 0.741 0.731 0.668 0.789 5 4
P029 Electric Toothbrush 72 0.750 0.728 0.643 0.805 4 5
=== 3. Sensor Drift Audit (Week 1 vs. Week 2, alert if JS > 0.05) ===
sensor metric kl_div js_div alert
S1 temperature_c 0.0681 0.0051 False
S1 humidity_pct 0.0464 0.0126 False
S1 vibration_mm_s 0.0071 0.0019 False
S2 temperature_c 0.0983 0.0089 False
S2 humidity_pct 0.3454 0.0177 False
S2 vibration_mm_s 0.0211 0.0028 False
S3 temperature_c 2.4094 0.2179 True
S3 humidity_pct 1.9542 0.1753 True
S3 vibration_mm_s 0.0579 0.0026 False
S4 temperature_c 0.0968 0.0074 False
S4 humidity_pct 0.2563 0.0216 False
S4 vibration_mm_s 5.2891 0.1512 True
Flagged alerts: 3 -> [('S3', 'temperature_c'), ('S3', 'humidity_pct'), ('S4', 'vibration_mm_s')]
Three-panel dashboard: left shows the RPU lift histogram mostly above zero; middle shows empirical-Bayes product rates with 95% credible intervals pulled toward the catalog mean; right shows sensor JS divergence bars with S3 temperature/humidity and S4 vibration rising far above the 0.05 alert line.
Bayesian Experimentation and Drift Toolkit diagnostic dashboard across ab_test.csv, reviews.csv and sensors.csv.

Executive findings:

The checkout redesign is a clear ship: conversion outperforms control with 99.3% probability (loss = 0.000014), and even after accounting for noisy buyer order values, revenue per user beats control with 91.7% probability and an expected downside risk of only USD 0.0125 per user. On the product catalog, empirical Bayes shrinkage with the catalog prior Beta(28.85,13.00)\text{Beta}(28.85, 13.00) stabilizes rankings—promoting P021 (Harbor Lane Mysteries, 115 reviews) above smaller-sample P018 (Adjustable Dumbbells, 53 reviews) and P010 (Cotton Bed Sheet Set, 166 reviews) above P029 (Electric Toothbrush, 72 reviews). On the sensor fleet, S1 and S2 remain stable across all metrics (JS < 0.02), whereas three drift alerts fire cleanly: S3 shows severe calibration drift in temperature (JS = 0.2179) and its coupled humidity channel (JS = 0.1753), while S4 shows sharp vibration wear (JS = 0.1512). Maintenance should prioritize recalibrating S3 and inspecting S4 bearings immediately.