Bayesian inference: prior, posterior and conjugacy
Update priors into posterior and predictive distributions, summarize uncertainty, and connect MAP to regularization.
After this lesson you can
- Derive conjugate posterior and predictive distributions.
- Interpret credible intervals and compare them with frequentist confidence intervals.
- Compute posterior grids and relate MAP estimates to regularization.
- Apply sequential Bayesian updating.
Before you start
- 05Likelihood functionMaximum likelihood estimator (MLE)Numerically stable maximum likelihoodExponential familySufficient statisticConfidence interval and coverageBinomial proportion confidence intervals
- 04Conditional densityBeta and Dirichlet distributionsExponential, gamma and chi-squared distributionsJoint law and marginals
Motivation: three out of three
You have written a new detection rule for a static analyzer and test it against three known vulnerabilities. It detects all three. What is its detection rate? Previous lessons answer with the maximum likelihood estimator of a proportion: . The rule would be perfect. Nobody believes it, for three reasons this lesson turns into mathematics.
- Uncertainty is missing. With , data are compatible with a rate of (three successive successes have probability ), and also . MLE gives a number without saying how much to trust it.
- Prior knowledge is missing. Before seeing data you know things: similar rules detect 70% to 95%, and exactly 1 would be extraordinary. MLE ignores this by construction.
- A useful decision answer is missing. To decide whether to publish, you need something like “what is the probability the rate exceeds ?” or “what is the probability of detecting the next one?” MLE answers and : it bets everything on never failing.
Bayesian inference addresses all three with one idea: treat parameter as uncertain and describe uncertainty with a probability distribution. Before data you have a prior distribution encoding knowledge; data update it using Bayes’s rule; the result is a posterior distribution over from which everything else follows: estimates, intervals, hypothesis probabilities and predictions.
There are practical reasons to master this now. Laplace smoothing in n-gram language models is a Bayesian predictive distribution (see n-gram smoothing). Ridge and lasso are Bayesian estimators in disguise (regularization as MAP). Bandit Thompson sampling acts on beta posteriors (Thompson sampling). When the posterior lacks closed form, modern Bayesian inference is devoted to computing it: MCMC and variational inference build on this lesson.
This lesson covers basics: the update rule and its arithmetic in conjugate models, posterior summaries (point and interval), predictive distribution, grid calculation for any low-dimensional model, the regularization connection and sequential updating. Prior choice, model comparison and asymptotic justification are covered in the next lesson.
Prior, likelihood and posterior
Start with a statistical model with . Until now was an unknown constant and data the only randomness. The Bayesian view adds a distribution over describing uncertainty about before data. Probability here measures degree of belief, not relative frequency, and Bayes’s rule for conditional densities tells how to revise it.
Three readings of that line to make clear from the start.
- The posterior is the complete inferential object. Any question about (, interval or estimate) is answered with it. There is no unique “Bayesian estimator”: there is one posterior and many summaries.
- Likelihood is not a density in . Its integral over need not equal 1. Its product with the prior can be normalized, which is why appears as a constant.
- Only shape matters, not the constant. Knowing up to a factor independent of suffices: the posterior kernel. Since a density is determined by its kernel (its normalizing constant is unique), recognizing a known family’s kernel computes the posterior. Every conjugacy result in this lesson uses that trick.
The detection rule with five possible values
To see the machinery without calculus, suppose can take only five values, all equally plausible before data. After three detections in three trials, .
| prior | likelihood | prior × likelihood | posterior | |
|---|---|---|---|---|
| 0.1 | 0.2 | 0.001 | 0.0002 | 0.0008 |
| 0.3 | 0.2 | 0.027 | 0.0054 | 0.0220 |
| 0.5 | 0.2 | 0.125 | 0.0250 | 0.1020 |
| 0.7 | 0.2 | 0.343 | 0.0686 | 0.2800 |
| 0.9 | 0.2 | 0.729 | 0.1458 | 0.5951 |
The fourth column sums to : that is , the constant to divide by. The posterior allocates mass among the five values proportional to , leaving under % probability on (not ruled out, just very unlikely). This is already a grid approximation; below we make it continuous and serious.
With and a uniform prior, posterior is proportional to on . That family has a name. Probability the rate exceeds is , posterior mean is , and a 95% equal-tailed interval is . The three motivating questions now have answers, none “100%.”
Beta-binomial: the posterior in one line
The simplest genuinely useful model has independent Bernoulli trials with success probability . With successes, and . For the natural prior family is beta: , density .
Proof
The posterior kernel is the product of kernels: , the kernel of . A density is fixed by its kernel, so this is the posterior. Evidence is the full-product integral: .
∎Updating is arithmetic on two counters: counts successes and failures. For the detection rule with a uniform prior (), gives with density : the previous table’s posterior, continuous.
The prior as pseudo-observations
The mean of posterior is . Compare MLE : it is the same as adding fictitious successes and failures to real data. Prior hyperparameters are pseudo-observations, and their sum is prior effective sample size. Rewritten, posterior mean is a convex combination of prior mean and observed proportion:
Prior weight is : it equals at and declines as as grows. A prior (4 pseudo-observations) is forgotten with a few dozen data points; (100 pseudo-observations) weighs as much as 100 real trials. Posterior variance is with posterior mean: it shrinks as , alongside the Cramér–Rao bound.
Conjugacy
Beta-binomial is no accident. Having posterior and prior in the same family makes everything calculation with hyperparameters.
A rigor warning: the definition trivially holds for “all distributions on .” Its usefulness requires to be parametric and small, with interpretable and easily computed . Four classic models:
| Model | Prior | Data | Posterior | Prior counts as |
|---|---|---|---|---|
| Bernoulli or binomial | successes in | successes and failures | ||
| Poisson | (shape, rate) | , | events in periods | |
| Normal, known | mean of observations | , formula below | observations with mean | |
| Multinomial of categories | counts | observations of category |
Proof
Likelihood is with . Multiplied by prior kernel this gives , the kernel of .
∎The pseudo-observation reading is the same: the prior is equivalent to events in periods. For hourly alerts with prior (mean 2), six hours with alerts give , mean : between prior and MLE .
The proof completes squares in the exponent of the product of two Gaussians, step by step in the exercises. Example: , , , and . Precisions are (prior) and (data), so and . Prior is worth observations versus nine real ones, so posterior mean lies closer to than .
Beta is the case. This models word frequencies, classifier classes and contingency tables. The kernel proof and predictive consequence (pseudo-count smoothing) are an exercise.
Why every exponential family has a conjugate prior
Conjugacy appearing in all four classic examples is no accident either. Recall an exponential family has densities , and an iid sample of size depends on data only through sufficient statistic .
Proof
Likelihood is . Multiplying by the prior kernel gives exponent , the same form with new hyperparameters. Factors do not depend on and enter the constant.
∎Hyperparameter counts pseudo-observations and is their fictitious mean sufficient statistic. For Bernoulli, , and , and the form gives , a : beta with pseudo-trials and pseudo-successes. Conjugacy is not a formula trick: it is sufficiency in the Bayesian world. Data enter posterior only through , the same summary sufficient for likelihood.
Summarizing the posterior
The posterior is a whole distribution; usually it needs a summary. Three natural point estimators are posterior mean , median and mode (MAP, studied separately). Each is optimal for a different loss: mean minimizes expected squared loss (this function of is a parabola minimized at the mean), median minimizes expected absolute error, and mode is the limit of 0–1 loss. This is the Bayes rule principle, covered in the decision lesson. For all four conjugate models mean has a closed form (above), while median and quantiles use standard functions (incomplete beta and gamma).
To quantify uncertainty, the analogue of a confidence interval is a credible interval.
Equal-tailed is easiest to calculate and transforms well (quantiles are equivariant under monotone functions). HPD is “best” in a precise sense.
Proof
Let be another set with equal posterior probability. Since both have mass , removing the intersection gives . Density on is at least and on less than , so
Adding to both ends, , and since , .
∎Consequences shown below. If posterior is unimodal, HPD is an interval with equal-density endpoints (unless it touches the support boundary, such as mode at ). If also symmetric, it equals the equal-tailed interval. If skewed, HPD is shorter: for at 90%, equal-tailed is (length ) and HPD (length ), 8% less. If posterior has two modes, HPD splits into two pieces, while equal-tailed includes the intermediate region the posterior considers implausible. There is a price: HPD is not invariant under reparameterization because the density acquires a Jacobian and level sets change. Equal-tailed is invariant.
The posterior predictive distribution
What you need is rarely ; usually it is a future observation . Estimating and predicting with treats as truth. Bayesian prediction averages over all possible values weighted by posterior plausibility.
This follows by marginalizing the joint: by conditional independence, then integrating . Prediction is always more dispersed than plug-in prediction, by total variance:
The second term is what plug-in ignores, zero only when the posterior has fully concentrated.
Beta-binomial. Probability of success on the next trial is . With uniform prior this is : Laplace’s rule of succession. After successes in trials, next success probability is not but : zero observed does not prove impossibility. For future trials, success count follows beta-binomial, with posterior , mean and variance
i.e. binomial variance multiplied by : overdispersion introduced by uncertainty about . With large the factor tends to ; with little information it is large. This distinguishes magenta and blue bars in the first figure.
Gamma-Poisson. With posterior , future count follows negative binomial: . Counts whose variance exceeds mean, impossible for Poisson, arise from a simple model: Poisson with an uncertain rate.
Normal with known variance. Predictive is : observation noise plus mean uncertainty. This is the Bayesian side of the prediction interval.
Dirichlet-multinomial. Probability the next observation is category is , with : observed frequencies smoothed with pseudo-counts. With this is Laplace “add-one” smoothing in naive Bayes classifiers and language models: an unseen word does not get zero probability.
Grid approximation
When posterior lacks closed form, the most honest and simplest option with few parameters is to evaluate the unnormalized posterior on a grid and normalize numerically.
This is the five-point table method with more points. Three details distinguish it from naive computation.
- Work in logs. With data, is order , below the smallest positive
float64(): the entire grid becomes 0 and normalization divides . Safely calculate and normalize with maximum subtraction (log-sum-exp): with . - The window must contain the mass and resolution the peak. A posterior concentrating as can hide between two coarse grid points. First inspect where mass lies using a cheap coarse grid.
- Cost grows as with dimension . With 100 points per parameter: evaluations for one parameter, for two, for four, for six. Instantaneous in 2D becomes days in 6D. This is the curse of dimensionality, why models with dozens or thousands of parameters need something else: MCMC, concentrating work in mass regions, or Laplace approximation.
A case with exact answer for measuring error: normal data with mean and standard deviation both unknown, with prior (flat in ; next lesson). Joint posterior is
and can be integrated: with , , so
The marginal posterior of is Student with degrees of freedom, centered at and scale : the 95% equal-tailed credible interval is exactly the classical interval from confidence intervals. This numerical coincidence (for that prior) joins statements of different kinds, revisited at the end.
The practical lesson: in 1D and 2D grid is excellent (a couple of NumPy lines, no formulas); beyond roughly 4 or 5 parameters it ceases to be practical. Another valuable use is checking a more sophisticated calculation (MCMC, Laplace approximation) against a reduced case.
MAP and regularization
One way to avoid the full posterior is to retain its peak.
With a uniform prior (in the parameterization used), MAP is MLE. An informed prior yields regularization. In a Gaussian linear model, :
Proof
Log posterior, up to constants, is . Multiplying by (without changing the minimizer) gives . For normal prior, . For Laplace, .
∎Useful intuition: ridge says coefficients are small (scale ), and lasso says most are near zero and some large (Laplace peak at 0). Stronger prior (smaller or ) means more penalty. A single datum makes this explicit: observe with . Gaussian-prior MAP is , proportional shrinkage; Laplace-prior MAP is soft threshold , exactly when . This gives lasso variable selection. Details and regularization paths are in ridge and lasso.
The figure reveals what MAP is not. MAP at zero does not mean posterior believes : with Laplace prior posterior mean is never exactly zero, and probability is modest even when MAP is pinned to 0. A point summary of a posterior is not the posterior.
A note on pseudo-counts: with , mode is , and posterior mean (equal to predictive) is . Laplace add-one smoothing is the predictive with , or MAP with . MAP with uniform prior is MLE: it smooths nothing.
Sequential updating
Data often arrive as a stream, and it is natural to reuse yesterday’s posterior as today’s prior.
Proof
By conditional independence, , so . Equality of processing routes follows from associativity and commutativity of multiplication: both accumulate the same product of factors over the prior, with the same normalizing constant.
∎This is sequential learning: today’s posterior is tomorrow’s prior. In conjugate models two numbers suffice: store and add 1 to the appropriate counter. Thompson sampling in a bandit does this: maintain a beta posterior per arm, draw a from each and play the largest, updating each arm’s posterior only with that arm’s observations.
Two cautions. First, sequential updating requires the same model for all data; if drifts over time add dynamics (Kalman filter or exponential forgetting of counters), otherwise posterior hardens and stops learning. Second, a prior assigning zero probability to a parameter value never recovers it: implies for all . Lindley’s Cromwell rule asks never to assign probability or to what is not logically impossible.
Credibility versus confidence
The two 95% intervals for one problem make different claims. With three detections in three trials, a uniform prior gives equal-tailed credible interval ; Wilson (see proportion intervals) gives and exact Clopper–Pearson . Similar, but answering different questions.
| Credibility | Confidence | |
|---|---|---|
| What is random | (for you, given data) | the interval, through samples |
| What it asserts | for every | |
| Depends on | model and prior | model and procedure |
| Guarantees | probability conditional on observations | long-run frequency over repeated samples |
Confidence is evaluated at fixed ; credibility at fixed data. A credible interval has no frequentist coverage guarantee: with uniform prior and , the 95% equal-tailed interval covers true % of the time when , % when , and never if (with the interval starts at , and with still farther right). But it has a different exact guarantee: if is actually drawn from the prior, coverage probability averaged over prior and data is , because
In this example, averaging frequentist coverage over gives exactly , with coverage oscillating in a sawtooth between and depending on . Both approaches coincide when prior is nearly flat relative to likelihood: in the normal model with prior , equality with the interval is exact (as seen), and asymptotically with much data and any prior not excluding truth, posterior becomes normal around MLE with variance inverse Fisher information, so intervals coincide (Bernstein–von Mises theorem in the next lesson). With few data and an informative prior, they need not.
Implementation from scratch
First, the four conjugate models, read as convex combinations. Everything is arithmetic on hyperparameters.
import numpy as np
def beta_binomial(a, b, x, n):
"""Posterior Beta(a + x, b + n - x) tras x éxitos en n ensayos."""
return a + x, b + (n - x)
def gamma_poisson(a, r, conteos):
"""Prior Gamma(forma a, tasa r): el posterior es Gamma(a + suma, r + n)."""
conteos = np.asarray(conteos)
return a + conteos.sum(), r + conteos.size
def normal_normal(m0, tau0_2, sigma2, y):
"""Media desconocida y varianza sigma2 conocida: media y varianza del posterior."""
y = np.asarray(y, dtype=float)
p0, pd = 1 / tau0_2, y.size / sigma2 # precisiones del prior y de los datos
p = p0 + pd # las precisiones se suman
return (p0 * m0 + pd * y.mean()) / p, 1 / p
def dirichlet_multinomial(alpha, conteos):
"""Dir(alpha + conteos); la predictiva es su media."""
post = np.asarray(alpha, dtype=float) + np.asarray(conteos)
return post, post / post.sum()
# 1. Regla de detección: 3 de 3, prior uniforme, y el informado Beta(17, 3) con 9 de 10
a, b = beta_binomial(1, 1, 3, 3)
print(f"Beta-binomial, uniforme y 3/3 : Beta({a}, {b}), media {a / (a + b):.3f}")
a, b = beta_binomial(17, 3, 9, 10)
w = 20 / (20 + 10)
print(f"Beta-binomial, Beta(17,3), 9/10: Beta({a}, {b}), media {a / (a + b):.4f} = "
f"{w:.3f} * 0.85 + {1 - w:.3f} * 0.9 = {w * 0.85 + (1 - w) * 0.9:.4f}")
# 2. Alertas por hora
a, r = gamma_poisson(2, 1, [3, 1, 4, 2, 5, 2])
print(f"Gamma-Poisson : Gamma({a}, {r}), media {a / r:.3f} (EMV {17 / 6:.3f})")
# 3. Media normal con varianza conocida
y = np.array([9, 15, 11, 13, 12, 10, 14, 12, 12])
m, v = normal_normal(10, 4, 9, y)
print(f"Normal-normal : media {m:.3f}, varianza {v:.3f}, desv. típica {np.sqrt(v):.3f}")
n0 = 9 / 4 # pseudo-observaciones del prior: sigma2 / tau0_2
print(f" como combinación convexa : {n0 / (n0 + 9):.3f} * 10 + {9 / (n0 + 9):.3f} * {y.mean():.0f} = {(n0 * 10 + 9 * y.mean()) / (n0 + 9):.3f}")
# 4. Palabras: 3 categorías con prior uniforme y recuentos (5, 2, 0)
post, pred = dirichlet_multinomial([1, 1, 1], [5, 2, 0])
print(f"Dirichlet-multinomial : {post}, predictiva {np.round(pred, 3)} (la categoría sin datos no tiene 0)")Notice no function contains an integral: conjugacy replaces calculus with counting. Now the general method: log-space grid with quantiles, HPD and predictive, checked against exact for the detection rule.
import numpy as np
from scipy import stats
def log_sum_exp(v):
m = v.max()
return m + np.log(np.exp(v - m).sum())
def posterior_rejilla(log_prior, log_lik, theta):
"""Masas por celda (suman 1) de log prior + log verosimilitud, sin salir del log hasta el final."""
lp = log_prior(theta) + log_lik(theta)
return np.exp(lp - log_sum_exp(lp))
def cuantil(theta, w, p):
"""Cuantil de las masas w: interpolación en la función de distribución acumulada."""
return np.interp(p, np.cumsum(w), theta)
def hpd_rejilla(theta, w, nivel=0.95):
"""HPD: las celdas de mayor masa hasta acumular el nivel (para un posterior unimodal, un intervalo)."""
orden = np.argsort(-w)
k = np.searchsorted(np.cumsum(w[orden]), nivel) + 1
sel = np.sort(theta[orden[:k]])
return sel[0], sel[-1]
theta = (np.arange(20000) + 0.5) / 20000 # 20 000 celdas en (0, 1)
x, n = 3, 3
w = posterior_rejilla(lambda t: np.zeros_like(t), # prior uniforme
lambda t: x * np.log(t) + (n - x) * np.log1p(-t), theta)
exacto = stats.beta(1 + x, 1 + n - x)
print("media rejilla %.4f exacta %.4f" % ((w * theta).sum(), exacto.mean()))
print("Pr(θ > 0.5) rejilla %.4f exacta %.4f" % (w[theta > 0.5].sum(), exacto.sf(0.5)))
print("colas iguales rejilla [%.3f, %.3f] exacto [%.3f, %.3f]" % (cuantil(theta, w, .025), cuantil(theta, w, .975), *exacto.interval(.95)))
print("HPD rejilla [%.3f, %.3f] exacto [%.3f, 1.000]" % (*hpd_rejilla(theta, w), 0.05 ** (1 / 4)))
print("predictiva Pr(siguiente es éxito) = sum w_j * θ_j = %.4f" % (w * theta).sum())
# Por qué el log: con 2000 datos la verosimilitud lineal desborda por abajo, la logarítmica no
rng = np.random.default_rng(0)
datos = rng.normal(3.0, 1.5, size=2000)
mu = np.linspace(2.5, 3.5, 400)
loglik = np.array([-0.5 * ((datos - m) ** 2).sum() / 1.5**2 for m in mu])
print("\nlog-verosimilitud máxima:", round(loglik.max(), 1), " exp() de ella:", np.exp(loglik.max()))
print("normalizando en lineal: ", np.exp(loglik).sum(), "(todo 0)")
wm = np.exp(loglik - log_sum_exp(loglik))
print("normalizando con log-sum-exp: suma %.6f, media posterior de μ = %.4f (media muestral %.4f)" % (wm.sum(), (wm * mu).sum(), datos.mean()))HPD for is and equal-tailed : density increases toward , so HPD reaches the endpoint. Now the normal model’s two-dimensional grid, marginal of compared with exact , and the cost of higher dimension.
import numpy as np
from scipy import stats
rng = np.random.default_rng(1)
y = rng.normal(3.0, 1.5, size=12)
n, ybar, S = y.size, y.mean(), ((y - y.mean()) ** 2).sum()
def log_sum_exp(v):
m = v.max()
return m + np.log(np.exp(v - m).sum())
mu = np.linspace(ybar - 4 * np.sqrt(S / (n - 1) / n) * 2, ybar + 4 * np.sqrt(S / (n - 1) / n) * 2, 200)
sg = np.linspace(0.3, 4.0, 200)
M, G = np.meshgrid(mu, sg, indexing="ij") # 200 x 200 = 40 000 evaluaciones
sq = ((y[:, None, None] - M[None]) ** 2).sum(axis=0) # suma de cuadrados en cada (mu, sigma)
logpost = -n * np.log(G) - sq / (2 * G**2) - np.log(G) # log verosimilitud + log prior 1/sigma
w = np.exp(logpost - log_sum_exp(logpost.ravel()))
marg_mu = w.sum(axis=1) # sumar sigma da la marginal de mu
c = np.cumsum(marg_mu) - marg_mu / 2 # acumulada en el centro de cada celda
rejilla = (np.interp(0.025, c, mu), np.interp(0.975, c, mu))
t = stats.t(df=n - 1, loc=ybar, scale=np.sqrt(S / (n - 1) / n))
print("intervalo 95 %% de μ: rejilla (%.3f, %.3f) t exacta (%.3f, %.3f)" % (*rejilla, *t.interval(0.95)))
print("media posterior de σ: rejilla %.3f (EMV de σ: %.3f)" % ((w.sum(axis=0) * sg).sum(), np.sqrt(S / n)))
for d in (2, 4, 6, 10):
print(f"d = {d:2d} parámetros con 100 puntos por eje: {100.0**d:.0e} evaluaciones, {100.0**d * 8 / 1e9:.1e} GB de memoria")With libraries
In SciPy each family has an object, and intervals, prediction and simulation each take one line.
import numpy as np
from scipy import stats
# Beta-binomial con Beta(2, 2) y 7 éxitos en 10
post = stats.beta(2 + 7, 2 + 3)
print("Beta(9, 5): media %.4f, mediana %.4f, intervalo 95 %% (%.3f, %.3f)" % (post.mean(), post.median(), *post.interval(0.95)))
print("Pr(θ > 0.5 | datos) = %.4f" % post.sf(0.5))
# Predictiva de 10 ensayos nuevos: beta-binomial, frente a la binomial con el EMV
k = np.arange(11)
pred = stats.betabinom(10, 9, 5).pmf(k)
plug = stats.binom(10, 0.7).pmf(k)
print("varianza predictiva %.3f frente a la del enchufe %.3f" % (stats.betabinom(10, 9, 5).var(), stats.binom(10, 0.7).var()))
print("Pr(10 de 10): predictiva %.4f frente a enchufe %.4f" % (pred[-1], plug[-1]))
# Gamma-Poisson: la predictiva es binomial negativa
a, r = 19, 7 # posterior de las alertas por hora
nb = stats.nbinom(a, r / (r + 1))
print("\nPr(0 alertas la próxima hora): %.4f (Poisson con la media: %.4f)" % (nb.pmf(0), stats.poisson(a / r).pmf(0)))
# Dirichlet: media, y muestras del posterior
alpha_post = np.array([6.0, 3.0, 1.0])
d = stats.dirichlet(alpha_post)
rng = np.random.default_rng(0)
print("Dirichlet: media", np.round(d.mean(), 3), " 1 muestra:", np.round(d.rvs(random_state=rng)[0], 3))
# Normal con varianza conocida: predictiva N(m_n, sigma2 + tau_n2)
m_n, tau_n2, sigma2 = 11.6, 0.8, 9.0
print("Predictiva normal: media %.1f, desv. típica %.3f (ruido %.3f, parámetro %.3f)" % (m_n, np.sqrt(sigma2 + tau_n2), np.sqrt(sigma2), np.sqrt(tau_n2)))Laboratory: detection rate with few data
Fictitious data and the motivating rule: estimate true-positive rate with a prior informed by similar rules, compare MLE and Wilson interval, and decide how many more trials make the lower credible bound exceed a threshold.
import numpy as np
from scipy import stats
from statsmodels.stats.proportion import proportion_confint
a0, b0 = 17, 3 # prior: media 0.85, equivalente a 20 pruebas de reglas parecidas
x, n = 9, 10 # 9 detectados en 10 vulnerabilidades
post = stats.beta(a0 + x, b0 + n - x)
wil = proportion_confint(x, n, method="wilson")
print("EMV %.3f media posterior %.3f MAP %.3f" % (x / n, post.mean(), (a0 + x - 1) / (a0 + b0 + n - 2)))
print("credibilidad 95 %% (%.3f, %.3f) Wilson 95 %% (%.3f, %.3f)" % (*post.interval(0.95), *wil))
print("límite inferior unilateral del 95 %%: %.3f" % post.ppf(0.05))
# ¿Cuántas pruebas MÁS, todas detectadas, para que el límite inferior (5 %) supere 0.9?
umbral = 0.9
for m in range(0, 500):
if stats.beta(a0 + x + m, b0 + n - x).ppf(0.05) > umbral:
break
print("hacen falta %d detecciones seguidas más (n = %d) para que el límite inferior supere %.2f" % (m, n + m, umbral))
# Con 3 de 3 y el mismo prior frente a prior uniforme: el prior frena el entusiasmo del EMV
for nombre, (a, b) in {"uniforme": (1, 1), "informado Beta(17, 3)": (17, 3)}.items():
p3 = stats.beta(a + 3, b + 0)
print("3 de 3, prior %-22s media %.3f intervalo 95 %% (%.3f, %.3f)" % (nombre, p3.mean(), *p3.interval(0.95)))The informed prior shifts the interval upward and narrows it: 20 favorable pseudo-observations unavailable to the Wilson interval, which sees only 10 real ones. This is desirable if the prior is well founded, risky otherwise (common mistakes revisits it). And coverage: what happens to credibility evaluated at fixed ?
import numpy as np
from scipy import stats
n = 10
xs = np.arange(n + 1)
lo = stats.beta(1 + xs, 1 + n - xs).ppf(0.025) # colas iguales con prior uniforme
hi = stats.beta(1 + xs, 1 + n - xs).ppf(0.975)
def cobertura(p):
"""Cobertura exacta a theta = p fijo: suma de Pr(X = x) sobre los x cuyo intervalo contiene a p."""
p = np.atleast_1d(p)
pm = stats.binom.pmf(xs[:, None], n, p[None, :])
dentro = (lo[:, None] <= p[None, :]) & (p[None, :] <= hi[:, None])
return (pm * dentro).sum(axis=0)
for p in (0.01, 0.05, 0.2, 0.5):
print("theta = %.2f: cobertura %.3f" % (p, cobertura(p)[0]))
ps = (np.arange(40000) + 0.5) / 40000
c = cobertura(ps)
print("cobertura mínima en la rejilla %.3f, máxima %.3f" % (c.min(), c.max()))
print("promedio sobre theta ~ U(0, 1) (la garantía bayesiana): %.4f" % c.mean())The guarantee is the average: exactly for drawn from the prior; not coverage at fixed . One last calculation from MAP: ridge regression is the posterior maximum with Gaussian prior, and soft threshold is MAP with Laplace prior.
import numpy as np
from scipy import optimize
rng = np.random.default_rng(3)
n, d, sigma, tau = 30, 4, 1.0, 0.5
X = rng.normal(size=(n, d))
beta_ver = np.array([1.0, -0.8, 0.0, 0.3])
y = X @ beta_ver + sigma * rng.normal(size=n)
lam = sigma**2 / tau**2 # la penalización equivalente
ridge = np.linalg.solve(X.T @ X + lam * np.eye(d), X.T @ y) # forma cerrada
def menos_log_posterior(b): # -log verosimilitud - log prior (gaussiano)
return ((y - X @ b) ** 2).sum() / (2 * sigma**2) + (b**2).sum() / (2 * tau**2)
map_num = optimize.minimize(menos_log_posterior, np.zeros(d), method="BFGS", options={"gtol": 1e-10}).x
print("ridge cerrado :", np.round(ridge, 5))
print("MAP numérico :", np.round(map_num, 5), " máx |diferencia| = %.1e" % np.abs(ridge - map_num).max())
# Un dato y = theta + N(0, 1) con prior de Laplace(0, b): el MAP es el umbral blando con lambda = 2 / b
b_lap = 1.0
lam1 = 2 * 1.0**2 / b_lap
for yobs in (0.5, 0.9, 1.0, 1.5, 3.0):
f = lambda t: 0.5 * (yobs - t) ** 2 + abs(t) / b_lap
num = optimize.minimize_scalar(f, bounds=(-10, 10), method="bounded", options={"xatol": 1e-10}).x
soft = np.sign(yobs) * max(abs(yobs) - lam1 / 2, 0.0)
print("y = %.1f: MAP numérico %.4f umbral blando %.4f" % (yobs, num, soft))Finally, sequential updating and Thompson sampling which uses it: each arm’s posterior is a pair of counters.
import numpy as np
rng = np.random.default_rng(0)
x = rng.random(500) < 0.3 # 500 ensayos con theta = 0.3
a0, b0 = 2, 6
# dato a dato, en lotes de 50 y de golpe: el mismo posterior
a, b = a0, b0
for xi in x:
a, b = a + xi, b + (1 - xi)
a_lote, b_lote = a0, b0
for trozo in np.split(x, 10):
a_lote, b_lote = a_lote + trozo.sum(), b_lote + (~trozo).sum()
print("dato a dato:", (int(a), int(b)), " en lotes:", (int(a_lote), int(b_lote)), " de golpe:", (a0 + int(x.sum()), b0 + int((~x).sum())))
# Thompson sampling con tres brazos de tasas desconocidas: el posterior de cada brazo es una beta
verdad = np.array([0.30, 0.45, 0.55])
par = np.ones((3, 2)) # (alfa, beta) de cada brazo, prior uniforme
pulls = np.zeros(3, dtype=int)
for t in range(2000):
muestras = rng.beta(par[:, 0], par[:, 1]) # un theta de cada posterior
k = int(np.argmax(muestras)) # juega el brazo cuyo theta muestreado sea mayor
exito = rng.random() < verdad[k]
par[k] += (exito, 1 - exito)
pulls[k] += 1
print("veces que se juega cada brazo:", pulls, " medias posteriores:", np.round(par[:, 0] / par.sum(axis=1), 3))Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. Which function of should you inspect?
Step 1 of 4. What kernel does the posterior have?
hpd(muestras, nivel=0.95) returning (lo, hi), the HPD interval of a unimodal posterior represented by samples: the shortest interval containing fraction nivel of samples (sort and slide a window of consecutive samples). It should match the equal-tailed interval for a symmetric posterior and be shorter for a skewed one.import numpy as np
def hpd(muestras, nivel=0.95):
"""Intervalo (lo, hi) más corto que contiene la fracción 'nivel' de las muestras."""
x = np.sort(np.asarray(muestras, dtype=float))
# tu código: tamaño de la ventana, anchuras de todas las ventanas consecutivas y la menor
return x[0], x[-1]Summary
- Rule. . Only the kernel matters: recognizing a known family calculates the posterior.
- Conjugacy. Beta-binomial (, ), gamma-Poisson (, ), normal-normal (precisions add, precision-weighted mean), and Dirichlet-multinomial (). Every exponential family has a conjugate prior, with hyperparameters read as pseudo-observations. Prior weight in the mean is .
- Summaries. Mean (squared loss), median (absolute loss), mode (MAP). Credible intervals are equal-tailed (equivariant) or HPD (smallest-length region, possibly split and not reparameterization invariant).
- Predictive. : more dispersed than plugging in MLE, and smooths (Laplace: ; Dirichlet: pseudo-counts).
- Grid. Evaluate unnormalized posterior on a grid and normalize in logs (log-sum-exp). Works for any one- or two-dimensional model and becomes infeasible because cost is : hence MCMC.
- MAP. Penalized maximum likelihood: ridge is MAP with normal prior (), lasso with Laplace prior (). It depends on parameterization and discards uncertainty.
- Sequential. Today’s posterior is tomorrow’s prior, with identical results in batches, one at a time and in any order. A prior assigning zero probability to truth cannot recover it.
- Credibility versus confidence. versus coverage at fixed . They coincide in some models (normal with prior gives the exact interval) and asymptotically; credibility only guarantees calibration averaged over prior.