Module contents
Lesson 21 of 27Core 110 min

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

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: θ^=x/n=3/3=1\hat\theta = x/n = 3/3 = 1. The rule would be perfect. Nobody believes it, for three reasons this lesson turns into mathematics.

  • Uncertainty is missing. With n=3n = 3, data are compatible with a rate of 0.60.6 (three successive successes have probability 0.2160.216), and also 0.990.99. 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 0.50.5?” or “what is the probability of detecting the next one?” MLE answers 11 and 11: it bets everything on never failing.

Bayesian inference addresses all three with one idea: treat parameter θ\theta 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 θ\theta 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 p(x∣θ)p(x \given \theta) with θ∈Θ\theta \in \Theta. Until now θ\theta was an unknown constant and data the only randomness. The Bayesian view adds a distribution π(θ)\pi(\theta) over Θ\Theta describing uncertainty about θ\theta 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.

  1. The posterior is the complete inferential object. Any question about θ\theta (P(θ>0.5∣x)\Pr(\theta > 0.5 \given x), interval or estimate) is answered with it. There is no unique “Bayesian estimator”: there is one posterior and many summaries.
  2. Likelihood is not a density in θ\theta. Its integral over θ\theta need not equal 1. Its product with the prior can be normalized, which is why m(x)m(x) appears as a constant.
  3. Only shape matters, not the constant. Knowing L(θ;x) π(θ)L(\theta; x)\,\pi(\theta) up to a factor independent of θ\theta 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 θ\theta can take only five values, all equally plausible before data. After three detections in three trials, L(θ)=θ3L(\theta) = \theta^3.

θ\thetapriorlikelihood θ3\theta^3prior × likelihoodposterior
0.10.20.0010.00020.0008
0.30.20.0270.00540.0220
0.50.20.1250.02500.1020
0.70.20.3430.06860.2800
0.90.20.7290.14580.5951

The fourth column sums to 0.2450.245: that is m(x)m(x), the constant to divide by. The posterior allocates mass among the five values proportional to θ3\theta^3, leaving under 0.10.1% probability on θ=0.1\theta = 0.1 (not ruled out, just very unlikely). This is already a grid approximation; below we make it continuous and serious.

With θ∈[0,1]\theta \in [0, 1] and a uniform prior, posterior is proportional to θ3\theta^3 on [0,1][0, 1]. That family has a name. Probability the rate exceeds 0.50.5 is 1−0.54=0.93751 - 0.5^4 = 0.9375, posterior mean is 0.80.8, and a 95% equal-tailed interval is [0.398,0.994][0.398, 0.994]. The three motivating questions now have answers, none “100%.”

Beta-binomial: the posterior in one line

The simplest genuinely useful model has nn independent Bernoulli trials with success probability θ\theta. With xx successes, X∣θ∼Bin⁡(n,θ)X \mid \theta \sim \Bin(n, \theta) and L(θ;x)∝θx(1−θ)n−xL(\theta; x) \propto \theta^x (1 - \theta)^{n - x}. For θ∈[0,1]\theta \in [0, 1] the natural prior family is beta: θ∼Beta(α,β)\theta \sim \mathrm{Beta}(\alpha, \beta), density π(θ)∝θα−1(1−θ)β−1\pi(\theta) \propto \theta^{\alpha - 1}(1 - \theta)^{\beta - 1}.

Proof

The posterior kernel is the product of kernels: θx(1−θ)n−x⋅θα−1(1−θ)β−1=θα+x−1(1−θ)β+n−x−1\theta^{x}(1 - \theta)^{n - x}\cdot\theta^{\alpha - 1}(1 - \theta)^{\beta - 1} = \theta^{\alpha + x - 1}(1 - \theta)^{\beta + n - x - 1}, the kernel of Beta(α+x,β+n−x)\mathrm{Beta}(\alpha + x, \beta + n - x). A density is fixed by its kernel, so this is the posterior. Evidence is the full-product integral: (nx)1B(α,β)∫01θα+x−1(1−θ)β+n−x−1 ⁣dθ=(nx)B(α+x,β+n−x)B(α,β)\binom{n}{x}\frac{1}{B(\alpha, \beta)}\int_0^1 \theta^{\alpha + x - 1}(1 - \theta)^{\beta + n - x - 1}\dd\theta = \binom{n}{x}\frac{B(\alpha + x, \beta + n - x)}{B(\alpha, \beta)}.

∎

Updating is arithmetic on two counters: α\alpha counts successes and β\beta failures. For the detection rule with a uniform prior (α=β=1\alpha = \beta = 1), x=n=3x = n = 3 gives Beta(4,1)\mathrm{Beta}(4, 1) with density 4θ34\theta^3: the previous table’s posterior, continuous.

InteractiveLive beta-binomial updating
Prior, normalized likelihood, and posterior of θ\theta (the success rate)
MLE 1.00
Predictive distribution for the next 10 trials: how many successes
  • prior
  • normalized likelihood
  • posterior and predictive
  • binomial with MLE (plug-in)
Prior
2.0
2.0
0.70
PosteriorBeta(5.0, 2.0) with x = 3, n = 3
Posterior mean · mode (MAP) · MLE0.714 · 0.800 · 1.000
95% HPD · 95% equal tails[0.409, 0.982] · [0.359, 0.957]
Prior weight (α+β)/(α+β+n)(\alpha+\beta)/(\alpha+\beta+n) · P(θ>0.5∣x)\Pr(\theta>0.5 \mid x)57 % · 89.1 %
With n=3n = 3 the prior has weight 57 %: the posterior mean (0.714) is far from the MLE (1.000).
The beta prior (dashed orange) is multiplied by likelihood (blue, normalized to area 1, the posterior with a uniform prior) to give posterior (magenta) and its 95% HPD region (lower bar). Add successes and failures one by one, or ten simulated with a chosen true θ\theta. With few data, which dominates, prior or data? Switch to informed prior Beta(18,6)\mathrm{Beta}(18, 6) and see how much data is needed for the posterior to resemble that under a uniform prior. Below, prediction of the next 10 trials versus the binomial plugging in MLE: it is wider because θ\theta is uncertain.

The prior as pseudo-observations

The mean of posterior Beta(α+x,β+n−x)\mathrm{Beta}(\alpha + x, \beta + n - x) is α+xα+β+n\dfrac{\alpha + x}{\alpha + \beta + n}. Compare MLE x/nx/n: it is the same as adding α\alpha fictitious successes and β\beta failures to real data. Prior hyperparameters are pseudo-observations, and their sum s=α+βs = \alpha + \beta is prior effective sample size. Rewritten, posterior mean is a convex combination of prior mean and observed proportion:

E[θ∣x]=α+xα+β+n=w αα+β⏟m0+(1−w) xn⏟θ^EMV,w=α+βα+β+n.\E[\theta \given x] = \frac{\alpha + x}{\alpha + \beta + n} = w\,\underbrace{\frac{\alpha}{\alpha + \beta}}_{m_0} + (1 - w)\,\underbrace{\frac{x}{n}}_{\hat\theta_{\text{EMV}}}, \qquad w = \frac{\alpha + \beta}{\alpha + \beta + n}.

Prior weight is s/(s+n)s/(s + n): it equals 1/21/2 at n=sn = s and declines as 1/n1/n as nn grows. A Beta(2,2)\mathrm{Beta}(2, 2) prior (4 pseudo-observations) is forgotten with a few dozen data points; Beta(90,10)\mathrm{Beta}(90, 10) (100 pseudo-observations) weighs as much as 100 real trials. Posterior variance is mˉ(1−mˉ)α+β+n+1\dfrac{\bar m(1 - \bar m)}{\alpha + \beta + n + 1} with mˉ\bar m posterior mean: it shrinks as 1/n1/n, alongside the Cramér–Rao bound.

InteractiveHow much weight does a prior have?
The posterior mean is a convex combination: a point between m0m_0 and p^\hat p positioned by the weight w=s/(s+n)w = s/(s+n)
00.250.50.751m₀ = 0.90p̂ = 0.60posterior mean 0.700prior 33 %data 67 %
Posterior mean versus number of observations nn (log⁡(n+1)\log(n+1) axis), with constant p^\hat p
prior meanobserved proportion
  • chosen strength s=10s = 10
  • other strengths (ss = 2, 10, 50, 200)
  • vertical dotted line: n=sn = s (50% weight)
0.90
10
20
0.60
Posterior mean =w m0+(1−w) p^= w\,m_0 + (1-w)\,\hat p0.700 = 0.333·0.90 + 0.667·0.60
PosteriorBeta(21.0, 9.0) · standard deviation 0.082
95% equal-tailed interval[0.528, 0.847]
The data weigh 67 %: with n=20>sn = 20 > s they now dominate, but the prior still moves the posterior mean (0.700) away from p^\hat p by 0.100.
Posterior mean is a point between prior mean m0m_0 (orange) and observed proportion p^\hat p (blue), and the bar shows weights ww and 1−w1 - w. Below, posterior mean versus nn: gray curves show other prior strengths (ss = 2, 10, 50, 200), and vertical dotted line marks n=sn = s, where data and prior weigh equally. Set m0=0.9m_0 = 0.9 and p^=0.6\hat p = 0.6 and increase ss: how many observations make the prior stop dominating? Then fix ss and change m0m_0: weight stays the same, only its direction changes.

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 Θ\Theta.” Its usefulness requires P\mathcal{P} to be parametric and small, with interpretable λ\lambda and easily computed λ′\lambda'. Four classic models:

ModelPriorDataPosteriorPrior counts as
Bernoulli or binomialθ∼Beta(α,β)\theta \sim \mathrm{Beta}(\alpha, \beta)xx successes in nnBeta(α+x, β+n−x)\mathrm{Beta}(\alpha + x,\ \beta + n - x)α\alpha successes and β\beta failures
Poissonλ∼Gamma(a,r)\lambda \sim \mathrm{Gamma}(a, r) (shape, rate)x1,…,xnx_1, \dots, x_n, S=∑xiS = \sum x_iGamma(a+S, r+n)\mathrm{Gamma}(a + S,\ r + n)aa events in rr periods
Normal, known σ2\sigma^2μ∼N(m0,τ02)\mu \sim \Normal(m_0, \tau_0^2)mean yˉ\bar y of nn observationsN(mn,τn2)\Normal(m_n, \tau_n^2), formula belown0=σ2/τ02n_0 = \sigma^2/\tau_0^2 observations with mean m0m_0
Multinomial of KK categoriesp∼Dir(α)\vb{p} \sim \mathrm{Dir}(\vb{\alpha})counts c1,…,cKc_1, \dots, c_KDir(α+c)\mathrm{Dir}(\vb{\alpha} + \vb{c})αk\alpha_k observations of category kk
Proof

Likelihood is ∏ie−λλxi/xi!∝λSe−nλ\prod_i e^{-\lambda}\lambda^{x_i}/x_i! \propto \lambda^{S}e^{-n\lambda} with S=∑ixiS = \sum_i x_i. Multiplied by prior kernel this gives λa+S−1e−(r+n)λ\lambda^{a + S - 1}e^{-(r + n)\lambda}, the kernel of Gamma(a+S,r+n)\mathrm{Gamma}(a + S, r + n).

∎

The pseudo-observation reading is the same: the prior is equivalent to aa events in rr periods. For hourly alerts with prior Gamma(2,1)\mathrm{Gamma}(2, 1) (mean 2), six hours with 3,1,4,2,5,23, 1, 4, 2, 5, 2 alerts give Gamma(19,7)\mathrm{Gamma}(19, 7), mean 19/7=2.7119/7 = 2.71: between prior 22 and MLE 17/6=2.8317/6 = 2.83.

The proof completes squares in the exponent of the product of two Gaussians, step by step in the exercises. Example: m0=10m_0 = 10, τ02=4\tau_0^2 = 4, σ2=9\sigma^2 = 9, n=9n = 9 and yˉ=12\bar y = 12. Precisions are 0.250.25 (prior) and 9/9=19/9 = 1 (data), so τn2=1/1.25=0.8\tau_n^2 = 1/1.25 = 0.8 and mn=(2.5+12)/1.25=11.6m_n = (2.5 + 12)/1.25 = 11.6. Prior is worth σ2/τ02=2.25\sigma^2/\tau_0^2 = 2.25 observations versus nine real ones, so posterior mean lies closer to yˉ\bar y than m0m_0.

Beta is the K=2K = 2 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 p(x∣θ)=h(x)exp⁡{η(θ)⊤T(x)−A(θ)}p(x \given \theta) = h(x)\exp\{\eta(\theta)\T T(x) - A(\theta)\}, and an iid sample of size nn depends on data only through sufficient statistic ∑iT(xi)\sum_i T(x_i).

Proof

Likelihood is ∏ih(xi)⋅exp⁡{η(θ)⊤∑iT(xi)−nA(θ)}\prod_i h(x_i)\cdot\exp\{\eta(\theta)\T\sum_i T(x_i) - nA(\theta)\}. Multiplying by the prior kernel gives exponent η(θ)⊤(τ+∑iT(xi))−(ν+n)A(θ)\eta(\theta)\T\big(\vb{\tau} + \sum_i T(x_i)\big) - (\nu + n)A(\theta), the same form with new hyperparameters. Factors h(xi)h(x_i) do not depend on θ\theta and enter the constant.

∎

Hyperparameter ν\nu counts pseudo-observations and τ/ν\vb{\tau}/\nu is their fictitious mean sufficient statistic. For Bernoulli, η(θ)=log⁡θ1−θ\eta(\theta) = \log\frac{\theta}{1 - \theta}, A(θ)=−log⁡(1−θ)A(\theta) = -\log(1 - \theta) and T(x)=xT(x) = x, and the form gives θτ(1−θ)ν−τ\theta^{\tau}(1 - \theta)^{\nu - \tau}, a Beta(τ+1,ν−τ+1)\mathrm{Beta}(\tau + 1, \nu - \tau + 1): beta with ν=α+β−2\nu = \alpha + \beta - 2 pseudo-trials and τ=α−1\tau = \alpha - 1 pseudo-successes. Conjugacy is not a formula trick: it is sufficiency in the Bayesian world. Data enter posterior only through (∑iT(xi),n)(\sum_i T(x_i), n), 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 E[θ∣x]\E[\theta \given x], median and mode (MAP, studied separately). Each is optimal for a different loss: mean minimizes expected squared loss E[(θ−a)2∣x]\E[(\theta - a)^2 \given x] (this function of aa 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 CC be another set with equal posterior probability. Since both have mass 1−α1 - \alpha, removing the intersection gives ∫Ck∖Cπ ⁣dθ=∫C∖Ckπ ⁣dθ\int_{C_k\setminus C}\pi \dd\theta = \int_{C\setminus C_k}\pi\dd\theta. Density on Ck∖CC_k\setminus C is at least kk and on C∖CkC\setminus C_k less than kk, so

k ∣Ck∖C∣≤∫Ck∖Cπ ⁣dθ=∫C∖Ckπ ⁣dθ≤k ∣C∖Ck∣.k\,\abs{C_k\setminus C} \le \int_{C_k\setminus C}\pi\dd\theta = \int_{C\setminus C_k}\pi\dd\theta \le k\,\abs{C\setminus C_k}.

Adding k∣C∩Ck∣k\abs{C\cap C_k} to both ends, k∣Ck∣≤k∣C∣k\abs{C_k} \le k\abs{C}, and since k>0k > 0, ∣Ck∣≤∣C∣\abs{C_k} \le \abs{C}.

∎

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 00). If also symmetric, it equals the equal-tailed interval. If skewed, HPD is shorter: for Gamma(3,1)\mathrm{Gamma}(3, 1) at 90%, equal-tailed is [0.818,6.296][0.818, 6.296] (length 5.4785.478) and HPD [0.441,5.479][0.441, 5.479] (length 5.0385.038), 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.

InteractiveHPD versus equal tails
Posterior density: the region with density above cc is the HPD
c = 0.063
The 90 % regions on the same axis
equal tailsHPD
  • equal tails
  • HPD (line at cc)
Posterior
3.0
90 %
Equal tails 90 %[0.818, 6.296] · length 5.478
HPD 90 %[0.441, 5.479] · length 5.038
HPD mass · density at threshold cc90.0 % · 0.063
The HPD is 8 % shorter than the equal-tailed interval at the same probability (90 %): it takes the points of highest density.
The horizontal line marks density threshold cc: HPD (magenta) is the region above it, with mass equal to the level. Equal-tailed intervals (blue dashed lines) leave equal mass on each side. Start with gamma and reduce shape toward 1: HPD reaches 0 and equal-tailed does not. For beta, take aa and bb below 1 (U-shaped posterior), and separate the mixture modes: what happens to HPD? Finally enable 'reparameterize' with gamma or beta: equal-tailed transforms with the function, but dotted bar (image of θ\theta HPD) no longer matches the new parameter's HPD.

The posterior predictive distribution

What you need is rarely θ\theta; usually it is a future observation x~\tilde x. Estimating θ^\hat\theta and predicting with p(x~∣θ^)p(\tilde x \given \hat\theta) treats θ^\hat\theta as truth. Bayesian prediction averages over all possible θ\theta values weighted by posterior plausibility.

This follows by marginalizing the joint: p(x~,θ∣x)=p(x~∣θ,x) π(θ∣x)=p(x~∣θ) π(θ∣x)p(\tilde x, \theta \given x) = p(\tilde x \given \theta, x)\,\pi(\theta \given x) = p(\tilde x \given \theta)\,\pi(\theta \given x) by conditional independence, then integrating θ\theta. Prediction is always more dispersed than plug-in prediction, by total variance:

Var⁡(x~∣x)=E[Var⁡(x~∣θ)∣x]⏟ruido del modelo+Var⁡(E[x~∣θ]∣x)⏟incertidumbre sobre θ.\Var(\tilde x \given x) = \underbrace{\E\big[\Var(\tilde x \given \theta) \given x\big]}_{\text{ruido del modelo}} + \underbrace{\Var\big(\E[\tilde x \given \theta] \given x\big)}_{\text{incertidumbre sobre } \theta}.

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 E[θ∣x]=α+xα+β+n\E[\theta \given x] = \frac{\alpha + x}{\alpha + \beta + n}. With uniform prior this is x+1n+2\frac{x + 1}{n + 2}: Laplace’s rule of succession. After 00 successes in 2020 trials, next success probability is not 00 but 1/22≈0.0451/22 \approx 0.045: zero observed does not prove impossibility. For mm future trials, success count follows beta-binomial(m,a,b)(m, a, b), with posterior Beta(a,b)\mathrm{Beta}(a, b), mean m aa+bm\,\frac{a}{a + b} and variance

m aa+b⋅ba+b⋅a+b+ma+b+1,m\,\frac{a}{a + b}\cdot\frac{b}{a + b}\cdot\frac{a + b + m}{a + b + 1},

i.e. binomial variance multiplied by (a+b+m)/(a+b+1)>1(a + b + m)/(a + b + 1) > 1: overdispersion introduced by uncertainty about θ\theta. With large a+ba + b the factor tends to 11; with little information it is large. This distinguishes magenta and blue bars in the first figure.

Gamma-Poisson. With posterior Gamma(a,r)\mathrm{Gamma}(a, r), future count follows negative binomial: P(x~=k)=(k+a−1k)(rr+1)a(1r+1)k\Pr(\tilde x = k) = \binom{k + a - 1}{k}\big(\tfrac{r}{r + 1}\big)^{a}\big(\tfrac{1}{r + 1}\big)^k. Counts whose variance exceeds mean, impossible for Poisson, arise from a simple model: Poisson with an uncertain rate.

Normal with known variance. Predictive is N(mn,σ2+τn2)\Normal(m_n, \sigma^2 + \tau_n^2): observation noise plus mean uncertainty. This is the Bayesian side of the prediction interval.

Dirichlet-multinomial. Probability the next observation is category kk is αk+ckα0+N\dfrac{\alpha_k + c_k}{\alpha_0 + N}, with α0=∑kαk\alpha_0 = \sum_k\alpha_k: observed frequencies smoothed with pseudo-counts. With αk=1\alpha_k = 1 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.

  1. Work in logs. With n=1000n = 1000 data, L(θ;x)L(\theta; x) is order e−1500e^{-1500}, below the smallest positive float64 (≈10−308=e−709\approx 10^{-308} = e^{-709}): the entire grid becomes 0 and normalization divides 0/00/0. Safely calculate ℓj=log⁡L(θj)+log⁡π(θj)\ell_j = \log L(\theta_j) + \log\pi(\theta_j) and normalize with maximum subtraction (log-sum-exp): wj=exp⁡{ℓj−log⁡∑ieℓi}w_j = \exp\{\ell_j - \log\sum_i e^{\ell_i}\} with log⁡∑ieℓi=ℓmax⁡+log⁡∑ieℓi−ℓmax⁡\log\sum_i e^{\ell_i} = \ell_{\max} + \log\sum_i e^{\ell_i - \ell_{\max}}.
  2. The window must contain the mass and resolution the peak. A posterior concentrating as 1/n1/\sqrt{n} can hide between two coarse grid points. First inspect where mass lies using a cheap coarse grid.
  3. Cost grows as MdM^d with dimension dd. With 100 points per parameter: 10210^2 evaluations for one parameter, 10410^4 for two, 10810^8 for four, 101210^{12} 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 μ\mu and standard deviation σ\sigma both unknown, with prior π(μ,σ)∝1/σ\pi(\mu, \sigma) \propto 1/\sigma (flat in (μ,log⁡σ)(\mu, \log\sigma); next lesson). Joint posterior is

π(μ,σ∣y)  ∝  σ−(n+1)exp⁡{−S+n(yˉ−μ)22σ2},S=∑i(yi−yˉ)2,\pi(\mu, \sigma \given y) \;\propto\; \sigma^{-(n+1)}\exp\Big\{-\frac{S + n(\bar y - \mu)^2}{2\sigma^2}\Big\}, \qquad S = \sum_i (y_i - \bar y)^2,

and σ\sigma can be integrated: with A=S+n(yˉ−μ)2A = S + n(\bar y - \mu)^2, ∫0∞σ−(n+1)e−A/(2σ2) ⁣dσ∝A−n/2\int_0^\infty\sigma^{-(n+1)}e^{-A/(2\sigma^2)}\dd\sigma \propto A^{-n/2}, so

π(μ∣y)∝(1+n(μ−yˉ)2S)−n/2⟺μ−yˉs/n  ∣  y  ∼  tn−1,s2=Sn−1.\pi(\mu \given y) \propto \big(1 + \tfrac{n(\mu - \bar y)^2}{S}\big)^{-n/2} \quad\Longleftrightarrow\quad \frac{\mu - \bar y}{s/\sqrt{n}}\;\Big|\; y \;\sim\; t_{n-1}, \qquad s^2 = \frac{S}{n - 1}.

The marginal posterior of μ\mu is Student tt with n−1n - 1 degrees of freedom, centered at yˉ\bar y and scale s/ns/\sqrt{n}: the 95% equal-tailed credible interval is exactly the classical tt interval from confidence intervals. This numerical coincidence (for that prior) joins statements of different kinds, revisited at the end.

Interactive2D posterior by grid
Joint posterior of (μ,σ)(\mu, \sigma) with n=12n = 12 normal observations and a flat prior on (μ,log⁡σ)(\mu, \log\sigma); 40 × 40 grid
22.533.544.555.51234μσMLE
Marginal of μ\mu: bars sum the grid over σ\sigma; curve is the exact Student tt
Grid cost with m=40m = 40 points per axis: log⁡10(md)\log_{10}(m^d) evaluations versus number of parameters dd
1 second at 10⁷/s1 day at 10⁷/s1 year at 10⁷/s
  • grid posterior
  • exact tt (reference)
  • chosen dd
12
40
2
Joint posterior view
Evaluations on this 2D grid (m2m^2) · with dd parameters (mdm^d)1600 · 1600
Time at 10⁷ evaluations/s · memory (8 B per point)less than 1 ms · 12.8 kB
95% interval for μ\mu: grid · exact (tn−1t_{n-1})[2.681, 4.741] · [2.676, 4.746]
Posterior mean of σ\sigma: grid · exact1.749 · 1.751
In 2D, the 40×40 grid (1600 evaluations) reproduces the exact result: the interval for μ\mu differs in length by 0.48%.
For nn normal observations, joint posterior of (μ,σ)(\mu, \sigma) evaluated on an m×mm \times m grid (heatmap with visible cells for small mm, or oblique relief). Below, the marginal of μ\mu from summing the grid versus exact tt. Reduce resolution to 6: what happens to the interval? Increase mm and watch bars approach the curve. Then increase parameter count dd of a hypothetical model: each bar in the last panel is log⁡10(md)\log_{10}(m^d), and lines mark time at ten million evaluations per second. Up to what dd is a grid with m=100m = 100 feasible?

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, y∣β∼N(Xβ,σ2I)\vb{y} \mid \vb{\beta} \sim \Normal(\mat{X}\vb{\beta}, \sigma^2\mat{I}):

Proof

Log posterior, up to constants, is −12σ2∥y−Xβ∥2+log⁡π(β)-\frac{1}{2\sigma^2}\norm{\vb{y} - \mat{X}\vb{\beta}}^2 + \log\pi(\vb{\beta}). Multiplying by −2σ2-2\sigma^2 (without changing the minimizer) gives ∥y−Xβ∥2−2σ2log⁡π(β)\norm{\vb{y} - \mat{X}\vb{\beta}}^2 - 2\sigma^2\log\pi(\vb{\beta}). For normal prior, −2σ2log⁡π(β)=σ2τ2∥β∥22+cte-2\sigma^2\log\pi(\vb{\beta}) = \frac{\sigma^2}{\tau^2}\norm{\vb{\beta}}_2^2 + \text{cte}. For Laplace, −2σ2log⁡π(β)=2σ2b∥β∥1+cte-2\sigma^2\log\pi(\vb{\beta}) = \frac{2\sigma^2}{b}\norm{\vb{\beta}}_1 + \text{cte}.

∎

Useful intuition: ridge says coefficients are small (scale τ\tau), and lasso says most are near zero and some large (Laplace peak at 0). Stronger prior (smaller τ\tau or bb) means more penalty. A single datum makes this explicit: observe y=θ+εy = \theta + \varepsilon with ε∼N(0,1)\varepsilon \sim \Normal(0, 1). Gaussian-prior MAP is y/(1+λ)y/(1 + \lambda), proportional shrinkage; Laplace-prior MAP is soft threshold sign⁡(y) (∣y∣−λ/2)+\operatorname{sign}(y)\,(\abs{y} - \lambda/2)_+, exactly 00 when ∣y∣≤λ/2\abs{y} \le \lambda/2. This gives lasso variable selection. Details and regularization paths are in ridge and lasso.

InteractiveMAP and regularization
Prior, likelihood and posterior of θ\theta for one observation y=θ+εy = \theta + \varepsilon
MAP 0.00
Estimator of θ\theta as a function of the observation yy (with the chosen λ\lambda)
  • MLE (identity)
  • Gaussian MAP = ridge
  • Laplace MAP = lasso (soft threshold)
  • posterior mean with Laplace
Prior on θ\theta
2.0
0.80
Laplace prior with scale b=2σ2/λb = 2\sigma^2/\lambdab = 1.000
MAP (posterior mode) · MLE0.000 · 0.800
Posterior mean · P(∣θ∣<0.1∣y)\Pr(\abs{\theta} < 0.1 \mid y)0.394 · 13.0 %
The MAP is exactly 0 (because ∣y∣≤λ/2\abs{y} \le \lambda/2), but the posterior mean is 0.394 and the posterior assigns only 13 % probability to ∣θ∣<0.1\abs{\theta} < 0.1: the posterior does not believe θ\theta is 0.
Top: prior (orange), likelihood of one observation yy (blue), posterior (magenta), its MAP (circle) and mean (green diamond). Bottom: estimator of θ\theta as a function of yy: diagonal is MLE, overlaid with ridge, lasso (soft threshold), and Laplace-prior posterior mean. With Laplace prior, move yy toward 0: MAP stays exactly 0 while ∣y∣≤λ/2\abs{y} \le \lambda/2. How much posterior probability says θ\theta is near 0? Compare with posterior mean. Switch to Gaussian prior: how do MAP and mean differ?

The figure reveals what MAP is not. MAP at zero does not mean posterior believes θ=0\theta = 0: with Laplace prior posterior mean is never exactly zero, and probability ∣θ∣<0.1\abs{\theta} < 0.1 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 Dir(α)\mathrm{Dir}(\vb{\alpha}), mode is (ck+αk−1)/(N+α0−K)(c_k + \alpha_k - 1)/(N + \alpha_0 - K), and posterior mean (equal to predictive) is (ck+αk)/(N+α0)(c_k + \alpha_k)/(N + \alpha_0). Laplace add-one smoothing is the predictive with Dir(1,…,1)\mathrm{Dir}(1, \dots, 1), or MAP with Dir(2,…,2)\mathrm{Dir}(2, \dots, 2). 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, L(θ;x1,…,xn)=∏i=1np(xi∣θ)L(\theta; x_1, \dots, x_n) = \prod_{i=1}^n p(x_i \given \theta), so π(θ∣x1:n)∝π(θ)∏i<np(xi∣θ)⋅p(xn∣θ)∝π(θ∣x1:n−1) p(xn∣θ)\pi(\theta \given x_{1:n}) \propto \pi(\theta)\prod_{i < n}p(x_i \given \theta)\cdot p(x_n \given \theta) \propto \pi(\theta \given x_{1:n-1})\,p(x_n \given \theta). 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 (α,β)(\alpha, \beta) and add 1 to the appropriate counter. Thompson sampling in a bandit does this: maintain a beta posterior per arm, draw a θ\theta from each and play the largest, updating each arm’s posterior only with that arm’s observations.

InteractiveToday's posterior is tomorrow's prior
The three posteriors of θ\theta after n=0n = 0 observations (vertical line: true θ\theta)
Posterior mean and 95% equal-tailed interval of each analyst, and observed proportion (gray), versus nn
true θ
  • Uniform
  • Weak skeptic
  • Wrong believer
  • observed proportion
n = 0
0.30
Data seenn = 0 · successes x = 0 · MLE undefined
Uniform: Beta(1, 1) → mean and 95% interval0.500 · [0.025, 0.975] · covers θ since n = 0
Weak skeptic: Beta(2, 6) → mean and 95% interval0.250 · [0.037, 0.579] · covers θ since n = 0
Wrong believer: Beta(24, 6) → mean and 95% interval0.800 · [0.642, 0.920] · does not cover θ
Sequential grid update (uniform prior) versus beta in one step: max |Δ density|1.6e-15 (rounding)
With n=0n = 0, the three posteriors are their priors. Press play: each observation updates all three by the same rule.
Three analysts see the same trials with success θ\theta (dashed gray line): one with uniform prior, one skeptical and weak, and one strongly believing θ≈0.8\theta \approx 0.8 (equivalent to 30 observations). Play the stream. Top: their posteriors after nn data points; bottom: each mean and 95% interval. With θ=0.3\theta = 0.3, how much data does the mistaken believer need before their interval stably contains θ\theta? Raise θ\theta to 0.8 and repeat. In the readings, grid posterior calculated one datum at a time, renormalizing each step, differs from batch beta only by rounding error.

Two cautions. First, sequential updating requires the same model for all data; if θ\theta 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: π(θ0)=0\pi(\theta_0) = 0 implies π(θ0∣x)=0\pi(\theta_0 \given x) = 0 for all xx. Lindley’s Cromwell rule asks never to assign probability 00 or 11 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 [0.398,0.994][0.398, 0.994]; Wilson (see proportion intervals) gives [0.439,1][0.439, 1] and exact Clopper–Pearson [0.292,1][0.292, 1]. Similar, but answering different questions.

CredibilityConfidence
What is randomθ\theta (for you, given data)the interval, through samples
What it assertsP(θ∈C∣x)=1−α\Pr(\theta \in C \given x) = 1 - \alphaPθ(θ∈C(X))≥1−α\Pr_\theta(\theta \in C(X)) \ge 1 - \alpha for every θ\theta
Depends onmodel and priormodel and procedure
Guaranteesprobability conditional on observationslong-run frequency over repeated samples

Confidence is evaluated at fixed θ\theta; credibility at fixed data. A credible interval has no frequentist coverage guarantee: with uniform prior and n=10n = 10, the 95% equal-tailed interval covers true θ\theta 90.490.4% of the time when θ=0.01\theta = 0.01, 97.997.9% when θ=0.5\theta = 0.5, and never if θ<0.0023\theta < 0.0023 (with x=0x = 0 the interval starts at 0.00230.0023, and with x≥1x \ge 1 still farther right). But it has a different exact guarantee: if θ\theta is actually drawn from the prior, coverage probability averaged over prior and data is 1−α1 - \alpha, because

P(θ∈C(X))=E[P(θ∈C(X)∣X)]=E[1−α]=1−α.\Pr(\theta \in C(X)) = \E\big[\Pr(\theta \in C(X) \given X)\big] = \E[1 - \alpha] = 1 - \alpha.

In this example, averaging frequentist coverage over θ∼U(0,1)\theta \sim \mathrm{U}(0, 1) gives exactly 0.950.95, with coverage oscillating in a sawtooth between 00 and 0.990.99 depending on θ\theta. Both approaches coincide when prior is nearly flat relative to likelihood: in the normal model with prior 1/σ1/\sigma, equality with the tt 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.

[ ]Four conjugate models from scratchBrowser
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 Beta(4,1)\mathrm{Beta}(4, 1) for the detection rule.

[ ]Posterior on a log-space grid, intervals and predictiveBrowser
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 Beta(4,1)\mathrm{Beta}(4, 1) is [0.473,1][0.473, 1] and equal-tailed [0.398,0.994][0.398, 0.994]: density 4θ34\theta^3 increases toward 11, so HPD reaches the endpoint. Now the normal model’s two-dimensional grid, marginal of μ\mu compared with exact tt, and the cost of higher dimension.

[ ]2D grid: unknown mean and standard deviationBrowser
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.

[ ]scipy.stats: posterior, interval and predictiveBrowser
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.

[ ]Detection rule: informed prior, MLE and WilsonBrowser
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 θ\theta?

[ ]Frequentist coverage of a credible intervalBrowser
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 0.950.95 for θ\theta drawn from the prior; not coverage at fixed θ\theta. One last calculation from MAP: ridge regression is the posterior maximum with Gaussian prior, and soft threshold is MAP with Laplace prior.

[ ]Ridge and lasso are MAP estimatorsBrowser
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.

[ ]Sequential equals batch, and Thompson samplingBrowser
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

NumericPosterior mean
With prior Beta(2,2)\mathrm{Beta}(2, 2) and 7 successes in 10 trials, calculate posterior mean of θ\theta.
NumericLaplace's rule of succession
With a uniform prior on θ\theta and 0 successes in 20 trials, calculate posterior predictive probability of success on the next trial.
NumericAlerts per hour
Hourly system alerts are Pois⁡(λ)\Pois(\lambda) with prior λ∼Gamma(3,2)\lambda \sim \mathrm{Gamma}(3, 2) (shape 3, rate 2). In 5 hours 20 alerts are observed. What is posterior mean of λ\lambda?
NumericCombining precisions
A parameter has prior μ∼N(0,4)\mu \sim \Normal(0, 4) and you observe the mean of n=4n = 4 data with σ2=1\sigma^2 = 1, yˉ=2\bar y = 2. What is posterior mean of μ\mu?
NumericWhen prior weight is one quarter
With prior Beta(8,2)\mathrm{Beta}(8, 2), how many observations nn make prior weight exactly 25% in posterior mean?
NumericTwo successes in a row
The posterior for θ\theta is Beta(5,2)\mathrm{Beta}(5, 2). What is the predictive probability that the next two trials both succeed?
QuizL2 penalty as a prior
In Gaussian linear regression, yi∣β∼N(xi⊤β,σ2)y_i \mid \vb{\beta} \sim \Normal(\vb{x}_i\T\vb{\beta}, \sigma^2), minimize ∥y−Xβ∥2+λ∥β∥22\norm{\vb{y} - \mat{X}\vb{\beta}}^2 + \lambda\norm{\vb{\beta}}_2^2. Which prior on β\vb{\beta} makes the solution MAP?
QuizWhat each interval asserts
After analyzing data with a given prior you obtain a 95% credible interval for θ\theta. Which statements are correct?

More than one answer may be correct.

QuizMAP and parameterization
A posterior for θ∈(0,1)\theta \in (0, 1) is Beta(5,2)\mathrm{Beta}(5, 2), mode 0.80.8. Reparameterize with ϕ=log⁡θ1−θ\phi = \log\frac{\theta}{1 - \theta} and find the mode of the posterior for ϕ\phi. What happens?
ProofThe normal-normal posterior
Prove: If y1,…,yn∣μ∼iidN(μ,σ2)y_1, \dots, y_n \mid \mu \iid \Normal(\mu, \sigma^2) with known σ2\sigma^2 and μ∼N(m0,τ02)\mu \sim \Normal(m_0, \tau_0^2), then μ∣y∼N(mn,τn2)\mu \given y \sim \Normal(m_n, \tau_n^2) with 1/τn2=1/τ02+n/σ21/\tau_n^2 = 1/\tau_0^2 + n/\sigma^2 and mn=τn2 (m0/τ02+nyˉ/σ2)m_n = \tau_n^2\,(m_0/\tau_0^2 + n\bar y/\sigma^2), the precision-weighted mean of m0m_0 and yˉ\bar y.
0
Work with the log posterior kernel as a function of μ\mu, recalling that log kernel of N(m,τ2)\Normal(m, \tau^2) is −(μ−m)22τ2-\frac{(\mu - m)^2}{2\tau^2} up to constants.

Step 1 of 4. Which function of μ\mu should you inspect?

ProofDirichlet-multinomial and smoothing
Prove: If p∼Dir(α1,…,αK)\vb{p} \sim \mathrm{Dir}(\alpha_1, \dots, \alpha_K) and c∣p∼Mult(N,p)\vb{c} \mid \vb{p} \sim \mathrm{Mult}(N, \vb{p}), then p∣c∼Dir(α1+c1,…,αK+cK)\vb{p} \given \vb{c} \sim \mathrm{Dir}(\alpha_1 + c_1, \dots, \alpha_K + c_K), and probability the next observation is category kk is (αk+ck)/(α0+N)(\alpha_k + c_k)/(\alpha_0 + N) with α0=∑kαk\alpha_0 = \sum_k\alpha_k.
0
The Dirichlet density is proportional to ∏kpkαk−1\prod_k p_k^{\alpha_k - 1} on simplex ∑kpk=1\sum_k p_k = 1, and multinomial likelihood is proportional to ∏kpkck\prod_k p_k^{c_k}.

Step 1 of 4. What kernel does the posterior have?

CodeHPD from samples
Implement 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 k=⌈nivel⋅n⌉k = \lceil \text{nivel}\cdot n\rceil 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]
Shift+Enter to run

Summary

Key idea
Bayesian inference treats the parameter as uncertain: posterior is normalized prior times likelihood. Everything else (estimates, intervals, predictions, regularization) summarizes that distribution, and conjugacy turns updating into pseudo-observation arithmetic.
  • Rule. π(θ∣x)∝L(θ;x) π(θ)\pi(\theta \given x) \propto L(\theta; x)\,\pi(\theta). Only the kernel matters: recognizing a known family calculates the posterior.
  • Conjugacy. Beta-binomial (α+x\alpha + x, β+n−x\beta + n - x), gamma-Poisson (a+∑xia + \sum x_i, r+nr + n), normal-normal (precisions add, precision-weighted mean), and Dirichlet-multinomial (α+c\vb{\alpha} + \vb{c}). Every exponential family has a conjugate prior, with hyperparameters read as pseudo-observations. Prior weight in the mean is s/(s+n)s/(s + n).
  • 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. p(x~∣x)=∫p(x~∣θ) π(θ∣x) ⁣dθp(\tilde x \given x) = \int p(\tilde x \given \theta)\,\pi(\theta \given x)\dd\theta: more dispersed than plugging in MLE, and smooths (Laplace: (x+1)/(n+2)(x + 1)/(n + 2); 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 MdM^d: hence MCMC.
  • MAP. Penalized maximum likelihood: ridge is MAP with normal prior (λ=σ2/τ2\lambda = \sigma^2/\tau^2), lasso with Laplace prior (λ=2σ2/b\lambda = 2\sigma^2/b). 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. P(θ∈C∣x)=1−α\Pr(\theta \in C \given x) = 1 - \alpha versus coverage at fixed θ\theta. They coincide in some models (normal with prior 1/σ1/\sigma gives the exact tt interval) and asymptotically; credibility only guarantees calibration averaged over prior.