Probability, Bayesian and information theory
This sheet covers probability identities, the core distribution families with scipy.stats parameterizations, conjugate Bayesian updating, MLE vs. MAP regularization, Metropolis–Hastings MCMC, and information-theoretic metrics for ML and drift detection. All blocks share one session using data/sales.csv, data/ab_test.csv, data/houses.csv, data/sensors.csv, and data/customers.csv:
import numpy as npimport pandas as pdfrom scipy import statsfrom scipy.spatial.distance import jensenshannonfrom scipy.special import rel_entrfrom sklearn.feature_selection import mutual_info_classiffrom sklearn.linear_model import Ridge
sales = pd.read_csv("data/sales.csv")ab = pd.read_csv("data/ab_test.csv")houses = pd.read_csv("data/houses.csv")sensors = pd.read_csv("data/sensors.csv")customers = pd.read_csv("data/customers.csv")Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Notes |
|---|---|---|
| invert a conditional probability | Bayes’ theorem | always track the base rate |
| model overdispersed event counts () | Negative Binomial (stats.nbinom) |
Poisson assumes |
| update a conversion rate with Beta–Binomial | conjugate; closed-form posterior | |
| update an event rate with Gamma–Poisson | scipy.stats.gamma(a, scale=1/rate) |
|
| Bayesian A/B probability treatment beats control | Monte Carlo draws from both Beta posteriors | also compute expected loss |
| shrink noisy small-sample averages toward a prior | empirical Bayes / hierarchical shrinkage | |
| connect Ridge / Lasso to Bayesian priors | MAP with Gaussian prior L2, Laplace L1 | for Ridge |
| sample a non-conjugate posterior | Metropolis–Hastings MCMC | tune proposal width for ~23–44% accept |
| measure uncertainty of a discrete distribution | Shannon entropy stats.entropy(p, base=2) |
bits (base 2) or nats (base ) |
| measure distribution drift vs. | KL rel_entr(p, q).sum() or JS jensenshannon(p, q)**2 |
JS is symmetric and finite on zeros |
| rank nonlinear feature–target dependence | mutual_info_classif / mutual_info_regression |
iff independent |
Probability axioms and rules
Section titled “Probability axioms and rules”| Rule | Formula | Condition / Note |
|---|---|---|
| Complement | ||
| Addition (inclusion–exclusion) | subtract overlap unless disjoint | |
| Conditional probability | requires | |
| Product (chain) rule | equals iff independent | |
| Law of total probability | partitions the sample space | |
| Bayes’ theorem | posterior likelihood prior | |
| Linearity of expectation | holds even when are dependent | |
| Variance identity | ||
| Sum of two random variables | if independent | |
| Law of total expectation | useful for hierarchical models |
Distribution reference
Section titled “Distribution reference”Discrete and continuous families
Section titled “Discrete and continuous families”| Family | Support | PMF / PDF | Mean | Variance | scipy.stats call |
|---|---|---|---|---|---|
| Bernoulli() | stats.bernoulli(p) |
||||
| Binomial() | stats.binom(n, p) |
||||
| Poisson() | stats.poisson(mu=lam) |
||||
| Geometric() | stats.geom(p) |
||||
| Neg. Binomial() | stats.nbinom(r, p) |
||||
| Multinomial() | stats.multinomial(n, p) |
||||
| Uniform() | stats.uniform(loc=a, scale=b-a) |
||||
| Exponential() | stats.expon(scale=1/lam) |
||||
| Gamma( rate) | stats.gamma(a=alpha, scale=1/beta) |
||||
| Beta() | stats.beta(alpha, beta) |
||||
| Normal() | stats.norm(loc=mu, scale=sigma) |
||||
| Log-normal() | stats.lognorm(s=sigma, scale=np.exp(mu)) |
daily_orders = sales.groupby("order_date")["order_id"].nunique().to_numpy()mu, var = float(daily_orders.mean()), float(daily_orders.var(ddof=1))# Method-of-moments Negative Binomial fit: var = mu + mu^2 / rr_nb = mu**2 / (var - mu)p_nb = r_nb / (r_nb + mu)ll_pois = float(stats.poisson(mu=mu).logpmf(daily_orders).sum())ll_nb = float(stats.nbinom(r_nb, p_nb).logpmf(daily_orders).sum())
print(f"daily orders: mean={mu:.2f}, var={var:.2f}, dispersion={var / mu:.2f}")print(f"log-likelihood: Poisson={ll_pois:.1f}, NegBin={ll_nb:.1f}")daily orders: mean=20.35, var=104.04, dispersion=5.11log-likelihood: Poisson=-3227.3, NegBin=-2597.8Conjugate priors and Bayesian updating
Section titled “Conjugate priors and Bayesian updating”A prior is conjugate to a likelihood when the posterior belongs to the same distribution family, turning Bayes’ rule into simple parameter addition.
| Likelihood | Prior | Posterior | Posterior mean |
|---|---|---|---|
| Binomial ( successes in ) | |||
| Poisson ( events over units) | (rate ) | ||
| Normal (known , sample mean , size ) | , | precision-weighted average of and | |
| Multinomial (counts ) |
summary = ab.groupby("group")["converted"].agg(["sum", "count"])kc, nc = int(summary.loc["control", "sum"]), int(summary.loc["control", "count"])kt, nt = int(summary.loc["treatment", "sum"]), int(summary.loc["treatment", "count"])
# Weakly informative Beta(1, 1) priorpost_c = stats.beta(1 + kc, 1 + nc - kc)post_t = stats.beta(1 + kt, 1 + nt - kt)rng = np.random.default_rng(42)sc = post_c.rvs(50_000, random_state=rng)st = post_t.rvs(50_000, random_state=rng)
prob_t_wins = float(np.mean(st > sc))exp_loss_ship_t = float(np.mean(np.maximum(sc - st, 0.0)))ci_lift = np.quantile(st - sc, [0.025, 0.975])print(f"P(treatment > control) = {prob_t_wins:.4f}")print(f"95% credible interval (t - c): [{ci_lift[0]:.4f}, {ci_lift[1]:.4f}]")print(f"expected loss if shipping treatment: {exp_loss_ship_t:.6f}")P(treatment > control) = 0.993795% credible interval (t - c): [0.0034, 0.0277]expected loss if shipping treatment: 0.000013MLE vs. MAP and regularization
Section titled “MLE vs. MAP and regularization”- MLE (Maximum Likelihood): .
- MAP (Maximum A Posteriori): .
| Noise likelihood | Weight prior | Negative log-posterior objective | Equivalent ML model |
|---|---|---|---|
| Gaussian | flat (improper) | OLS linear regression | |
| Gaussian | , | Ridge regression (L2) | |
| Gaussian | Laplace | , | Lasso regression (L1) |
| Bernoulli (logit) | binary cross-entropy | L2 LogisticRegression () |
X_raw = houses[["sqft", "bedrooms", "bathrooms", "condition"]].to_numpy(dtype=float)X = (X_raw - X_raw.mean(0)) / X_raw.std(0)y = np.log(houses["price"].to_numpy(dtype=float))y_c = y - y.mean()
lam = 25.0 # sigma^2 / tau^2w_map = np.linalg.solve(X.T @ X + lam * np.eye(X.shape[1]), X.T @ y_c)w_ridge = Ridge(alpha=lam, fit_intercept=False).fit(X, y_c).coef_print("MAP weights: ", np.round(w_map, 5))print("matches Ridge:", np.allclose(w_map, w_ridge))MAP weights: [ 0.33573 -0.01172 0.05283 0.10692]matches Ridge: TrueMetropolis–Hastings MCMC
Section titled “Metropolis–Hastings MCMC”When a posterior has no conjugate closed form, Metropolis–Hastings draws correlated samples from without computing the normalizing constant:
- Propose (symmetric random walk: ).
- Compute log acceptance ratio (add if asymmetric).
- Accept if for , else keep .
| Diagnostic | Healthy target | What to fix if off |
|---|---|---|
| Burn-in | discard initial 10–25% of draws | trace still trending away from start |
| Acceptance rate (1D / multi-D) | ~40–50% (1D), ~23% (high-D) | too high widen step; too low shrink step |
| Trace plot | fuzzy horizontal caterpillar | sticky plateaus poor mixing; reparameterize |
| Split- (multi-chain) | run longer or fix multimodal parameterization |
def log_post(theta: float) -> float: if not (0.0 < theta < 1.0): return -np.inf return float( stats.beta.logpdf(theta, 2.0, 2.0) + stats.binom.logpmf(18, 50, theta) )
chain = np.empty(6_000)cur, accepted = 0.5, 0cur_lp = log_post(cur)for i in range(len(chain)): prop = cur + float(rng.normal(0.0, 0.15)) prop_lp = log_post(prop) if np.log(rng.random()) < prop_lp - cur_lp: cur, cur_lp = prop, prop_lp accepted += 1 chain[i] = cur
draws = chain[1_000:] # discard burn-inexact = stats.beta(2 + 18, 2 + 32)print(f"accept rate: {accepted / len(chain):.3f}")print(f"MCMC mean={draws.mean():.4f}, std={draws.std():.4f}")print(f"Exact mean={exact.mean():.4f}, std={exact.std():.4f}")accept rate: 0.462MCMC mean=0.3734, std=0.0681Exact mean=0.3704, std=0.0651Information theory
Section titled “Information theory”| Measure | Formula (discrete) | Properties & ML use | Python |
|---|---|---|---|
| Shannon entropy | ; decision-tree impurity, coding lower bound | stats.entropy(p, base=2) |
|
| Cross-entropy | ; classification loss | -np.sum(p * np.log(q)) |
|
| KL divergence | , asymmetric; if where | rel_entr(p, q).sum() |
|
| Jensen–Shannon divergence | symmetric, bounded in (or base 2) | jensenshannon(p, q) ** 2 |
|
| Mutual information | ; captures linear and nonlinear dependence | mutual_info_classif(X, y) |
s3 = sensors.loc[sensors["sensor_id"] == "S3", ["timestamp", "temperature_c"]].dropna()w1 = s3.loc[s3["timestamp"] < "2024-05-08", "temperature_c"].to_numpy()w2 = s3.loc[s3["timestamp"] >= "2024-05-08", "temperature_c"].to_numpy()edges = np.linspace(min(w1.min(), w2.min()), max(w1.max(), w2.max()), 16)p1 = np.histogram(w1, bins=edges)[0] + 1e-6 # Laplace smoothing avoids log(0)p2 = np.histogram(w2, bins=edges)[0] + 1e-6p1, p2 = p1 / p1.sum(), p2 / p2.sum()
kl_nats = float(rel_entr(p1, p2).sum())js_div = float(jensenshannon(p1, p2) ** 2)
mi_cols = ["tenure_months", "monthly_charges", "support_tickets", "logins_last_30d"]mi = mutual_info_classif( customers[mi_cols], customers["churned"], random_state=42)print(f"S3 drift (week 1 vs week 2): KL={kl_nats:.3f} nats, JSD={js_div:.3f}")print("MI:", ", ".join(f"{c}={v:.4f}" for c, v in zip(mi_cols, mi)))S3 drift (week 1 vs week 2): KL=2.820 nats, JSD=0.212MI: tenure_months=0.0751, monthly_charges=0.0133, support_tickets=0.0196, logins_last_30d=0.0023Gotchas
Section titled “Gotchas”| Trap | Symptom | Fix |
|---|---|---|
confusing scale with rate in stats.gamma / stats.expon |
posterior mean is inverted ( instead of ) | pass scale=1 / rate |
| ignoring base rate in Bayes’ theorem | “95% accurate test” looks like 95% disease probability | compute using prevalence |
| reading a 95% confidence interval as a 95% credible interval | wrong interpretation of frequentist coverage | use a Bayesian posterior for |
| computing likelihoods as raw products | underflows to 0.0 at |
sum log-likelihoods (logpdf / logpmf) |
passing unsmoothed histograms to rel_entr(p, q) |
returns inf whenever any bin has q == 0 |
add small pseudocounts or use jensenshannon(p, q) ** 2 |
| treating KL divergence as symmetric | differs sharply from | document reference vs. model , or use JSD |
forgetting to square jensenshannon(p, q) |
SciPy returns JS distance (), not divergence | square it for divergence; pass base=2 for bits |
| skipping burn-in or acceptance checks in MCMC | biased posterior mean or stuck chain | discard burn-in, check acceptance rate and trace plots |
forgetting stats.nbinom(r, p) counts failures |
wrong mean when using standard textbook | check mean = r * (1 - p) / p, var = r * (1 - p) / p**2 |