48. Probability, Bayesian statistics and information theory — Cheat sheet
The essentials of module 48 on one page. Every runnable block is checked against its output and shares one session:
import math
import numpy as npimport pandas as pdfrom scipy import statsfrom scipy.spatial.distance import jensenshannonfrom sklearn.feature_selection import mutual_info_classiffrom sklearn.linear_model import Ridge
customers = pd.read_csv("data/customers.csv")houses = pd.read_csv("data/houses.csv")ab = pd.read_csv("data/ab_test.csv")Quick lookup
Section titled “Quick lookup”| I want to… | Use… |
|---|---|
| count combinations / permutations | math.comb(n, k) / math.perm(n, k) |
| joint table | pd.crosstab(x, y, normalize="all") |
| conditional table | pd.crosstab(x, y, normalize="index") |
| sample covariance / correlation matrix | np.cov(X, rowvar=False, ddof=1) / np.corrcoef(X, rowvar=False) |
| multivariate normal log-density | stats.multivariate_normal(mean=mu, cov=cov).logpdf(x) |
| Exponential with rate | stats.expon(scale=1 / lam) |
| Gamma with shape , rate | stats.gamma(a=alpha, scale=1 / beta) |
| Beta for a probability in | stats.beta(alpha, beta) |
| Log-normal with | stats.lognorm(s=sigma, scale=np.exp(mu)) |
| Negative Binomial with dispersion , mean | stats.nbinom(n=r, p=r / (r + mu)) |
| Multinomial for -class counts | stats.multinomial(n=n, p=probs) |
| discrete inclusive tail | dist.sf(k - 1) |
| Beta–Binomial posterior | stats.beta(a0 + k, b0 + n - k) |
| Gamma–Poisson posterior (rate ) | stats.gamma(a=a0 + x.sum(), scale=1 / (b0 + len(x))) |
| 95% equal-tailed credible interval | post.ppf([0.025, 0.975]) or np.quantile(draws, [0.025, 0.975]) |
| 95% HPD interval from MCMC/MC draws | shortest contiguous window of int(0.95 * len(s)) sorted draws |
| Bayesian A/B win probability | (draws_t > draws_c).mean() |
| expected loss of shipping treatment | np.maximum(draws_c - draws_t, 0.0).mean() |
| Gaussian MAP / Ridge linear weights | np.linalg.solve(X.T @ X + lam * np.eye(p), X.T @ y_c) |
| stable logistic log-likelihood | np.sum(y * z - np.logaddexp(0.0, z)) |
| Shannon entropy in bits / nats | stats.entropy(p, base=2) / stats.entropy(p) |
| KL divergence (nats) | stats.entropy(p, q) |
| Jensen–Shannon divergence (nats) | jensenshannon(p, q) ** 2 |
| non-linear feature–target dependence | mutual_info_classif(X, y) / mutual_info_regression(X, y) |
Probability laws and joint distributions
Section titled “Probability laws and joint distributions”| Law | Formula | Notes |
|---|---|---|
| Conditional probability | Requires | |
| Law of total probability | partitions | |
| Bayes’ theorem | Flips conditioning; uses base rate | |
| Independence | Implies (converse is false) |
joint = pd.crosstab(customers["plan"], customers["contract"], normalize="all")marg = np.outer(joint.sum(axis=1), joint.sum(axis=0))gap = np.abs(joint.to_numpy() - marg).max()print(f"comb(10,3)={math.comb(10, 3)} | max |P(X,Y)-P(X)P(Y)|={gap:.4f}")comb(10,3)=120 | max |P(X,Y)-P(X)P(Y)|=0.0086Distribution families in scipy.stats
Section titled “Distribution families in scipy.stats”| Family | Support | SciPy call | Mean | Variance |
|---|---|---|---|---|
| Exponential() | stats.expon(scale=1/lam) |
|||
| Gamma() | stats.gamma(a=alpha, scale=1/beta) |
|||
| Beta() | stats.beta(alpha, beta) |
|||
| Log-normal() | stats.lognorm(s=sigma, scale=np.exp(mu)) |
|||
| Negative Binomial() | stats.nbinom(n=r, p=p) |
|||
| Multinomial() | stats.multinomial(n, p) |
nb = stats.nbinom(n=5, p=5 / (5 + 20)) # dispersion r=5, mean mu=20ln = stats.lognorm(s=0.5, scale=np.exp(3.0))print( f"NegBin mean={nb.mean():.1f}, var={nb.var():.1f}" f" | LogNorm mean={ln.mean():.2f}, med={ln.median():.2f}")NegBin mean=20.0, var=100.0 | LogNorm mean=22.76, med=20.09Conjugate priors and Bayesian updating
Section titled “Conjugate priors and Bayesian updating”| Likelihood | Conjugate prior | Posterior update | Posterior mean |
|---|---|---|---|
| Binomial() | |||
| Poisson() | |||
| Normal( known) | |||
| Multinomial() |
rng = np.random.default_rng(42)g = ab.groupby("group")["converted"].agg(["sum", "count"])kc, nc = int(g.loc["control", "sum"]), int(g.loc["control", "count"])kt, nt = int(g.loc["treatment", "sum"]), int(g.loc["treatment", "count"])dc = stats.beta(1 + kc, 1 + nc - kc).rvs(20_000, random_state=rng)dt = stats.beta(1 + kt, 1 + nt - kt).rvs(20_000, random_state=rng)loss_t = np.maximum(dc - dt, 0.0).mean()print(f"P(T>C)={(dt > dc).mean():.4f} | expected loss(T)={loss_t:.6f}")P(T>C)=0.9929 | expected loss(T)=0.000018MLE, MAP and regularization
Section titled “MLE, MAP and regularization”| Method | Objective maximized | Equivalent ML loss | Effect on weights |
|---|---|---|---|
| MLE | Unregularized OLS / Logit | Unbiased, higher variance on small | |
| Gaussian MAP | Ridge () | Smooth shrinkage toward 0 | |
| Laplace MAP | Lasso () | Sparse exact zeros |
X = houses[["sqft", "bedrooms", "bathrooms"]].to_numpy(dtype=float)X = (X - X.mean(axis=0)) / X.std(axis=0)y = np.log(houses["price"].to_numpy(dtype=float))lam = 10.0 # sigma^2 / tau^2w_map = np.linalg.solve(X.T @ X + lam * np.eye(X.shape[1]), X.T @ (y - y.mean()))w_ridge = Ridge(alpha=lam).fit(X, y).coef_print(f"max |MAP - Ridge| = {np.max(np.abs(w_map - w_ridge)):.2e}")max |MAP - Ridge| = 4.44e-16Metropolis–Hastings MCMC recipe
Section titled “Metropolis–Hastings MCMC recipe”Work in log-space, discard burn-in, and tune step_scale so acceptance lands around 0.25–0.45:
rng = np.random.default_rng(42)target = stats.beta(5, 15)cur, cur_lp = 0.5, float(target.logpdf(0.5))chain, acc = np.empty(4000), 0for t in range(4000): prop = cur + rng.normal(0.0, 0.16) if 0.0 < prop < 1.0: prop_lp = float(target.logpdf(prop)) if np.log(rng.random()) < prop_lp - cur_lp: cur, cur_lp, acc = prop, prop_lp, acc + 1 chain[t] = curprint( f"acc={acc / 4000:.3f} | MH mean={chain[1000:].mean():.4f}" f" | exact={target.mean():.4f}")acc=0.560 | MH mean=0.2509 | exact=0.2500Information theory and drift metrics
Section titled “Information theory and drift metrics”| Measure | Formula | Range | Symmetric? |
|---|---|---|---|
| Shannon entropy | — | ||
| Cross-entropy | No | ||
| KL divergence | No | ||
| JS divergence | Yes | ||
| Mutual information | Yes |
p, q = np.array([0.7, 0.2, 0.1]), np.array([0.4, 0.4, 0.2])mi_age = mutual_info_classif( customers[["age"]], customers["churned"], random_state=42)[0]print( f"H(P)={stats.entropy(p, base=2):.3f}b | KL={stats.entropy(p, q):.3f}" f" | JS={jensenshannon(p, q) ** 2:.3f} | MI(age,churn)={mi_age:.4f}")H(P)=1.157b | KL=0.184 | JS=0.046 | MI(age,churn)=0.0110Gotchas
Section titled “Gotchas”- SciPy
scaleis inverse rate:stats.expon(scale=1 / lam)andstats.gamma(a=alpha, scale=1 / beta)take1 / rate, neverrate. - SciPy
lognormtakesexp(mu): usestats.lognorm(s=sigma, scale=np.exp(mu)), notloc=mu. - SciPy
nbinomuses failure counts: for dispersion and mean , passp = r / (r + mu), notmu / (r + mu). - Discrete
sf(k)is strict: equalsdist.sf(k - 1), notdist.sf(k). jensenshannon(p, q)returns distance: square it (** 2) to get JS divergence.- KL explodes on zeros: always add tiny smoothing (e.g.
1e-6) to shared histogram bins before callingstats.entropy(q, p). - MCMC underflows outside log-space: always sum
logpdf/logpmfand comparenp.log(u) < prop_lp - cur_lp. - Do not penalize the intercept: center
yor exclude the intercept column when matching Gaussian/Laplace MAP to Ridge/Lasso.