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.
What you will learn
Section titled “What you will learn”- 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.statsbeyond 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.
Prerequisites
Section titled “Prerequisites”- 23. NumPy: vectorized arrays, broadcasting, matrix algebra and
np.random.default_rng. - 29. Statistics and probability: random variables, PMF/PDF/CDF/PPF, confidence intervals, hypothesis tests and A/B testing.
- 32. Math for ML: dot products, logarithms, gradients and basic probability notation.
- 47. Calculus and optimization for ML: derivatives, log-likelihood optimization and numerical integration (recommended).
- The course datasets in a
data/folder: Get the data.
Concepts
Section titled “Concepts”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 pltimport numpy as npimport pandas as pdimport scipyimport statsmodels.api as smfrom scipy import optimize, statsfrom scipy.spatial.distance import jensenshannonfrom sklearn.feature_selection import mutual_info_classiffrom 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__}")numpy 2.5.4 | scipy 1.18.1Probability 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 (the set of all possible outcomes):
- Non-negativity: for every event .
- Normalization: (something in the sample space must happen).
- Additivity: if events and are mutually exclusive (), then .
From those three rules follow the complement rule , the inclusion–exclusion rule , and conditional probability:
When events partition the sample space (they do not overlap and together cover everything), the law of total probability expresses as a weighted average of conditional probabilities:
Reversing the conditioning gives Bayes’ theorem:
In discrete probability you also count combinations and permutations using combinatorics: the number of ways to choose unordered items from is the binomial coefficient (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_echeckp_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)}")P(churn) direct: 0.1926 | via total probability: 0.1926P(churn | echeck) Bayes: 0.2476 | direct: 0.24765-card hands from 52: 2,598,960 | 3-stage orders from 8: 336The law of total probability matches the global churn rate to full precision, and Bayes’ theorem recovers from the reverse conditional probability 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 assigns probability to pairs of outcomes. Summing (or integrating) over one variable recovers the marginal distribution: . Fixing one variable and renormalizing gives the conditional distribution: .
Two variables are independent () when knowing one tells you nothing about the other: for every pair . 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}")Joint P(plan, contract):contract month-to-month one-year two-yearplanbasic 0.234 0.094 0.078premium 0.106 0.050 0.042standard 0.216 0.102 0.078
Conditional P(contract | plan):contract month-to-month one-year two-yearplanbasic 0.578 0.231 0.191premium 0.535 0.251 0.214standard 0.546 0.257 0.197
Max |P(X,Y) - P(X)P(Y)|: 0.0086The rows of are nearly identical across basic, premium and standard, and the largest gap between and is only 0.0086. In this customer base, plan tier and contract length are practically independent.
For continuous random vectors , linear co-movement is captured by the covariance matrix , where . The diagonal entries are variances , and is symmetric positive semi-definite. The multivariate normal distribution 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}")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.947Log-density at large house (3500, 5, 4): -11.002np.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 , 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() | Wait time between Poisson events (memoryless) | stats.expon(scale=1/lam) |
, | |
| Gamma() | Wait time for events; prior for rates | stats.gamma(a=alpha, scale=1/beta) |
, | |
| Beta() | Probability / conversion rate; prior for | stats.beta(alpha, beta) |
, | |
| Log-normal() | Multiplicative quantities: revenue, prices | stats.lognorm(s=sigma, scale=np.exp(mu)) |
, | |
| Negative Binomial() | Overdispersed counts (Var Mean) | stats.nbinom(n=r, p=p) |
, | |
| Multinomial() | Category counts across classes | stats.multinomial(n, p) |
, |
Pay close attention to scipy.stats parameter conventions! For Exponential and Gamma, SciPy uses scale = 1 / rate rather than the rate or . For Log-normal, s is the standard deviation of and scale is , where is the mean of . Verify all six families in code:
expon_d = stats.expon(scale=1 / 0.25) # rate lambda = 0.25 events/mingamma_d = stats.gamma(a=4, scale=1 / 0.5) # shape=4, rate=0.5 -> mean 8beta_d = stats.beta(a=12, b=88) # 12% conversion ratelognorm_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 = 15multinom_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}")Expon(lam=0.25): mean=4.00, P(X>4)=0.3679Gamma(a=4, b=0.5): mean=8.00, var=16.00Beta(12, 88): mean=0.120, std=0.0323LogNorm(3.5, 0.6): median=33.12, mean=39.65NegBin(r=5, p=0.25): mean=15.00, var=60.00Multinom PMF [5,3,2]: 0.0850Notice two handy facts in that output: for LogNorm(3.5, 0.6), the median is while the mean is pulled higher to 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 (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 itself as a random variable with a probability distribution representing your state of knowledge. You start with a prior , observe data with likelihood , and apply Bayes’ theorem to obtain the posterior :
The denominator 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 | 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 |
| Interval output | Confidence interval (procedure coverage) | Credible interval (direct ) |
| Direct decision metric | p-value (tail area assuming ) | 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.
Conjugate priors and sequential updating
Section titled “Conjugate priors and sequential updating”Computing the normalizing integral 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() | probability | ||
| Poisson() | rate | (rate ) | |
| Normal( known) | mean | (precision-weighted average) | |
| Multinomial() | probabilities |
In a Beta–Binomial model, and act as pseudo-counts: starting with (uniform over ) and seeing conversions out of visitors simply adds to and to . 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()n=0 k=0 -> Beta(2, 18) mean=0.1000n=20 k=1 -> Beta(3, 37) mean=0.0750n=200 k=27 -> Beta(29, 191) mean=0.1318n=2000 k=247 -> Beta(249, 1771) mean=0.1233
With visitors the prior ( pseudo-observations) still pulls the estimate strongly toward 10%. By , 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 satisfies . 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 lies between and .
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 rather than the parameter , integrate over parameter uncertainty to form the posterior predictive distribution:
In code, sampling from the posterior predictive takes two lines: draw from the posterior, then draw from the likelihood given . 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) priorpost_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 visitorsp_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)}")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 exactly, which produces dangerously overconfident forecasts when 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 rather than a full distribution. Two principles dominate ML:
- Maximum Likelihood Estimation (MLE) picks to maximize the data likelihood (equivalently, minimize negative log-likelihood):
- Maximum A Posteriori (MAP) estimation picks the mode of the posterior, adding the log-prior to the log-likelihood:
Now plug in a linear regression model with independent zero-mean priors on the weights:
- Gaussian prior : . Maximizing the log-posterior is identical to minimizing: Gaussian MAP is literally Ridge (L2) regression with penalty ! A tighter prior (smaller ) means stronger regularization.
- Laplace prior : . Maximizing the log-posterior minimizes: 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, 3mle_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}")3/3 conversions -> MLE: 1.000 | MAP: 0.308 | Post mean: 0.333MLE 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 has no closed form.
Markov Chain Monte Carlo (MCMC) solves this without ever computing . Instead, it constructs a Markov chain whose stationary distribution is the posterior and collects samples from it. The foundational algorithm is Metropolis–Hastings:
- Start at an initial parameter vector .
- At step , propose a candidate , where (a symmetric random-walk proposal).
- Compute the log-acceptance ratio (note how cancels completely!):
- Draw . If , accept ; otherwise stay at .
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 is too tiny, the chain accepts 95%+ of proposals but barely moves; if 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——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_500chain = np.empty(n_steps)cur = 0.5cur_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}")Acceptance rate: 0.533Exact Beta(6,14): mean=0.3000, std=0.1000MH MCMC samples: mean=0.2968, std=0.0983With 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 as:
A sure event () carries bits of surprise. A fair coin flip () carries bit. A 1-in-16 event carries 4 bits. Using the natural logarithm instead of measures information in nats (the unit used by PyTorch and scikit-learn losses).
Shannon entropy is the expected surprise of a discrete random variable :
Entropy is maximized by the uniform distribution ( for 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")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 bitsSame rating entropy in nats: 1.3984 natsBecause 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 (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 and a model’s predicted distribution .
- Cross-entropy is the average code length when data comes from but you encode it using . In classification, minimizing log-loss (binary or categorical cross-entropy) minimizes .
- Kullback–Leibler (KL) divergence (relative entropy) is the extra information lost when approximating with : By Gibbs’ inequality, if and only if . Because 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: , and if where , KL explodes to .
- Jensen–Shannon (JS) divergence fixes both issues by averaging KL to the midpoint :
JS divergence is symmetric, always finite, and bounded between and (or and in base 2).
scipy.spatial.distance.jensenshannon(p, q)returns the JS distance , so squaring it gives JS divergence! - Mutual information (MI) measures how much knowing reduces uncertainty about —equivalently, the KL divergence between the joint distribution and the product of marginals: if and only if and 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) # natsce_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 MIrng = 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}")H(P)=0.8018 | H(P,Q)=0.9856 | H(P,Q)-H(P)=0.1838KL(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.6247Look 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).
Worked examples
Section titled “Worked examples”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 ; 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}")Days: 731 | Mean: 20.35 | Variance: 104.04Variance / Mean ratio: 5.11The variance is more than five times the mean, driven by weekly cycles, holiday peaks and promotions. A Poisson model with 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 has and . Solving for gives the method-of-moments starter , 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})")MoM init: r=4.949, p=0.1956NB MLE: r=7.244, mu=20.35, p=0.2625Log-likelihood -> Poisson: -3227.3 | NegBin: -2582.6 (gain +644.7)Optimizing over 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 ().
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()P(orders >= 40) -> Observed: 0.0301 | Poisson: 0.000076 | NB: 0.0298
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 instead of ; in SciPy, is the success probability and counts failures, so . - Using
sf(40)instead ofsf(39)for discrete : becausesf(k)computes , discrete inclusive tails requiresf(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 , 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 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}")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 —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_crel_lift = abs_diff / draws_cprob_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}")P(treatment > control): 0.9937Absolute lift 95% CrI: [0.0034, 0.0277]Relative lift 95% CrI: [3.1%, 29.0%]Expected loss (ship T): 0.000013 | (keep C): 0.015508There 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()
Common mistakes:
- Reading 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 ) 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 ) 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 () 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))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.741Adjustable 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 from the population of all 30 products rather than guessing them by hand. Matching the sample mean and variance of the product rates to a Beta distribution gives:
m_rate = prod_rev["raw_rate"].mean()v_rate = prod_rev["raw_rate"].var(ddof=1)strength = m_rate * (1 - m_rate) / v_rate - 1alpha0 = m_rate * strengthbeta0 = (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))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.728Look 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}")New item (2/2) raw=1.000 -> EB=0.704Small hit (18/20) raw=0.900 -> EB=0.758Proven bestseller (160/200) raw=0.800 -> EB=0.781Empirical 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 then mixes sampling noise with true between-product variance; for very uneven , fit a Beta–Binomial MLE instead.
- Forgetting that the shrinkage formula is the posterior mean of .
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 and standardize five numeric house features so the intercept separates cleanly and all weights share one prior scale . Under and , setting the gradient of the log-posterior to zero yields:
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-pricetau2 = 0.002 # prior variance on each standardized slopelam = 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}")lambda = sigma^2 / tau^2 = 20.0Max |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.19179The 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 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 * alphaalpha_l1 = 0.03lam1 = len(y_c) * alpha_l1w_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}")Feature Gaussian MAP Laplace MAP sklearn Lassosqft +0.3568 +0.3388 +0.3388bedrooms -0.0163 +0.0000 +0.0000bathrooms +0.0536 +0.0238 +0.0238condition +0.1429 +0.1085 +0.1085distance_to_center_km -0.1918 -0.1533 -0.1533Directly 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 along with the slopes: shifting
yby a constant should shift the intercept without shrinking it toward zero, which is why we centeredy(or leave unpenalized). - Forgetting the factor in scikit-learn’s
Lasso(alpha=...)objective compared to the unaveraged sum of squared errors inRidge(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})")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, where . Using np.logaddexp(0.0, z) computes without overflow. Place a weakly informative 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_000chain = 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}]" )Acceptance rate: 0.378MCMC 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_newp_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()High-risk customer churn P: mean=0.445, 95% CrI=[0.326 0.564]
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 to0.0immediately. - 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 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)) 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.009avg_session_minutes 0.052 0.007 logins_last_30d 0.096 0.005Look 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 , and compute both 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))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.151The 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()
Common mistakes:
- Computing KL divergence on raw histogram counts without smoothing: a single empty bin in the reference distribution makes .
- Confusing
scipy.spatial.distance.jensenshannon(which returns , the JS distance) with JS divergence ().
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
| Confusing with | 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 |
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 |
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 when you want a symmetric, bounded drift score |
| Penalizing the intercept in MAP / Ridge | Predictions are systematically biased toward zero | Center 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 |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- 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,
gzipandzstd. - 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.
Summary
Section titled “Summary”- 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.
Self-check questions
Section titled “Self-check questions”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: . Because defects are rare (low base rate), false alarms outnumber true alarms.
Q2. Suppose . Does that prove and are independent? What measure can detect non-linear dependence?
Answer
No. Zero covariance only rules out linear association; for example, and have zero covariance yet are completely dependent. Mutual information equals zero if and only if and 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 that lets variance exceed the mean (), capturing heavy busy-day tails accurately.
Q4. You start with a 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 . Its posterior mean is .
Q5. Why is a posterior predictive interval wider than a plug-in prediction interval that fixes ?
Answer
A plug-in interval accounts only for sampling randomness of future observations assuming is known exactly. The posterior predictive distribution integrates over the posterior uncertainty in as well, combining both parameter uncertainty and outcome randomness.
Q6. In linear regression with noise variance , how does the Ridge penalty relate to the prior variance in a Gaussian MAP model, and what prior corresponds to Lasso?
Answer
For a zero-mean Gaussian prior , the MAP penalty is : a smaller prior variance means stronger L2 regularization. Replacing the Gaussian prior with a Laplace prior yields an L1 penalty, which corresponds to Lasso regression.
Q7. Why does the Metropolis–Hastings acceptance ratio never require computing the marginal likelihood ?
Answer
Because the acceptance ratio divides by . The constant 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 , and the true data entropy does not depend on the model’s parameters. Therefore any parameter update that decreases cross-entropy decreases 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 whenever the reference histogram has a zero-count bin where new data appears. Jensen–Shannon divergence averages KL to the midpoint , so it is always finite, symmetric and bounded between and (or bit), making alert thresholds easy to calibrate.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- 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.