Skip to content

48. Probability, Bayesian statistics and information theory

Module 29 gave you the classical statistics toolkit: summary numbers, standard distributions, confidence intervals and hypothesis tests. Those tools answer “could chance alone explain this pattern?” This module goes deeper into the probabilistic engine behind modern data science and machine learning: modeling uncertainty with rich distribution families, updating beliefs with Bayes’ theorem, connecting prior distributions directly to L2 and L1 regularization, sampling complex posteriors with MCMC, and measuring information and distribution drift with entropy and KL divergence.

These ideas show up everywhere in production ML. Bayesian A/B testing tells a product manager the exact probability that a checkout redesign wins and the expected cost of a wrong launch. Empirical Bayes keeps a brand-new product with two five-star reviews from outranking a bestseller with 150 reviews. Cross-entropy loss, KL divergence and mutual information power neural network training, feature selection and live drift monitors.

  • Apply probability axioms, combinatorics, the law of total probability, and joint, marginal and conditional distributions (including covariance matrices and multivariate normals).
  • Choose and parameterize key distributions in scipy.stats beyond Normal and Binomial: Exponential, Gamma, Beta, Log-normal, Negative Binomial and Multinomial.
  • Contrast frequentist and Bayesian inference, perform sequential conjugate updating (Beta–Binomial and Gamma–Poisson), and build credible intervals and posterior predictive checks.
  • Show mathematically and numerically why Maximum A Posteriori (MAP) estimation with a Gaussian prior equals Ridge regression and with a Laplace prior equals Lasso regression.
  • Implement a Metropolis–Hastings Markov Chain Monte Carlo (MCMC) sampler from scratch in NumPy, tune its proposal scale and inspect burn-in, acceptance rate and trace diagnostics.
  • Compute Shannon entropy, cross-entropy, Kullback–Leibler (KL) divergence, Jensen–Shannon (JS) divergence and mutual information to measure model loss, non-linear feature dependence and data drift.

All code on this page runs in one session. Start by importing the libraries, configuring pandas display width and checking package versions:

import math
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy
import statsmodels.api as sm
from scipy import optimize, stats
from scipy.spatial.distance import jensenshannon
from sklearn.feature_selection import mutual_info_classif
from sklearn.linear_model import Ridge
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
print(f"numpy {np.__version__} | scipy {scipy.__version__}")
Output
numpy 2.5.4 | scipy 1.18.1

Probability axioms, combinatorics and the law of total probability

Section titled “Probability axioms, combinatorics and the law of total probability”

Every probabilistic model rests on three Kolmogorov axioms over a sample space Ω\Omega (the set of all possible outcomes):

  1. Non-negativity: P(A)≥0P(A) \ge 0 for every event AA.
  2. Normalization: P(Ω)=1P(\Omega) = 1 (something in the sample space must happen).
  3. Additivity: if events AA and BB are mutually exclusive (A∩B=∅A \cap B = \emptyset), then P(A∪B)=P(A)+P(B)P(A \cup B) = P(A) + P(B).

From those three rules follow the complement rule P(Ac)=1−P(A)P(A^c) = 1 - P(A), the inclusion–exclusion rule P(A∪B)=P(A)+P(B)−P(A∩B)P(A \cup B) = P(A) + P(B) - P(A \cap B), and conditional probability:

P(A∣B)=P(A∩B)P(B)(P(B)>0)P(A \mid B) = \frac{P(A \cap B)}{P(B)} \qquad (P(B) > 0)

When events B1,B2,…,BkB_1, B_2, \dots, B_k partition the sample space (they do not overlap and together cover everything), the law of total probability expresses P(A)P(A) as a weighted average of conditional probabilities:

P(A)=∑i=1kP(A∣Bi) P(Bi)P(A) = \sum_{i=1}^{k} P(A \mid B_i)\, P(B_i)

Reversing the conditioning gives Bayes’ theorem:

P(Bj∣A)=P(A∣Bj) P(Bj)∑i=1kP(A∣Bi) P(Bi)P(B_j \mid A) = \frac{P(A \mid B_j)\, P(B_j)}{\sum_{i=1}^{k} P(A \mid B_i)\, P(B_i)}

In discrete probability you also count combinations and permutations using combinatorics: the number of ways to choose kk unordered items from nn is the binomial coefficient (nk)=n!k!(n−k)!\binom{n}{k} = \frac{n!}{k!(n-k)!} (math.comb(n, k)), while ordered arrangements use math.perm(n, k). Verify the law of total probability and Bayes’ theorem directly on data/customers.csv:

customers = pd.read_csv("data/customers.csv")
# Law of total probability: P(churn) = sum_c P(churn | contract=c) * P(contract=c)
p_churn = customers["churned"].mean()
by_contract = customers.groupby("contract")["churned"].agg(["count", "mean"])
by_contract["share"] = by_contract["count"] / len(customers)
total_prob = (by_contract["share"] * by_contract["mean"]).sum()
# Bayes' theorem: P(churn | echeck) from P(echeck | churn), P(churn), P(echeck)
is_echeck = customers["payment_method"] == "electronic_check"
p_echeck = is_echeck.mean()
p_echeck_given_churn = is_echeck[customers["churned"] == 1].mean()
p_churn_given_echeck_bayes = p_echeck_given_churn * p_churn / p_echeck
p_churn_given_echeck_direct = customers.loc[is_echeck, "churned"].mean()
print(f"P(churn) direct: {p_churn:.4f} | via total probability: {total_prob:.4f}")
print(
f"P(churn | echeck) Bayes: {p_churn_given_echeck_bayes:.4f}"
f" | direct: {p_churn_given_echeck_direct:.4f}"
)
print(
f"5-card hands from 52: {math.comb(52, 5):,}"
f" | 3-stage orders from 8: {math.perm(8, 3)}"
)
Output
P(churn) direct: 0.1926 | via total probability: 0.1926
P(churn | echeck) Bayes: 0.2476 | direct: 0.2476
5-card hands from 52: 2,598,960 | 3-stage orders from 8: 336

The law of total probability matches the global churn rate to full precision, and Bayes’ theorem recovers P(churn∣electronic_check)=0.2476P(\text{churn} \mid \text{electronic\_check}) = 0.2476 from the reverse conditional probability P(electronic_check∣churn)P(\text{electronic\_check} \mid \text{churn}) and the base rates.

Joint, marginal and conditional distributions; independence and covariance

Section titled “Joint, marginal and conditional distributions; independence and covariance”

Real datasets have many variables at once. A joint distribution P(X=x,Y=y)P(X = x, Y = y) assigns probability to pairs of outcomes. Summing (or integrating) over one variable recovers the marginal distribution: P(X=x)=∑yP(X=x,Y=y)P(X = x) = \sum_y P(X = x, Y = y). Fixing one variable and renormalizing gives the conditional distribution: P(Y=y∣X=x)=P(X=x,Y=y)/P(X=x)P(Y = y \mid X = x) = P(X = x, Y = y) / P(X = x).

Two variables are independent (X⊥YX \perp Y) when knowing one tells you nothing about the other: P(X=x,Y=y)=P(X=x) P(Y=y)P(X = x, Y = y) = P(X = x)\, P(Y = y) for every pair (x,y)(x, y). Check joint, marginal and conditional tables on plan and contract in customers.csv:

joint = pd.crosstab(customers["plan"], customers["contract"], normalize="all")
marg_plan = joint.sum(axis=1)
marg_contract = joint.sum(axis=0)
expected_indep = np.outer(marg_plan, marg_contract)
max_gap = np.abs(joint.to_numpy() - expected_indep).max()
cond_contract_given_plan = pd.crosstab(
customers["plan"], customers["contract"], normalize="index"
)
print("Joint P(plan, contract):")
print(joint.round(3))
print("\nConditional P(contract | plan):")
print(cond_contract_given_plan.round(3))
print(f"\nMax |P(X,Y) - P(X)P(Y)|: {max_gap:.4f}")
Output
Joint P(plan, contract):
contract month-to-month one-year two-year
plan
basic 0.234 0.094 0.078
premium 0.106 0.050 0.042
standard 0.216 0.102 0.078
Conditional P(contract | plan):
contract month-to-month one-year two-year
plan
basic 0.578 0.231 0.191
premium 0.535 0.251 0.214
standard 0.546 0.257 0.197
Max |P(X,Y) - P(X)P(Y)|: 0.0086

The rows of P(contract∣plan)P(\text{contract} \mid \text{plan}) are nearly identical across basic, premium and standard, and the largest gap between P(X,Y)P(X, Y) and P(X)P(Y)P(X)P(Y) is only 0.0086. In this customer base, plan tier and contract length are practically independent.

For continuous random vectors X=(X1,…,Xd)⊤\mathbf{X} = (X_1, \dots, X_d)^\top, linear co-movement is captured by the covariance matrix Σ\Sigma, where Σij=Cov(Xi,Xj)=E[(Xi−μi)(Xj−μj)]\Sigma_{ij} = \text{Cov}(X_i, X_j) = \mathbb{E}[(X_i - \mu_i)(X_j - \mu_j)]. The diagonal entries are variances σi2\sigma_i^2, and Σ\Sigma is symmetric positive semi-definite. The multivariate normal distribution N(μ,Σ)\mathcal{N}(\boldsymbol{\mu}, \Sigma) is completely specified by its mean vector and covariance matrix:

houses = pd.read_csv("data/houses.csv")
house_cols = ["sqft", "bedrooms", "bathrooms"]
X_h = houses[house_cols].to_numpy(dtype=float)
mu_h = X_h.mean(axis=0)
cov_h = np.cov(X_h, rowvar=False, ddof=1)
corr_h = np.corrcoef(X_h, rowvar=False)
mvn = stats.multivariate_normal(mean=mu_h, cov=cov_h)
print("Mean vector:", np.round(mu_h, 2))
print("Correlation matrix:\n", np.round(corr_h, 3))
print(f"Log-density at mean: {mvn.logpdf(mu_h):.3f}")
print(f"Log-density at large house (3500, 5, 4): {mvn.logpdf([3500, 5, 4]):.3f}")
Output
Mean vector: [1856.64 3.02 2.62]
Correlation matrix:
[[1. 0.851 0.845]
[0.851 1. 0.896]
[0.845 0.896 1. ]]
Log-density at mean: -7.947
Log-density at large house (3500, 5, 4): -11.002

np.cov(X_h, rowvar=False) treats columns as variables and rows as observations. Notice that mvn.logpdf returns a log-density: working in log-space prevents floating-point underflow when multiplying many probabilities or evaluating high-dimensional Gaussians.

Distribution families beyond Normal and Binomial

Section titled “Distribution families beyond Normal and Binomial”

The Normal and Binomial distributions cover only a slice of data science problems. Positive waiting times, probabilities constrained to (0,1)(0, 1), skewed order amounts, overdispersed counts and multi-class categories each have a natural parametric family:

Distribution Support Typical use case scipy.stats call Mean / Variance
Exponential(λ\lambda) x≥0x \ge 0 Wait time between Poisson events (memoryless) stats.expon(scale=1/lam) 1/λ1/\lambda, 1/λ21/\lambda^2
Gamma(α,β\alpha, \beta) x>0x > 0 Wait time for α\alpha events; prior for rates stats.gamma(a=alpha, scale=1/beta) α/β\alpha/\beta, α/β2\alpha/\beta^2
Beta(α,β\alpha, \beta) x∈(0,1)x \in (0, 1) Probability / conversion rate; prior for pp stats.beta(alpha, beta) αα+β\frac{\alpha}{\alpha+\beta}, αβ(α+β)2(α+β+1)\frac{\alpha\beta}{(\alpha+\beta)^2(\alpha+\beta+1)}
Log-normal(μ,σ\mu, \sigma) x>0x > 0 Multiplicative quantities: revenue, prices stats.lognorm(s=sigma, scale=np.exp(mu)) eμ+σ2/2e^{\mu+\sigma^2/2}, (eσ2−1)e2μ+σ2(e^{\sigma^2}-1)e^{2\mu+\sigma^2}
Negative Binomial(r,pr, p) k∈{0,1,… }k \in \{0, 1, \dots\} Overdispersed counts (Var >> Mean) stats.nbinom(n=r, p=p) r(1−p)/pr(1-p)/p, r(1−p)/p2r(1-p)/p^2
Multinomial(n,pn, \mathbf{p}) ∑ki=n\sum k_i = n Category counts across KK classes stats.multinomial(n, p) npinp_i, npi(1−pi)np_i(1-p_i)

Pay close attention to scipy.stats parameter conventions! For Exponential and Gamma, SciPy uses scale = 1 / rate rather than the rate λ\lambda or β\beta. For Log-normal, s is the standard deviation σ\sigma of ln⁡X\ln X and scale is exp⁡(μ)\exp(\mu), where μ\mu is the mean of ln⁡X\ln X. Verify all six families in code:

expon_d = stats.expon(scale=1 / 0.25) # rate lambda = 0.25 events/min
gamma_d = stats.gamma(a=4, scale=1 / 0.5) # shape=4, rate=0.5 -> mean 8
beta_d = stats.beta(a=12, b=88) # 12% conversion rate
lognorm_d = stats.lognorm(s=0.6, scale=np.exp(3.5)) # log(X) ~ N(3.5, 0.6^2)
nbinom_d = stats.nbinom(n=5, p=0.25) # mean = 5 * 0.75 / 0.25 = 15
multinom_d = stats.multinomial(n=10, p=[0.5, 0.3, 0.2])
print(f"Expon(lam=0.25): mean={expon_d.mean():.2f}, P(X>4)={expon_d.sf(4):.4f}")
print(f"Gamma(a=4, b=0.5): mean={gamma_d.mean():.2f}, var={gamma_d.var():.2f}")
print(f"Beta(12, 88): mean={beta_d.mean():.3f}, std={beta_d.std():.4f}")
print(
f"LogNorm(3.5, 0.6): median={lognorm_d.median():.2f},"
f" mean={lognorm_d.mean():.2f}"
)
print(f"NegBin(r=5, p=0.25): mean={nbinom_d.mean():.2f}, var={nbinom_d.var():.2f}")
print(f"Multinom PMF [5,3,2]: {multinom_d.pmf([5, 3, 2]):.4f}")
Output
Expon(lam=0.25): mean=4.00, P(X>4)=0.3679
Gamma(a=4, b=0.5): mean=8.00, var=16.00
Beta(12, 88): mean=0.120, std=0.0323
LogNorm(3.5, 0.6): median=33.12, mean=39.65
NegBin(r=5, p=0.25): mean=15.00, var=60.00
Multinom PMF [5,3,2]: 0.0850

Notice two handy facts in that output: for LogNorm(3.5, 0.6), the median is e3.5=33.12e^{3.5} = 33.12 while the mean is pulled higher to 39.6539.65 by right skew; and for NegBin(r=5, p=0.25), the variance (60.00) is four times the mean (15.00), making it the workhorse distribution whenever count data has heavier spread than a Poisson model allows.

Frequentist vs. Bayesian thinking: parameters as random variables

Section titled “Frequentist vs. Bayesian thinking: parameters as random variables”

Classical (frequentist) statistics treats an unknown parameter θ\theta (such as a true conversion rate) as a fixed, unknown constant. Randomness lives only in the data you happen to sample, so intervals and p-values describe how a procedure behaves across hypothetical repeated experiments.

Bayesian statistics treats the unknown parameter θ\theta itself as a random variable with a probability distribution representing your state of knowledge. You start with a prior p(θ)p(\theta), observe data DD with likelihood p(D∣θ)p(D \mid \theta), and apply Bayes’ theorem to obtain the posterior p(θ∣D)p(\theta \mid D):

p(θ∣D)=p(D∣θ) p(θ)p(D)∝p(D∣θ) p(θ)p(\theta \mid D) = \frac{p(D \mid \theta)\, p(\theta)}{p(D)} \propto p(D \mid \theta)\, p(\theta)

The denominator p(D)=∫p(D∣θ) p(θ) dθp(D) = \int p(D \mid \theta)\, p(\theta)\, d\theta is the marginal likelihood (also called evidence). It is a normalizing constant that ensures the posterior integrates to 1.

flowchart LR
    Prior["Prior p(theta)"] --> Update["Bayes update: p(D | theta) * p(theta)"]
    Data["Observed data D"] --> Update
    Update --> Post["Posterior p(theta | D)"]
    Post --> Next["Becomes next prior"]
    Post --> Pred["Posterior predictive p(D_new | D)"]
Dimension Frequentist view Bayesian view
Status of θ\theta Fixed unknown constant Random variable with a distribution
Meaning of probability Long-run relative frequency Degree of calibrated belief
Prior knowledge Not part of the formula Explicitly encoded in p(θ)p(\theta)
Interval output Confidence interval (procedure coverage) Credible interval (direct P(a≤θ≤b∣D)P(a \le \theta \le b \mid D))
Direct decision metric p-value (tail area assuming H0H_0) P(θB>θA∣D)P(\theta_B > \theta_A \mid D) and expected loss

Neither school replaces the other. Frequentist tools need no prior and are fast defaults for well-powered experiments. Bayesian tools shine when sample sizes are small, when you update estimates sequentially as data arrives, when you share strength across groups (hierarchical / empirical Bayes), or when stakeholders want direct probability statements about business risk.

Computing the normalizing integral p(D)=∫p(D∣θ) p(θ) dθp(D) = \int p(D \mid \theta)\, p(\theta)\, d\theta can be hard in general. A conjugate prior is a prior family whose posterior after observing data from a matching likelihood stays in the exact same distribution family—reducing Bayes’ theorem to simple arithmetic on the parameters:

Likelihood Parameter Conjugate prior Posterior parameters after data
Binomial(n,pn, p) probability pp Beta(α,β)\text{Beta}(\alpha, \beta) Beta(α+k,  β+n−k)\text{Beta}(\alpha + k,\; \beta + n - k)
Poisson(λ\lambda) rate λ\lambda Gamma(α,β)\text{Gamma}(\alpha, \beta) (rate β\beta) Gamma(α+∑xi,  β+n)\text{Gamma}(\alpha + \sum x_i,\; \beta + n)
Normal(μ,σ2\mu, \sigma^2 known) mean μ\mu N(μ0,τ02)\mathcal{N}(\mu_0, \tau_0^2) N(μn,τn2)\mathcal{N}(\mu_n, \tau_n^2) (precision-weighted average)
Multinomial(n,pn, \mathbf{p}) probabilities p\mathbf{p} Dirichlet(α)\text{Dirichlet}(\boldsymbol{\alpha}) Dirichlet(α+k)\text{Dirichlet}(\boldsymbol{\alpha} + \mathbf{k})

In a Beta–Binomial model, α\alpha and β\beta act as pseudo-counts: starting with Beta(1,1)\text{Beta}(1, 1) (uniform over [0,1][0, 1]) and seeing kk conversions out of nn visitors simply adds kk to α\alpha and n−kn - k to β\beta. Better yet, sequential updating gives the exact same posterior whether you update one batch at a time or all at once! Watch how a Beta posterior sharpens around the true treatment conversion rate as visitors arrive in data/ab_test.csv:

ab = pd.read_csv("data/ab_test.csv")
treat = ab.loc[ab["group"] == "treatment", "converted"].to_numpy()
checkpoints = [0, 20, 200, 2000]
x_grid = np.linspace(0.0, 0.35, 400)
fig, ax = plt.subplots(figsize=(7.5, 4.0))
alpha, beta = 2.0, 18.0 # weakly informative prior centered at 10%
for n_obs in checkpoints:
k = int(treat[:n_obs].sum())
a_post, b_post = alpha + k, beta + (n_obs - k)
dist = stats.beta(a_post, b_post)
label = f"n={n_obs} (mean={dist.mean():.3f})"
ax.plot(x_grid, dist.pdf(x_grid), lw=2, label=label)
print(
f"n={n_obs:<4} k={k:<3} -> Beta({a_post:.0f}, {b_post:.0f})"
f" mean={dist.mean():.4f}"
)
ax.set_title("Sequential Beta-Binomial updating on treatment conversions")
ax.set_xlabel("Conversion rate p")
ax.set_ylabel("Posterior density")
ax.legend()
ax.grid(alpha=0.25)
fig.tight_layout()
plt.show()
Output
n=0 k=0 -> Beta(2, 18) mean=0.1000
n=20 k=1 -> Beta(3, 37) mean=0.0750
n=200 k=27 -> Beta(29, 191) mean=0.1318
n=2000 k=247 -> Beta(249, 1771) mean=0.1233
Four overlaid Beta posterior curves showing a wide prior at n=0 progressively narrowing and peaking near 0.123 by n=2000.
Sequential Beta-Binomial updating: as observations accumulate, the posterior narrows and the prior influence fades.

With n=20n = 20 visitors the prior (α+β=20\alpha + \beta = 20 pseudo-observations) still pulls the estimate strongly toward 10%. By n=2,000n = 2{,}000, the data carries 100× the weight of the prior, so different reasonable priors converge to nearly the same posterior.

Credible intervals vs. confidence intervals, and posterior predictive checks

Section titled “Credible intervals vs. confidence intervals, and posterior predictive checks”

A 95% credible interval [L,U][L, U] satisfies P(L≤θ≤U∣D)=0.95P(L \le \theta \le U \mid D) = 0.95. Unlike a frequentist confidence interval (which only says the method covers the fixed truth 95% of the time across repeated samples), a credible interval allows the direct interpretation people naturally want: given the model, prior and observed data, there is a 95% probability that θ\theta lies between LL and UU.

The simplest credible interval is the equal-tailed interval, taken from the 2.5th and 97.5th percentiles of the posterior (dist.ppf([0.025, 0.975])). For skewed posteriors, the highest posterior density (HPD) interval is the narrowest interval holding 95% of posterior mass.

To predict new data y~\tilde{y} rather than the parameter θ\theta, integrate over parameter uncertainty to form the posterior predictive distribution:

p(y~∣D)=∫p(y~∣θ) p(θ∣D) dθp(\tilde{y} \mid D) = \int p(\tilde{y} \mid \theta)\, p(\theta \mid D)\, d\theta

In code, sampling from the posterior predictive takes two lines: draw θ(s)\theta^{(s)} from the posterior, then draw y~(s)\tilde{y}^{(s)} from the likelihood given θ(s)\theta^{(s)}. This propagates both parameter uncertainty and sampling noise into future forecasts:

rng = np.random.default_rng(42)
# Suppose we observed 18 conversions in 150 trials with a Beta(1, 1) prior
post_p = stats.beta(1 + 18, 1 + 150 - 18)
cri_95 = post_p.ppf([0.025, 0.975])
# Posterior predictive: conversions expected in the NEXT 500 visitors
p_draws = post_p.rvs(size=20_000, random_state=rng)
y_new_pp = rng.binomial(n=500, p=p_draws)
# Plug-in prediction ignoring parameter uncertainty (fixing p = MLE = 18/150)
y_new_plugin = rng.binomial(n=500, p=18 / 150, size=20_000)
print(f"95% equal-tailed CrI for p: [{cri_95[0]:.4f}, {cri_95[1]:.4f}]")
print(
f"Next 500 buyers (posterior predictive): 95% range"
f" {np.quantile(y_new_pp, [0.025, 0.975]).round(1)}"
)
print(
f"Next 500 buyers (plug-in MLE only): 95% range"
f" {np.quantile(y_new_plugin, [0.025, 0.975]).round(1)}"
)
Output
95% equal-tailed CrI for p: [0.0775, 0.1818]
Next 500 buyers (posterior predictive): 95% range [35. 94.]
Next 500 buyers (plug-in MLE only): 95% range [46. 75.]

Look how much wider the posterior predictive range ([35, 94]) is than the plug-in MLE range ([46, 75]). Plugging in a single point estimate pretends you know pp exactly, which produces dangerously overconfident forecasts when nn is modest.

MLE vs. MAP estimation: Gaussian priors equal Ridge, Laplace priors equal Lasso

Section titled “MLE vs. MAP estimation: Gaussian priors equal Ridge, Laplace priors equal Lasso”

Often you want a single point estimate of parameters w\mathbf{w} rather than a full distribution. Two principles dominate ML:

  • Maximum Likelihood Estimation (MLE) picks w\mathbf{w} to maximize the data likelihood (equivalently, minimize negative log-likelihood): w^MLE=arg⁡max⁡wlog⁡p(D∣w)\hat{\mathbf{w}}_{\text{MLE}} = \arg\max_{\mathbf{w}} \log p(D \mid \mathbf{w})
  • Maximum A Posteriori (MAP) estimation picks the mode of the posterior, adding the log-prior to the log-likelihood: w^MAP=arg⁡max⁡w[log⁡p(D∣w)+log⁡p(w)]\hat{\mathbf{w}}_{\text{MAP}} = \arg\max_{\mathbf{w}} \bigl[\log p(D \mid \mathbf{w}) + \log p(\mathbf{w})\bigr]

Now plug in a linear regression model yi∼N(xi⊤w,σ2)y_i \sim \mathcal{N}(\mathbf{x}_i^\top \mathbf{w}, \sigma^2) with independent zero-mean priors on the weights:

  1. Gaussian prior wj∼N(0,τ2)w_j \sim \mathcal{N}(0, \tau^2): log⁡p(wj)=−wj22τ2+const\log p(w_j) = -\frac{w_j^2}{2\tau^2} + \text{const}. Maximizing the log-posterior is identical to minimizing: ∑i=1n(yi−xi⊤w)2+σ2τ2⏟λ∑j=1pwj2\sum_{i=1}^{n}(y_i - \mathbf{x}_i^\top \mathbf{w})^2 + \underbrace{\frac{\sigma^2}{\tau^2}}_{\lambda} \sum_{j=1}^{p} w_j^2 Gaussian MAP is literally Ridge (L2) regression with penalty λ=σ2/τ2\lambda = \sigma^2 / \tau^2! A tighter prior (smaller τ2\tau^2) means stronger regularization.
  2. Laplace prior wj∼Laplace(0,b)w_j \sim \text{Laplace}(0, b): log⁡p(wj)=−∣wj∣b+const\log p(w_j) = -\frac{|w_j|}{b} + \text{const}. Maximizing the log-posterior minimizes: ∑i=1n(yi−xi⊤w)2+2σ2b⏟λ∑j=1p∣wj∣\sum_{i=1}^{n}(y_i - \mathbf{x}_i^\top \mathbf{w})^2 + \underbrace{\frac{2\sigma^2}{b}}_{\lambda} \sum_{j=1}^{p} |w_j| Laplace MAP is literally Lasso (L1) regression! Because the Laplace density has a sharp spike at zero, its MAP estimate sets weak weights to exact zero.

Even for a single coin flip or conversion rate, MLE can overreact on tiny samples while MAP stabilizes the estimate. Suppose 3 out of 3 beta testers convert:

k_small, n_small = 3, 3
mle_p = k_small / n_small
# Beta(2, 10) prior -> posterior Beta(5, 10); mode = (a - 1) / (a + b - 2)
a_p, b_p = 2 + k_small, 10 + (n_small - k_small)
map_p = (a_p - 1) / (a_p + b_p - 2)
post_mean_p = a_p / (a_p + b_p)
print(
f"3/3 conversions -> MLE: {mle_p:.3f} | MAP: {map_p:.3f}"
f" | Post mean: {post_mean_p:.3f}"
)
Output
3/3 conversions -> MLE: 1.000 | MAP: 0.308 | Post mean: 0.333

MLE claims a 100% conversion rate forever after three lucky observations. MAP pulls the estimate back to 30.8%, reflecting the prior belief that extreme conversion rates are unlikely until stronger evidence arrives.

MCMC intuition: Metropolis–Hastings in NumPy

Section titled “MCMC intuition: Metropolis–Hastings in NumPy”

Conjugate priors exist only for simple models. The moment you fit a Bayesian logistic regression, a hierarchical model or a custom likelihood, the normalizing integral p(D)=∫p(D∣θ)p(θ) dθp(D) = \int p(D \mid \theta) p(\theta)\, d\theta has no closed form.

Markov Chain Monte Carlo (MCMC) solves this without ever computing p(D)p(D). Instead, it constructs a Markov chain whose stationary distribution is the posterior p(θ∣D)p(\theta \mid D) and collects samples from it. The foundational algorithm is Metropolis–Hastings:

  1. Start at an initial parameter vector θ(0)\theta^{(0)}.
  2. At step tt, propose a candidate θ∗=θ(t)+ϵ\theta^* = \theta^{(t)} + \epsilon, where ϵ∼N(0,s2I)\epsilon \sim \mathcal{N}(0, s^2 I) (a symmetric random-walk proposal).
  3. Compute the log-acceptance ratio (note how p(D)p(D) cancels completely!): log⁡r=[log⁡p(D∣θ∗)+log⁡p(θ∗)]−[log⁡p(D∣θ(t))+log⁡p(θ(t))]\log r = \bigl[\log p(D \mid \theta^*) + \log p(\theta^*)\bigr] - \bigl[\log p(D \mid \theta^{(t)}) + \log p(\theta^{(t)})\bigr]
  4. Draw u∼Uniform(0,1)u \sim \text{Uniform}(0, 1). If log⁡u<log⁡r\log u < \log r, accept θ(t+1)=θ∗\theta^{(t+1)} = \theta^*; otherwise stay at θ(t+1)=θ(t)\theta^{(t+1)} = \theta^{(t)}.

Three practical checks make or break an MCMC run:

  • Burn-in: discard the initial steps (say the first 20–25%) while the chain travels from its arbitrary starting point to the high-probability posterior region.
  • Acceptance rate: if the proposal step ss is too tiny, the chain accepts 95%+ of proposals but barely moves; if ss is too huge, it proposes far into the tails and gets stuck rejecting 95% of steps. Aim for roughly 25%–45% acceptance for low-dimensional random-walk MH.
  • Trace plot & autocorrelation: a healthy trace plot looks like a fuzzy horizontal caterpillar with no upward/downward drift and no long flat plateaus.

Verify a 15-line Metropolis–Hastings sampler on a known target—Beta(6,14)\text{Beta}(6, 14)—so you can check its samples against exact quantiles:

rng = np.random.default_rng(42)
target = stats.beta(6, 14)
n_steps, burn = 6_000, 1_500
chain = np.empty(n_steps)
cur = 0.5
cur_lp = target.logpdf(cur)
accepted = 0
for t in range(n_steps):
prop = cur + rng.normal(0.0, 0.18)
if 0.0 < prop < 1.0:
prop_lp = target.logpdf(prop)
if np.log(rng.random()) < prop_lp - cur_lp:
cur, cur_lp = prop, prop_lp
accepted += 1
chain[t] = cur
kept = chain[burn:]
print(f"Acceptance rate: {accepted / n_steps:.3f}")
print(f"Exact Beta(6,14): mean={target.mean():.4f}, std={target.std():.4f}")
print(f"MH MCMC samples: mean={kept.mean():.4f}, std={kept.std():.4f}")
Output
Acceptance rate: 0.533
Exact Beta(6,14): mean=0.3000, std=0.1000
MH MCMC samples: mean=0.2968, std=0.0983

With just 6,000 steps and zero closed-form normalization, the sampler hits an acceptance rate of 0.533 and recovers the exact mean (0.3000) and standard deviation (0.1000) to two decimals. In Example 5 you will apply the exact same loop to a real 3-parameter Bayesian logistic regression.

Information theory: Shannon entropy and surprise

Section titled “Information theory: Shannon entropy and surprise”

How much uncertainty lives in a probability distribution? Claude Shannon defined the self-information (or surprise) of observing an event with probability pp as:

I(x)=−log⁡2p(x)(measured in bits)I(x) = -\log_2 p(x) \quad \text{(measured in bits)}

A sure event (p=1p = 1) carries −log⁡21=0-\log_2 1 = 0 bits of surprise. A fair coin flip (p=0.5p = 0.5) carries −log⁡2(0.5)=1-\log_2(0.5) = 1 bit. A 1-in-16 event carries 4 bits. Using the natural logarithm ln⁡\ln instead of log⁡2\log_2 measures information in nats (the unit used by PyTorch and scikit-learn losses).

Shannon entropy is the expected surprise of a discrete random variable XX:

H(X)=−∑xP(X=x)log⁡2P(X=x)H(X) = -\sum_{x} P(X = x) \log_2 P(X = x)

Entropy is maximized by the uniform distribution (Hmax⁡=log⁡2KH_{\max} = \log_2 K for KK outcomes, maximum unpredictability) and equals 0 when one outcome happens with probability 1. Decision trees (Module 36) split features to maximize information gain—the drop in target entropy after a split. Compute Shannon entropy on customers["plan"] and reviews["rating"] using scipy.stats.entropy:

reviews = pd.read_csv("data/reviews.csv", keep_default_na=False)
p_plan = customers["plan"].value_counts(normalize=True).to_numpy()
p_rating = reviews["rating"].value_counts(normalize=True).to_numpy()
p_uniform_5 = np.full(5, 0.2)
print(
f"Entropy(plan, 3 classes): {stats.entropy(p_plan, base=2):.4f} bits"
f" (max {np.log2(3):.4f})"
)
print(
f"Entropy(rating, 5 classes): {stats.entropy(p_rating, base=2):.4f} bits"
f" (max {np.log2(5):.4f})"
)
print(f"Entropy(uniform 5 classes): {stats.entropy(p_uniform_5, base=2):.4f} bits")
print(f"Same rating entropy in nats: {stats.entropy(p_rating):.4f} nats")
Output
Entropy(plan, 3 classes): 1.5198 bits (max 1.5850)
Entropy(rating, 5 classes): 2.0175 bits (max 2.3219)
Entropy(uniform 5 classes): 2.3219 bits
Same rating entropy in nats: 1.3984 nats

Because 5-star reviews dominate reviews.csv, the rating distribution has lower entropy (2.0175 bits) than a uniform 5-star scale (2.3219 bits). Notice that stats.entropy(p) defaults to base ee (nats); pass base=2 for bits.

Cross-entropy, KL divergence and mutual information

Section titled “Cross-entropy, KL divergence and mutual information”

Entropy measures one distribution. Machine learning constantly compares two distributions: the true distribution PP and a model’s predicted distribution QQ.

  • Cross-entropy H(P,Q)=−∑xP(x)log⁡Q(x)H(P, Q) = -\sum_x P(x) \log Q(x) is the average code length when data comes from PP but you encode it using QQ. In classification, minimizing log-loss (binary or categorical cross-entropy) minimizes H(Ptrue,Qmodel)H(P_{\text{true}}, Q_{\text{model}}).
  • Kullback–Leibler (KL) divergence (relative entropy) is the extra information lost when approximating PP with QQ: DKL(P∥Q)=∑xP(x)log⁡P(x)Q(x)=H(P,Q)−H(P)≥0D_{\text{KL}}(P \Vert Q) = \sum_{x} P(x) \log \frac{P(x)}{Q(x)} = H(P, Q) - H(P) \ge 0 By Gibbs’ inequality, DKL(P∥Q)=0D_{\text{KL}}(P \Vert Q) = 0 if and only if P=QP = Q. Because H(P)H(P) is fixed with respect to a model’s weights, minimizing cross-entropy is identical to minimizing KL divergence from the data distribution to the model.
  • KL is asymmetric: DKL(P∥Q)≠DKL(Q∥P)D_{\text{KL}}(P \Vert Q) \neq D_{\text{KL}}(Q \Vert P), and if Q(x)=0Q(x) = 0 where P(x)>0P(x) > 0, KL explodes to +∞+\infty.
  • Jensen–Shannon (JS) divergence fixes both issues by averaging KL to the midpoint M=12(P+Q)M = \frac{1}{2}(P + Q): DJS(P∥Q)=12DKL(P∥M)+12DKL(Q∥M)D_{\text{JS}}(P \Vert Q) = \frac{1}{2} D_{\text{KL}}(P \Vert M) + \frac{1}{2} D_{\text{KL}}(Q \Vert M) JS divergence is symmetric, always finite, and bounded between 00 and ln⁡2\ln 2 (or 00 and 11 in base 2). scipy.spatial.distance.jensenshannon(p, q) returns the JS distance DJS\sqrt{D_{\text{JS}}}, so squaring it gives JS divergence!
  • Mutual information (MI) measures how much knowing XX reduces uncertainty about YY—equivalently, the KL divergence between the joint distribution and the product of marginals: I(X;Y)=DKL(P(X,Y)∥P(X)P(Y))=H(Y)−H(Y∣X)≥0I(X; Y) = D_{\text{KL}}\bigl(P(X, Y) \Vert P(X)P(Y)\bigr) = H(Y) - H(Y \mid X) \ge 0 I(X;Y)=0I(X; Y) = 0 if and only if XX and YY are truly independent—capturing both linear and non-linear relationships!

Verify the cross-entropy identity, KL asymmetry, JS symmetry and non-linear mutual information in one block:

p = np.array([0.70, 0.20, 0.10])
q = np.array([0.40, 0.40, 0.20])
h_p = stats.entropy(p) # nats
ce_pq = -np.sum(p * np.log(q))
kl_pq = stats.entropy(p, q)
kl_qp = stats.entropy(q, p)
js_div = jensenshannon(p, q) ** 2
print(f"H(P)={h_p:.4f} | H(P,Q)={ce_pq:.4f} | H(P,Q)-H(P)={ce_pq - h_p:.4f}")
print(f"KL(P||Q)={kl_pq:.4f} | KL(Q||P)={kl_qp:.4f} (asymmetric!)")
print(f"JS(P||Q)={js_div:.4f} | JS(Q||P)={jensenshannon(q, p) ** 2:.4f} (symmetric!)")
# Non-linear dependence: Y = X^2 has Pearson r ~ 0, but high MI
rng = np.random.default_rng(42)
x_nl = rng.normal(0, 1, size=2_000)
y_nl = (x_nl**2 > 1.0).astype(int)
mi_nl = mutual_info_classif(x_nl.reshape(-1, 1), y_nl, random_state=42)[0]
r_nl = np.corrcoef(x_nl, y_nl)[0, 1]
print(f"Non-linear Y=(X^2>1): Pearson r={r_nl:.4f} | MI={mi_nl:.4f}")
Output
H(P)=0.8018 | H(P,Q)=0.9856 | H(P,Q)-H(P)=0.1838
KL(P||Q)=0.1838 | KL(Q||P)=0.1920 (asymmetric!)
JS(P||Q)=0.0462 | JS(Q||P)=0.0462 (symmetric!)
Non-linear Y=(X^2>1): Pearson r=-0.0947 | MI=0.6247

Look at the last line: Y = (X**2 > 1) depends completely on X, yet Pearson correlation is -0.0947 (blind to symmetry). Mutual information immediately spots the strong dependence (0.6247 nats).

Example 1 — Model overdispersed daily orders with Negative Binomial vs. Poisson

Section titled “Example 1 — Model overdispersed daily orders with Negative Binomial vs. Poisson”

Goal: Fit Poisson and Negative Binomial distributions to daily order counts in data/sales.csv and verify which model accurately predicts busy-day demand spikes.

Step 1 — Measure daily order counts and diagnose overdispersion

Section titled “Step 1 — Measure daily order counts and diagnose overdispersion”

Aggregate unique order_id values per order_date and compare the sample mean to the sample variance. A Poisson distribution forces Var(X)=E[X]\text{Var}(X) = \mathbb{E}[X]; when variance greatly exceeds the mean, the counts are overdispersed.

sales = pd.read_csv("data/sales.csv")
daily_orders = sales.groupby("order_date")["order_id"].nunique()
mean_ord = daily_orders.mean()
var_ord = daily_orders.var(ddof=1)
print(f"Days: {len(daily_orders)} | Mean: {mean_ord:.2f} | Variance: {var_ord:.2f}")
print(f"Variance / Mean ratio: {var_ord / mean_ord:.2f}")
Output
Days: 731 | Mean: 20.35 | Variance: 104.04
Variance / Mean ratio: 5.11

The variance is more than five times the mean, driven by weekly cycles, holiday peaks and promotions. A Poisson model with λ=20.35\lambda = 20.35 will drastically underestimate how often extreme order days occur.

Step 2 — Fit Negative Binomial by method of moments and maximum likelihood

Section titled “Step 2 — Fit Negative Binomial by method of moments and maximum likelihood”

A Negative Binomial distribution parameterized by (r,p)(r, p) has μ=r(1−p)/p\mu = r(1-p)/p and σ2=μ+μ2/r\sigma^2 = \mu + \mu^2 / r. Solving for rr gives the method-of-moments starter r^MoM=μ2/(σ2−μ)\hat{r}_{\text{MoM}} = \mu^2 / (\sigma^2 - \mu), which we refine with scipy.optimize.minimize to obtain the exact MLE and compare total log-likelihoods.

counts = daily_orders.to_numpy()
r_mom = mean_ord**2 / (var_ord - mean_ord)
p_mom = r_mom / (r_mom + mean_ord)
def neg_loglik_nb(log_params: np.ndarray) -> float:
r, mu = np.exp(log_params)
p = r / (r + mu)
return float(-stats.nbinom.logpmf(counts, r, p).sum())
res_nb = optimize.minimize(
neg_loglik_nb, x0=np.log([r_mom, mean_ord]), method="Nelder-Mead"
)
r_mle, mu_mle = np.exp(res_nb.x)
p_mle = r_mle / (r_mle + mu_mle)
ll_pois = stats.poisson.logpmf(counts, mu=mean_ord).sum()
ll_nb = stats.nbinom.logpmf(counts, n=r_mle, p=p_mle).sum()
print(f"MoM init: r={r_mom:.3f}, p={p_mom:.4f}")
print(f"NB MLE: r={r_mle:.3f}, mu={mu_mle:.2f}, p={p_mle:.4f}")
print(
f"Log-likelihood -> Poisson: {ll_pois:.1f}"
f" | NegBin: {ll_nb:.1f} (gain +{ll_nb - ll_pois:.1f})"
)
Output
MoM init: r=4.949, p=0.1956
NB MLE: r=7.244, mu=20.35, p=0.2625
Log-likelihood -> Poisson: -3227.3 | NegBin: -2582.6 (gain +644.7)

Optimizing over (log⁡r,log⁡μ)(\log r, \log \mu) keeps both parameters strictly positive without needing box constraints. Switching from Poisson to Negative Binomial increases the log-likelihood by +644.7 points for just one extra parameter (rr).

Step 3 — Compare tail-risk predictions and plot the fitted PMFs

Section titled “Step 3 — Compare tail-risk predictions and plot the fitted PMFs”

Check the business question that matters for warehouse staffing: what is the probability of a surge day with at least 40 orders?

obs_surge = (counts >= 40).mean()
pois_surge = stats.poisson.sf(39, mu=mean_ord)
nb_surge = stats.nbinom.sf(39, n=r_mle, p=p_mle)
print(
f"P(orders >= 40) -> Observed: {obs_surge:.4f}"
f" | Poisson: {pois_surge:.6f} | NB: {nb_surge:.4f}"
)
k_vals = np.arange(0, 65)
fig, ax = plt.subplots(figsize=(7.5, 4.0))
ax.hist(
counts,
bins=np.arange(0, 66, 2),
density=True,
alpha=0.45,
label="Observed daily orders",
)
ax.plot(k_vals, stats.poisson.pmf(k_vals, mu=mean_ord), lw=2, label="Poisson MLE")
ax.plot(
k_vals,
stats.nbinom.pmf(k_vals, n=r_mle, p=p_mle),
lw=2,
label="Negative Binomial MLE",
)
ax.set_title("Daily orders in sales.csv: Poisson vs. Negative Binomial")
ax.set_xlabel("Orders per day")
ax.set_ylabel("Probability / density")
ax.legend()
ax.grid(alpha=0.25)
fig.tight_layout()
plt.show()
Output
P(orders >= 40) -> Observed: 0.0301 | Poisson: 0.000076 | NB: 0.0298
Histogram of daily orders peaking near 18 with a right tail past 50; the narrow Poisson curve misses the spread while the Negative Binomial curve closely tracks both the peak and the tail.
Poisson severely underestimates spread on overdispersed daily orders; Negative Binomial matches both the body and the surge tail.

Observed surge days happen 3.01% of the time (about 11 days per year). Poisson predicts 0.0076% (once every 36 years!), whereas Negative Binomial predicts 2.98%—right in line with reality.

Common mistakes:

  • Parameterizing stats.nbinom(n=r, p=p) with p=μ/(r+μ)p = \mu / (r + \mu) instead of p=r/(r+μ)p = r / (r + \mu); in SciPy, pp is the success probability and kk counts failures, so E[k]=r(1−p)/p\mathbb{E}[k] = r(1-p)/p.
  • Using sf(40) instead of sf(39) for discrete P(X≥40)P(X \ge 40): because sf(k) computes P(X>k)P(X > k), discrete inclusive tails require sf(k - 1).

Example 2 — Bayesian A/B test on checkout conversion

Section titled “Example 2 — Bayesian A/B test on checkout conversion”

Goal: Re-analyze data/ab_test.csv with a Beta–Binomial Bayesian model to compute P(treatment>control)P(\text{treatment} > \text{control}), a 95% credible interval for relative lift, and the expected conversion loss of shipping either variant.

Step 1 — Compute conjugate Beta posteriors from conversion counts

Section titled “Step 1 — Compute conjugate Beta posteriors from conversion counts”

Start with a flat Beta(1,1)\text{Beta}(1, 1) prior for each variant and update with the observed conversions and non-conversions.

ab_summary = ab.groupby("group")["converted"].agg(["sum", "count"])
k_c = int(ab_summary.loc["control", "sum"])
n_c = int(ab_summary.loc["control", "count"])
k_t = int(ab_summary.loc["treatment", "sum"])
n_t = int(ab_summary.loc["treatment", "count"])
post_c = stats.beta(1 + k_c, 1 + n_c - k_c)
post_t = stats.beta(1 + k_t, 1 + n_t - k_t)
cri_c = np.round(post_c.ppf([0.025, 0.975]), 4)
cri_t = np.round(post_t.ppf([0.025, 0.975]), 4)
print(f"Control: {k_c}/{n_c} -> post mean {post_c.mean():.4f}, 95% CrI {cri_c}")
print(f"Treatment: {k_t}/{n_t} -> post mean {post_t.mean():.4f}, 95% CrI {cri_t}")
Output
Control: 506/5002 -> post mean 0.1013, 95% CrI [0.0931 0.1098]
Treatment: 583/4998 -> post mean 0.1168, 95% CrI [0.108 0.1258]

Both posteriors are tightly concentrated because each arm has roughly 5,000 users.

Step 2 — Estimate probability of beating control and expected loss via Monte Carlo

Section titled “Step 2 — Estimate probability of beating control and expected loss via Monte Carlo”

Draw 50,000 independent samples from each posterior. The expected loss of choosing treatment is E[max⁡(pc−pt,0)]\mathbb{E}[\max(p_c - p_t, 0)]—the average conversion rate you forfeit if control was actually better.

rng = np.random.default_rng(42)
draws_c = post_c.rvs(size=50_000, random_state=rng)
draws_t = post_t.rvs(size=50_000, random_state=rng)
abs_diff = draws_t - draws_c
rel_lift = abs_diff / draws_c
prob_t_wins = (draws_t > draws_c).mean()
loss_ship_t = np.maximum(draws_c - draws_t, 0.0).mean()
loss_keep_c = np.maximum(draws_t - draws_c, 0.0).mean()
abs_lo, abs_hi = np.quantile(abs_diff, [0.025, 0.975])
rel_lo, rel_hi = np.quantile(rel_lift, [0.025, 0.975])
print(f"P(treatment > control): {prob_t_wins:.4f}")
print(f"Absolute lift 95% CrI: [{abs_lo:.4f}, {abs_hi:.4f}]")
print(f"Relative lift 95% CrI: [{rel_lo:.1%}, {rel_hi:.1%}]")
print(f"Expected loss (ship T): {loss_ship_t:.6f} | (keep C): {loss_keep_c:.6f}")
Output
P(treatment > control): 0.9937
Absolute lift 95% CrI: [0.0034, 0.0277]
Relative lift 95% CrI: [3.1%, 29.0%]
Expected loss (ship T): 0.000013 | (keep C): 0.015508

There is a 99.37% posterior probability that treatment outperforms control, with a relative lift most plausibly between +3.1% and +29.0%. Shipping treatment carries an expected regret of only 0.000013 conversion points—more than 1,000× smaller than the expected regret of keeping control (0.0155).

Step 3 — Visualize the posterior distributions and lift

Section titled “Step 3 — Visualize the posterior distributions and lift”

Plot the two conversion-rate posteriors side by side with the posterior distribution of the relative lift.

fig, axes = plt.subplots(1, 2, figsize=(9.0, 3.6))
p_grid = np.linspace(0.085, 0.135, 300)
axes[0].plot(p_grid, post_c.pdf(p_grid), lw=2, label="Control")
axes[0].plot(p_grid, post_t.pdf(p_grid), lw=2, label="Treatment")
axes[0].set_title("Posterior conversion rate")
axes[0].set_xlabel("Conversion rate p")
axes[0].set_ylabel("Density")
axes[0].legend()
axes[0].grid(alpha=0.25)
axes[1].hist(rel_lift * 100, bins=50, density=True, alpha=0.65)
axes[1].axvline(0.0, color="crimson", ls="--", lw=1.5, label="No lift (0%)")
axes[1].set_title("Posterior relative lift (%)")
axes[1].set_xlabel("Relative lift (%)")
axes[1].legend()
axes[1].grid(alpha=0.25)
fig.tight_layout()
plt.show()
Left panel shows two bell-shaped Beta posterior densities with treatment shifted right of control; right panel shows the relative lift histogram lying almost entirely above the dashed zero line.
Bayesian A/B test on ab_test.csv: posterior conversion densities (left) and relative lift distribution (right).

Common mistakes:

  • Reading P(treatment>control)=0.9937P(\text{treatment} > \text{control}) = 0.9937 as “guaranteed +15% lift”: high probability of being positive can still correspond to a small practical lift, so always report the credible interval and expected loss.
  • Using an overly strong prior (like Beta(500,4500)\text{Beta}(500, 4500)) without documenting it, which can drown out a small experiment’s data.

Example 3 — Shrink noisy product ratings with empirical Bayes

Section titled “Example 3 — Shrink noisy product ratings with empirical Bayes”

Goal: Rank the 30 products in data/reviews.csv by positive-review rate (rating ≥4\ge 4) using empirical Bayes Beta–Binomial shrinkage so products with few reviews do not jump to the top or bottom by luck.

Step 1 — Compute raw positive rates per product

Section titled “Step 1 — Compute raw positive rates per product”

Count total reviews and positive reviews (rating≥4\text{rating} \ge 4) for each product.

prod_rev = (
reviews.groupby(["product_id", "product"])
.agg(n=("rating", "count"), pos=("rating", lambda s: int((s >= 4).sum())))
.reset_index()
)
prod_rev["raw_rate"] = prod_rev["pos"] / prod_rev["n"]
print(prod_rev.sort_values("raw_rate", ascending=False).head(5).to_string(index=False))
Output
product_id product n pos raw_rate
P018 Adjustable Dumbbells 53 44 0.830
P021 Harbor Lane Mysteries 115 93 0.809
P008 Chef's Knife Set 117 90 0.769
P029 Electric Toothbrush 72 54 0.750
P010 Cotton Bed Sheet Set 166 123 0.741

Adjustable Dumbbells ranks #1 on raw rate (0.830), but it has less than half the review volume of Harbor Lane Mysteries (115 reviews, 0.809).

Step 2 — Estimate the catalog-wide Beta prior via method of moments

Section titled “Step 2 — Estimate the catalog-wide Beta prior via method of moments”

Empirical Bayes estimates the prior hyperparameters (α0,β0)(\alpha_0, \beta_0) from the population of all 30 products rather than guessing them by hand. Matching the sample mean mm and variance vv of the product rates to a Beta distribution gives:

α0=m(m(1−m)v−1),β0=(1−m)(m(1−m)v−1)\alpha_0 = m\left(\frac{m(1-m)}{v} - 1\right), \qquad \beta_0 = (1-m)\left(\frac{m(1-m)}{v} - 1\right)
m_rate = prod_rev["raw_rate"].mean()
v_rate = prod_rev["raw_rate"].var(ddof=1)
strength = m_rate * (1 - m_rate) / v_rate - 1
alpha0 = m_rate * strength
beta0 = (1 - m_rate) * strength
prod_rev["eb_rate"] = (prod_rev["pos"] + alpha0) / (prod_rev["n"] + alpha0 + beta0)
prior_mean = alpha0 / (alpha0 + beta0)
print(
f"Empirical prior: Beta({alpha0:.2f}, {beta0:.2f})"
f" -> prior mean {prior_mean:.4f}"
)
print("\nTop 5 after empirical Bayes shrinkage:")
cols = ["product_id", "product", "n", "raw_rate", "eb_rate"]
top5 = prod_rev.sort_values("eb_rate", ascending=False)[cols].head(5)
print(top5.to_string(index=False))
Output
Empirical prior: Beta(28.85, 13.00) -> prior mean 0.6894
Top 5 after empirical Bayes shrinkage:
product_id product n raw_rate eb_rate
P021 Harbor Lane Mysteries 115 0.809 0.777
P018 Adjustable Dumbbells 53 0.830 0.768
P008 Chef's Knife Set 117 0.769 0.748
P010 Cotton Bed Sheet Set 166 0.741 0.731
P029 Electric Toothbrush 72 0.750 0.728

Look at the top two: Harbor Lane Mysteries (115 reviews) overtakes Adjustable Dumbbells (53 reviews), because the empirical prior contributes about 42 pseudo-reviews centered at 68.9%, shrinking smaller-sample extremes more strongly toward the catalog mean.

Step 3 — Check how shrinkage protects against a 2-review newcomer

Section titled “Step 3 — Check how shrinkage protects against a 2-review newcomer”

Test what happens when a brand-new item launches and its first two buyers both leave 5-star reviews (raw positive rate 100%):

for label, pos_k, total_n in [
("New item (2/2)", 2, 2),
("Small hit (18/20)", 18, 20),
("Proven bestseller (160/200)", 160, 200),
]:
raw = pos_k / total_n
eb = (pos_k + alpha0) / (total_n + alpha0 + beta0)
print(f"{label:<28} raw={raw:.3f} -> EB={eb:.3f}")
Output
New item (2/2) raw=1.000 -> EB=0.704
Small hit (18/20) raw=0.900 -> EB=0.758
Proven bestseller (160/200) raw=0.800 -> EB=0.781

Empirical Bayes gives a completely principled ranking: 160/200 (0.781) beats 18/20 (0.758), which beats 2/2 (0.704), without arbitrary hard cutoffs like “hide items under 10 reviews.”

Common mistakes:

  • Fitting the empirical Beta prior using products that only have 1 or 2 reviews without weighting—the raw variance vv then mixes sampling noise with true between-product variance; for very uneven nn, fit a Beta–Binomial MLE instead.
  • Forgetting that the shrinkage formula k+α0n+α0+β0\frac{k + \alpha_0}{n + \alpha_0 + \beta_0} is the posterior mean of Beta(α0+k,β0+n−k)\text{Beta}(\alpha_0 + k, \beta_0 + n - k).

Example 4 — Verify that Gaussian MAP equals Ridge regression

Section titled “Example 4 — Verify that Gaussian MAP equals Ridge regression”

Goal: Show numerically on data/houses.csv that linear regression with a Gaussian weight prior produces the exact same coefficients as sklearn.linear_model.Ridge, and compare against a Laplace (L1) MAP solution.

Step 1 — Standardize house features and solve closed-form Gaussian MAP

Section titled “Step 1 — Standardize house features and solve closed-form Gaussian MAP”

Center log⁡(price)\log(\text{price}) and standardize five numeric house features so the intercept separates cleanly and all weights share one prior scale τ2\tau^2. Under yi∼N(xi⊤w,σ2)y_i \sim \mathcal{N}(\mathbf{x}_i^\top \mathbf{w}, \sigma^2) and wj∼N(0,τ2)w_j \sim \mathcal{N}(0, \tau^2), setting the gradient of the log-posterior to zero yields:

w^MAP=(X⊤X+λI)−1X⊤y,λ=σ2τ2\hat{\mathbf{w}}_{\text{MAP}} = \bigl(X^\top X + \lambda I\bigr)^{-1} X^\top \mathbf{y}, \qquad \lambda = \frac{\sigma^2}{\tau^2}
feat_cols = ["sqft", "bedrooms", "bathrooms", "condition", "distance_to_center_km"]
X_raw = houses[feat_cols].to_numpy(dtype=float)
X_std = (X_raw - X_raw.mean(axis=0)) / X_raw.std(axis=0)
y_log = np.log(houses["price"].to_numpy(dtype=float))
y_c = y_log - y_log.mean()
sigma2 = 0.04 # assumed noise variance on log-price
tau2 = 0.002 # prior variance on each standardized slope
lam = sigma2 / tau2 # = 20.0
w_map = np.linalg.solve(X_std.T @ X_std + lam * np.eye(X_std.shape[1]), X_std.T @ y_c)
ridge = Ridge(alpha=lam, fit_intercept=True).fit(X_std, y_log)
max_diff = np.max(np.abs(w_map - ridge.coef_))
print(f"lambda = sigma^2 / tau^2 = {lam:.1f}")
print(f"Max |w_MAP - Ridge.coef_|: {max_diff:.2e}")
for name, wm, wr in zip(feat_cols, w_map, ridge.coef_, strict=True):
print(f" {name:<22} MAP={wm:+.5f} Ridge={wr:+.5f}")
Output
lambda = sigma^2 / tau^2 = 20.0
Max |w_MAP - Ridge.coef_|: 4.44e-16
sqft MAP=+0.35678 Ridge=+0.35678
bedrooms MAP=-0.01627 Ridge=-0.01627
bathrooms MAP=+0.05365 Ridge=+0.05365
condition MAP=+0.14288 Ridge=+0.14288
distance_to_center_km MAP=-0.19179 Ridge=-0.19179

The Gaussian MAP formula matches sklearn.linear_model.Ridge(alpha=20.0) to 4.44e-16—machine epsilon.

Step 2 — Compare Gaussian MAP (L2) vs. Laplace MAP (L1) shrinkage

Section titled “Step 2 — Compare Gaussian MAP (L2) vs. Laplace MAP (L1) shrinkage”

Now swap the Gaussian prior for a Laplace prior with penalty λ1=σ2/b\lambda_1 = \sigma^2 / b and solve the Laplace MAP objective via soft-thresholding coordinate descent (the exact algorithm inside Lasso). Compare how L2 shrinks bedrooms near zero while L1 pushes it to exact zero:

from sklearn.linear_model import Lasso
# sklearn Lasso minimizes (1 / (2n)) * ||y - Xw||^2 + alpha * ||w||_1
# That matches Laplace MAP with lambda_1 = sigma^2 / b = n * alpha
alpha_l1 = 0.03
lam1 = len(y_c) * alpha_l1
w_lap = np.zeros(X_std.shape[1])
for _ in range(500):
for j in range(X_std.shape[1]):
r_j = y_c - X_std @ w_lap + X_std[:, j] * w_lap[j]
rho = float(X_std[:, j] @ r_j)
denom = float(X_std[:, j] @ X_std[:, j])
w_lap[j] = np.sign(rho) * max(abs(rho) - lam1, 0.0) / denom
lasso = Lasso(alpha=alpha_l1, fit_intercept=True, max_iter=5000, tol=1e-8).fit(
X_std, y_log
)
print("Feature Gaussian MAP Laplace MAP sklearn Lasso")
for name, wg, wl, wlas in zip(feat_cols, w_map, w_lap, lasso.coef_, strict=True):
print(f"{name:<22} {wg:+11.4f} {wl:+11.4f} {wlas:+13.4f}")
Output
Feature Gaussian MAP Laplace MAP sklearn Lasso
sqft +0.3568 +0.3388 +0.3388
bedrooms -0.0163 +0.0000 +0.0000
bathrooms +0.0536 +0.0238 +0.0238
condition +0.1429 +0.1085 +0.1085
distance_to_center_km -0.1918 -0.1533 -0.1533

Directly minimizing the Laplace negative log-posterior reproduces sklearn.linear_model.Lasso to four decimals, setting the weak bedrooms slope (once sqft is controlled for) to exact 0.0000.

Common mistakes:

  • Penalizing the intercept w0w_0 along with the slopes: shifting y by a constant should shift the intercept without shrinking it toward zero, which is why we centered y (or leave w0w_0 unpenalized).
  • Forgetting the 1/(2n)1/(2n) factor in scikit-learn’s Lasso(alpha=...) objective compared to the unaveraged sum of squared errors in Ridge(alpha=...).

Example 5 — Bayesian logistic regression with Metropolis–Hastings MCMC

Section titled “Example 5 — Bayesian logistic regression with Metropolis–Hastings MCMC”

Goal: Estimate the full posterior distribution of a logistic regression predicting customer churn on a 600-row sample of data/customers.csv using a hand-written NumPy Metropolis–Hastings sampler, and verify it against statsmodels MLE.

Step 1 — Prepare features and compute the frequentist MLE baseline

Section titled “Step 1 — Prepare features and compute the frequentist MLE baseline”

Sample 600 customers, standardize tenure_months and support_tickets, add an intercept column, and fit sm.Logit as a sanity check.

sub = customers.sample(n=600, random_state=42)
X_lr = sub[["tenure_months", "support_tickets"]].to_numpy(dtype=float)
X_lr_std = (X_lr - X_lr.mean(axis=0)) / X_lr.std(axis=0)
X_design = np.column_stack([np.ones(len(sub)), X_lr_std])
y_lr = sub["churned"].to_numpy(dtype=float)
mle_fit = sm.Logit(y_lr, X_design).fit(disp=False)
param_names = ["intercept", "tenure_std", "tickets_std"]
for name, est, se in zip(param_names, mle_fit.params, mle_fit.bse, strict=True):
print(f"MLE {name:<12}: {est:+.4f} (SE {se:.4f})")
Output
MLE intercept : -1.8425 (SE 0.1476)
MLE tenure_std : -1.1375 (SE 0.1858)
MLE tickets_std : +0.2375 (SE 0.1062)

Longer tenure strongly reduces churn log-odds (-1.1375), while more support tickets raise churn log-odds (+0.2375).

Step 2 — Write the numerically stable log-posterior and run Metropolis–Hastings

Section titled “Step 2 — Write the numerically stable log-posterior and run Metropolis–Hastings”

For logistic regression, log⁡p(yi∣xi,β)=yizi−log⁡(1+ezi)\log p(y_i \mid \mathbf{x}_i, \boldsymbol{\beta}) = y_i z_i - \log(1 + e^{z_i}) where zi=xi⊤βz_i = \mathbf{x}_i^\top \boldsymbol{\beta}. Using np.logaddexp(0.0, z) computes log⁡(1+ez)\log(1 + e^z) without overflow. Place a weakly informative N(0,22)\mathcal{N}(0, 2^2) prior on each parameter and run 8,000 Metropolis–Hastings steps with 2,000 burn-in.

def log_post_logit(
beta: np.ndarray, X: np.ndarray, y: np.ndarray, prior_sd: float = 2.0
) -> float:
z = X @ beta
log_lik = np.sum(y * z - np.logaddexp(0.0, z))
log_prior = -0.5 * np.sum((beta / prior_sd) ** 2)
return float(log_lik + log_prior)
rng = np.random.default_rng(42)
n_steps, burn = 8_000, 2_000
chain = np.empty((n_steps, 3))
beta = np.zeros(3)
cur_lp = log_post_logit(beta, X_design, y_lr)
step_scale = np.array([0.14, 0.14, 0.14])
accepted = 0
for t in range(n_steps):
prop = beta + rng.normal(0.0, step_scale)
prop_lp = log_post_logit(prop, X_design, y_lr)
if np.log(rng.random()) < prop_lp - cur_lp:
beta, cur_lp = prop, prop_lp
accepted += 1
chain[t] = beta
post_samples = chain[burn:]
print(f"Acceptance rate: {accepted / n_steps:.3f}")
for i, name in enumerate(param_names):
s = post_samples[:, i]
lo, hi = np.quantile(s, [0.025, 0.975])
print(
f"MCMC {name:<11}: mean={s.mean():+.4f} sd={s.std():.4f}"
f" 95% CrI=[{lo:+.3f}, {hi:+.3f}]"
)
Output
Acceptance rate: 0.378
MCMC intercept : mean=-1.8425 sd=0.1464 95% CrI=[-2.139, -1.553]
MCMC tenure_std : mean=-1.1379 sd=0.1895 95% CrI=[-1.506, -0.774]
MCMC tickets_std: mean=+0.2402 sd=0.1123 95% CrI=[+0.024, +0.467]

The acceptance rate is 0.378 (right in the healthy 0.25–0.45 band), and the posterior means and standard deviations closely agree with the statsmodels MLE estimates and standard errors!

Step 3 — Inspect trace diagnostics and predict churn probability with uncertainty

Section titled “Step 3 — Inspect trace diagnostics and predict churn probability with uncertainty”

Plot the trace and posterior histogram for tenure_std, and propagate all 6,000 posterior draws into a predicted churn probability for a high-risk customer (1 SD below mean tenure, 2 SD above mean tickets):

x_new = np.array([1.0, -1.0, 2.0])
logits_new = post_samples @ x_new
p_churn_new = 1.0 / (1.0 + np.exp(-logits_new))
print(
f"High-risk customer churn P: mean={p_churn_new.mean():.3f},"
f" 95% CrI={np.quantile(p_churn_new, [0.025, 0.975]).round(3)}"
)
fig, axes = plt.subplots(1, 2, figsize=(9.0, 3.4))
axes[0].plot(post_samples[:, 1], lw=0.6, alpha=0.8)
axes[0].axhline(mle_fit.params[1], color="crimson", ls="--", lw=1.5, label="MLE")
axes[0].set_title("MCMC trace: tenure_std (after burn-in)")
axes[0].set_xlabel("Iteration")
axes[0].set_ylabel("Coefficient")
axes[0].legend()
axes[0].grid(alpha=0.25)
axes[1].hist(post_samples[:, 1], bins=35, density=True, alpha=0.7)
axes[1].axvline(mle_fit.params[1], color="crimson", ls="--", lw=1.5, label="MLE")
axes[1].set_title("Posterior distribution: tenure_std")
axes[1].set_xlabel("Coefficient")
axes[1].legend()
axes[1].grid(alpha=0.25)
fig.tight_layout()
plt.show()
Output
High-risk customer churn P: mean=0.445, 95% CrI=[0.326 0.564]
Left panel shows a stationary fuzzy trace plot oscillating around -1.14 with a dashed MLE reference line; right panel shows a symmetric bell-shaped posterior histogram centered on the MLE.
Metropolis-Hastings diagnostics for the standardized tenure coefficient: stationary trace (left) and posterior histogram (right).

With posterior samples in hand, getting a credible interval for any non-linear function of the parameters—like a predicted customer probability (0.326 to 0.564)—requires zero extra math.

Common mistakes:

  • Multiplying raw likelihood probabilities (np.prod(p**y * (1-p)**(1-y))) instead of summing log-likelihoods: with 600 rows, raw products underflow to 0.0 immediately.
  • Failing to standardize predictors before using an isotropic proposal step_scale = [0.14, 0.14, 0.14]: variables on wildly different scales need different step sizes or the chain gets stuck.

Example 6 — Feature dependence with mutual information and sensor drift with KL and JS divergence

Section titled “Example 6 — Feature dependence with mutual information and sensor drift with KL and JS divergence”

Goal: Use mutual information on data/customers.csv to uncover non-linear churn predictors that Pearson correlation misses, then use smoothed KL and Jensen–Shannon divergence on data/sensors.csv to detect which sensors drifted between Week 1 and Week 2.

Step 1 — Compare Pearson correlation and mutual information on customer churn

Section titled “Step 1 — Compare Pearson correlation and mutual information on customer churn”

Compute both ∣r∣|r| and mutual_info_classif for every numeric predictor in customers.csv.

num_cols = [
"age",
"tenure_months",
"monthly_charges",
"support_tickets",
"logins_last_30d",
"avg_session_minutes",
]
mi_scores = mutual_info_classif(
customers[num_cols], customers["churned"], random_state=42
)
rows = []
for col, mi_val in zip(num_cols, mi_scores, strict=True):
r_val = customers[col].corr(customers["churned"])
rows.append({"feature": col, "abs_pearson": abs(r_val), "mutual_info": mi_val})
dep_df = pd.DataFrame(rows).sort_values("mutual_info", ascending=False)
print(dep_df.to_string(index=False))
Output
feature abs_pearson mutual_info
tenure_months 0.281 0.068
age 0.039 0.013
support_tickets 0.210 0.010
monthly_charges 0.122 0.009
avg_session_minutes 0.052 0.007
logins_last_30d 0.096 0.005

Look closely at age: it has the smallest linear correlation (|r| = 0.039), yet the second-highest mutual information (0.013). Checking churn by age bracket explains why: young and older subscribers churn more than middle-aged subscribers—a U-shape whose upward and downward halves cancel out in Pearson correlation.

Step 2 — Measure sensor distribution drift with smoothed KL and JS divergence

Section titled “Step 2 — Measure sensor distribution drift with smoothed KL and JS divergence”

Split data/sensors.csv into Week 1 (May 1–7, baseline) and Week 2 (May 8–14, live window). Bin each sensor’s temperature and vibration readings onto a shared grid, add tiny Laplace smoothing (eps = 1e-6) so zero bins never cause ∞\infty, and compute both DKL(Week 2∥Week 1)D_{\text{KL}}(\text{Week 2} \Vert \text{Week 1}) and symmetric JS divergence.

sensors = pd.read_csv("data/sensors.csv")
sensors["ts"] = pd.to_datetime(sensors["timestamp"])
w1 = sensors[sensors["ts"] < "2024-05-08"]
w2 = sensors[sensors["ts"] >= "2024-05-08"]
def histogram_drift(
base: pd.Series, curr: pd.Series, bins: np.ndarray
) -> tuple[float, float]:
p, _ = np.histogram(base.dropna(), bins=bins)
q, _ = np.histogram(curr.dropna(), 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)) # KL(current || baseline) in nats
js = float(jensenshannon(p, q) ** 2)
return kl, js
t_bins = np.linspace(18.0, 45.0, 28)
v_bins = np.linspace(1.0, 20.0, 20)
drift_rows = []
for sid in ["S1", "S2", "S3", "S4"]:
kl_t, js_t = histogram_drift(
w1.loc[w1["sensor_id"] == sid, "temperature_c"],
w2.loc[w2["sensor_id"] == sid, "temperature_c"],
t_bins,
)
kl_v, js_v = histogram_drift(
w1.loc[w1["sensor_id"] == sid, "vibration_mm_s"],
w2.loc[w2["sensor_id"] == sid, "vibration_mm_s"],
v_bins,
)
drift_rows.append(
{
"sensor": sid,
"temp_KL": kl_t,
"temp_JS": js_t,
"vib_KL": kl_v,
"vib_JS": js_v,
}
)
drift_df = pd.DataFrame(drift_rows)
print(drift_df.round(3).to_string(index=False))
Output
sensor temp_KL temp_JS vib_KL vib_JS
S1 0.068 0.005 0.007 0.002
S2 0.098 0.009 0.021 0.003
S3 2.409 0.218 0.058 0.003
S4 0.097 0.007 5.289 0.151

The drift signal is unmistakable: S1 and S2 have near-zero JS divergence (< 0.01) on both metrics, S3 flags severe temperature drift (JS = 0.218, KL = 2.409), and S4 flags severe vibration wear (JS = 0.151, KL = 5.289).

Step 3 — Visualize the drifting distributions for S3 and S4

Section titled “Step 3 — Visualize the drifting distributions for S3 and S4”

Plot Week 1 vs. Week 2 distributions for the two flagged metrics so engineers can see the physical shift immediately.

fig, axes = plt.subplots(1, 2, figsize=(9.0, 3.5))
for sid, col, bins, ax, title in [
("S3", "temperature_c", t_bins, axes[0], "S3 temperature drift (JS=0.218)"),
("S4", "vibration_mm_s", v_bins, axes[1], "S4 vibration drift (JS=0.151)"),
]:
ax.hist(
w1.loc[w1["sensor_id"] == sid, col].dropna(),
bins=bins,
density=True,
alpha=0.55,
label="Week 1 (May 1-7)",
)
ax.hist(
w2.loc[w2["sensor_id"] == sid, col].dropna(),
bins=bins,
density=True,
alpha=0.55,
label="Week 2 (May 8-14)",
)
ax.set_title(title)
ax.set_xlabel(col)
ax.legend()
ax.grid(alpha=0.25)
fig.tight_layout()
plt.show()
Left panel shows S3 temperature shifting right by roughly 2.4 degrees in Week 2; right panel shows S4 vibration developing a long heavy right tail in Week 2.
Visual confirmation of the two drift alerts flagged by Jensen-Shannon divergence: S3 calibration drift (left) and S4 mechanical wear (right).

Common mistakes:

  • Computing KL divergence on raw histogram counts without smoothing: a single empty bin in the reference distribution makes DKL=∞D_{\text{KL}} = \infty.
  • Confusing scipy.spatial.distance.jensenshannon (which returns DJS\sqrt{D_{\text{JS}}}, the JS distance) with JS divergence (DJSD_{\text{JS}}).
Mistake Symptom Fix
Confusing P(A∣B)P(A \mid B) with P(B∣A)P(B \mid A) Base-rate fallacy (e.g. reading a 99% test sensitivity as a 99% chance of disease) Always apply Bayes’ theorem with the prior base rate P(A)P(A)
Wrong scipy.stats parameterization Mean is inverted or wildly off for Exponential, Gamma, Log-normal or Negative Binomial Remember scale = 1/rate for Exponential/Gamma, scale = exp(mu) for Log-normal, and p = r/(r+mu) for NegBin
Multiplying raw probabilities in likelihoods Posterior ratio becomes 0/0 (NaN) once n≳100n \gtrsim 100 Work entirely in log-space (logpdf, logpmf, np.logaddexp)
Computing KL with zero bins stats.entropy(q, p) returns inf Add small smoothing (e.g. 1e-6) to shared histogram bins, or use JS divergence
Treating KL divergence as a symmetric metric Swapping reference and live windows gives a different alert threshold Use DJS(P∥Q)D_{\text{JS}}(P \Vert Q) when you want a symmetric, bounded drift score
Penalizing the intercept in MAP / Ridge Predictions are systematically biased toward zero Center yy or exclude the intercept term from the prior penalty
Skipping MCMC diagnostics Posterior means look plausible even though the chain barely moved Always check acceptance rate (target ~0.25–0.45), discard burn-in and inspect trace plots
Reading a frequentist CI as a credible interval Incorrect probability claim about a fixed parameter Use Bayesian posteriors when you need P(a≤θ≤b∣D)P(a \le \theta \le b \mid D)
  • Data compression and networking: Shannon entropy sets the exact mathematical lower bound (in bits per symbol) for lossless compression algorithms such as Huffman coding, arithmetic coding, gzip and zstd.
  • Site reliability engineering (SRE) and queuing: Exponential and Gamma distributions model inter-arrival times and service latencies in distributed systems, helping engineers size thread pools and predict tail-latency SLA breaches.
  • Actuarial science and quantitative finance: Negative Binomial and Gamma–Poisson mixtures model insurance claim frequencies, while Log-normal distributions and Bayesian updating underpin option pricing and risk reserves.
  • Spam filtering, search and bioinformatics: Naive Bayes classifiers, Dirichlet-smoothed language models and KL/mutual-information scores power email filters, document retrieval and DNA sequence motif discovery.
  • Probability axioms, the law of total probability and Bayes’ theorem govern how joint, marginal and conditional distributions fit together.
  • Match the distribution family to the data’s domain and variance: Exponential/Gamma for positive wait times, Beta for probabilities, Log-normal for skewed money, Negative Binomial for overdispersed counts and Multinomial for multi-class counts.
  • Conjugate priors (Beta–Binomial, Gamma–Poisson, Normal–Normal, Dirichlet–Multinomial) turn Bayesian updating into simple parameter updates and give direct credible intervals and posterior predictive distributions.
  • MAP estimation links probability directly to ML regularization: a Gaussian prior yields Ridge (L2) and a Laplace prior yields Lasso (L1).
  • When posteriors have no closed form, Metropolis–Hastings MCMC samples from the unnormalized log-posterior; monitor burn-in, acceptance rate and trace plots.
  • Shannon entropy quantifies uncertainty, cross-entropy measures prediction loss, KL and JS divergences detect distribution drift, and mutual information captures both linear and non-linear dependence.

Q1. In a factory, 2% of batches are defective. A sensor flags 95% of defective batches and falsely flags 5% of good batches. If a batch is flagged, is the probability that it is truly defective close to 95%?

Answer

No—it is only about 27.9%. By Bayes’ theorem: P(defect∣flag)=0.95×0.020.95×0.02+0.05×0.98=0.0190.068≈0.279P(\text{defect} \mid \text{flag}) = \frac{0.95 \times 0.02}{0.95 \times 0.02 + 0.05 \times 0.98} = \frac{0.019}{0.068} \approx 0.279. Because defects are rare (low base rate), false alarms outnumber true alarms.

Q2. Suppose Cov(X,Y)=0\text{Cov}(X, Y) = 0. Does that prove XX and YY are independent? What measure can detect non-linear dependence?

Answer

No. Zero covariance only rules out linear association; for example, X∼N(0,1)X \sim \mathcal{N}(0, 1) and Y=X2Y = X^2 have zero covariance yet are completely dependent. Mutual information I(X;Y)I(X; Y) equals zero if and only if XX and YY are independent, so it detects non-linear relationships too.

Q3. Daily support tickets have mean 12 and variance 48. Why is a Poisson model a poor fit, and which distribution should you use instead?

Answer

A Poisson distribution requires variance to equal the mean (12), so variance 48 shows strong overdispersion (4× the mean). A Negative Binomial distribution adds a dispersion parameter rr that lets variance exceed the mean (σ2=μ+μ2/r\sigma^2 = \mu + \mu^2 / r), capturing heavy busy-day tails accurately.

Q4. You start with a Beta(3,27)\text{Beta}(3, 27) prior for click-through rate and observe 15 clicks in 100 impressions. What is the exact posterior distribution and its posterior mean?

Answer

Because Beta is conjugate to Binomial, the posterior is Beta(3+15,  27+85)=Beta(18,112)\text{Beta}(3 + 15,\; 27 + 85) = \text{Beta}(18, 112). Its posterior mean is 18/(18+112)=18/130≈0.138518 / (18 + 112) = 18 / 130 \approx 0.1385.

Q5. Why is a posterior predictive interval wider than a plug-in prediction interval that fixes θ=θ^MLE\theta = \hat{\theta}_{\text{MLE}}?

Answer

A plug-in interval accounts only for sampling randomness of future observations assuming θ\theta is known exactly. The posterior predictive distribution integrates over the posterior uncertainty in θ\theta as well, combining both parameter uncertainty and outcome randomness.

Q6. In linear regression with noise variance σ2\sigma^2, how does the Ridge penalty λ\lambda relate to the prior variance τ2\tau^2 in a Gaussian MAP model, and what prior corresponds to Lasso?

Answer

For a zero-mean Gaussian prior wj∼N(0,τ2)w_j \sim \mathcal{N}(0, \tau^2), the MAP penalty is λ=σ2/τ2\lambda = \sigma^2 / \tau^2: a smaller prior variance τ2\tau^2 means stronger L2 regularization. Replacing the Gaussian prior with a Laplace prior wj∼Laplace(0,b)w_j \sim \text{Laplace}(0, b) yields an L1 penalty, which corresponds to Lasso regression.

Q7. Why does the Metropolis–Hastings acceptance ratio never require computing the marginal likelihood p(D)p(D)?

Answer

Because the acceptance ratio divides p(θ∗∣D)=p(D∣θ∗)p(θ∗)p(D)p(\theta^* \mid D) = \frac{p(D \mid \theta^*)p(\theta^*)}{p(D)} by p(θ(t)∣D)=p(D∣θ(t))p(θ(t))p(D)p(\theta^{(t)} \mid D) = \frac{p(D \mid \theta^{(t)})p(\theta^{(t)})}{p(D)}. The constant p(D)p(D) cancels in numerator and denominator, leaving only the ratio of unnormalized posteriors (a difference in log-space).

Q8. Your Metropolis–Hastings sampler has an acceptance rate of 0.94 and the trace plot wanders slowly like a drunken walk. What is wrong and how do you fix it?

Answer

The proposal step size is too small, so nearly every move is accepted but the chain explores the posterior very slowly with high autocorrelation. Increase the proposal standard deviation until the acceptance rate falls into roughly the 0.25–0.45 range.

Q9. Why is minimizing cross-entropy loss during neural network classification mathematically equivalent to minimizing KL divergence from the true label distribution to the predicted probabilities?

Answer

Because H(P,Q)=H(P)+DKL(P∥Q)H(P, Q) = H(P) + D_{\text{KL}}(P \Vert Q), and the true data entropy H(P)H(P) does not depend on the model’s parameters. Therefore any parameter update that decreases cross-entropy H(P,Q)H(P, Q) decreases DKL(P∥Q)D_{\text{KL}}(P \Vert Q) by the exact same amount.

Q10. Why is Jensen–Shannon divergence often preferred over raw KL divergence for monitoring feature drift in production?

Answer

KL divergence is asymmetric and explodes to +∞+\infty whenever the reference histogram has a zero-count bin where new data appears. Jensen–Shannon divergence averages KL to the midpoint 12(P+Q)\frac{1}{2}(P + Q), so it is always finite, symmetric and bounded between 00 and ln⁡2\ln 2 (or 11 bit), making alert thresholds easy to calibrate.

Your progress

0 / 4 done

  • Exercises: 25+ exercises across Warm-up, Core and Challenge tiers with hints and full verified solutions.
  • Mini-project: build a reusable Bayesian Experimentation and Drift Toolkit on the course datasets.
  • Cheat sheet: distributions, conjugate priors, MAP regularization, MCMC and information-theory formulas on one page.
  • Next module: 49. Causal inference, GLMs and advanced experimentation extends these probabilistic models to causal DAGs, CUPED, multi-armed bandits, GLMs and survival analysis.