Module contents
Lesson 22 of 27Advanced 105 min

Priors, Bayesian model comparison and Bernstein-von Mises

Choose and check priors, compare models with Bayes factors, and understand asymptotic posterior behavior.

After this lesson you can

  • Derive Jeffreys priors and test posterior propriety.
  • Compute marginal likelihoods and understand prior sensitivity of Bayes factors.
  • Use prior and posterior predictive checks.
  • Explain the Bernstein–von Mises theorem and its limitations.

Before you start

Motivation: same data, three priors and two questions

A new model is evaluated on 20 difficult cases and fails 3. Three analysts want a distribution for its failure rate pp, and all say they do not want to “add information” in the prior:

  • Ana uses uniform (0,1)(0, 1), Beta(1,1)\mathrm{Beta}(1, 1). By conjugacy her posterior is Beta(4,18)\mathrm{Beta}(4, 18): mean 0.1820.182, central 95% credible interval [0.054,0.363][0.054, 0.363].
  • Bruno argues a probability’s natural scale is log odds, η=log⁡p1−p\eta = \log\frac{p}{1-p}, and puts a flat prior on η\eta. This means π(p)∝1/(p(1−p))\pi(p) \propto 1/(p(1-p)), yielding posterior Beta(3,17)\mathrm{Beta}(3, 17): mean 0.1500.150, interval [0.034,0.331][0.034, 0.331].
  • Carla uses Jeffreys prior Beta(12,12)\mathrm{Beta}(\tfrac12, \tfrac12), introduced shortly: mean 0.1670.167, interval [0.044,0.349][0.044, 0.349].

Three “uninformative” priors, three answers. Differences are a substantial fraction of posterior standard deviation (about 0.080.08); had the model never failed, Bruno’s posterior would not even exist: p−1(1−p)19p^{-1}(1-p)^{19} is not integrable near 00. With 300 failures in 2000 cases, however, Ana, Bruno and Carla obtain means 0.15030.1503, 0.15000.1500 and 0.15020.1502, standard deviation 0.0080.008: prior no longer matters.

Now change the question. The previous model failed 5% of the time and we want to know if the new one is equal, H0:p=0.05H_0: p = 0.05. Here prior never stops mattering: the p-value does not depend on it, but the Bayesian answer depends on how widely the alternative prior spreads however large nn is, and can contradict the p-value.

This lesson addresses those decisions. First, choosing and defending a prior when it matters: Jeffreys prior and invariance, improper priors and their legitimacy, and weakly informative priors with prior predictive simulation. Next, model comparison via marginal likelihood and Bayes factors, where prior always matters, and the Jeffreys–Lindley paradox. Then checking model resemblance to data with posterior predictive checks. Finally, Bernstein–von Mises explains why prior loses importance in the first example, why Bayesian and frequentist intervals then coincide, and where this fails.

Uninformative priors: the scale problem

The oldest “neutral” prior idea is Laplace’s principle of insufficient reason: if I know nothing about pp, all values are equally probable. The problem is that “equally probable values” depends on the parameter scale. If p∼Unif⁡(0,1)p \sim \Unif(0, 1) and η=log⁡p1−p\eta = \log\frac{p}{1-p}, the density change-of-variables formula gives

πη(η)=πp(p(η)) ∣ ⁣dp ⁣dη∣=1⋅p(1−p)=eη(1+eη)2,\pi_\eta(\eta) = \pi_p(p(\eta))\,\Big\lvert\frac{\dd p}{\dd\eta}\Big\rvert = 1 \cdot p(1-p) = \frac{e^\eta}{(1 + e^\eta)^2},

the standard logistic density: a bell centered at 0 that considers ∣η∣>4\abs{\eta} > 4 unlikely, i.e. p<0.018p < 0.018 or p>0.982p > 0.982. Conversely a flat prior on η\eta (improper, since η\eta spans the real line) corresponds to πp(p)∝1/(p(1−p))\pi_p(p) \propto 1/(p(1-p)), Haldane’s prior, piling mass at boundaries. Neither choice is “neutral”: each is flat on one scale, not all others.

InteractiveUniform in p is not uniform in log odds
Probability scale p∈(0,1)p \in (0, 1)
B's prior: improper, arbitrary scale
Log-odds scale η=log⁡p1−p\eta = \log\frac{p}{1-p}
  • A: rule applied in pp (dashed prior, solid posterior)
  • B: rule applied in η\eta
  • A's MAP on each scale
Prior rule
10
1
A's posterior | B's posteriorBeta(2.0, 10.0) | Beta(1.0, 9.0)
Posterior mean of pp: A | B0.167 | 0.100
95% central interval: A | B[0.023, 0.413] | [0.003, 0.336]
A's MAP on the pp scale | on η\eta (mapped to pp)0.100 | 0.167
Both analysts use the “flat” rule, but their posteriors differ: means 0.167 versus 0.100. Flat in pp corresponds to a logistic density in η\eta; flat in η\eta corresponds to 1/(p(1−p))1/(p(1-p)) in pp, concentrating mass at the edges.
Two analysts apply the same rule to a Bernoulli parameter: A on the pp scale (orange), B on log-odds η\eta (aqua). Dotted curves are priors and solid curves posteriors after kk successes in nn trials, plotted on both scales with Jacobian p(1−p)p(1-p). Under the 'flat' rule posteriors disagree; take kk to 0 and B's ceases to exist. With Jeffreys rule both curves overlap in both panels. The dotted line marks A's MAP on each scale: even with Jeffreys it does not point to the same pp.

What we seek is not a flat prior but a rule constructing priors with the same result on every scale. If one analyst applies the rule to θ\theta and another to φ=h(θ)\varphi = h(\theta), their priors should be related by the Jacobian, describing the same distribution. “Flat” fails. In 1946 Harold Jeffreys found a rule that works, using the intrinsic object the model assigns each parameter: Fisher information.

Intuition: I(θ) ∣ ⁣dθ∣\sqrt{I(\theta)}\,\abs{\dd\theta} measures how many parameter values “distinguishable by data” fit in an interval  ⁣dθ\dd\theta. Where information is high, a small change in θ\theta strongly changes the data distribution, and Jeffreys puts more mass. This is the volume measure of the geometry Fisher information induces on the model (Fisher–Rao metric), hence coordinate-independent.

Proof

Data density does not change under reparameterization: p~(x∣φ)=p(x∣θ(φ))\tilde p(x \given \varphi) = p(x \given \theta(\varphi)). By the chain rule, ∇φlog⁡p~=J⊤∇θlog⁡p\grad_\varphi \log\tilde p = \mat{J}\T\grad_\theta \log p. Thus

Iφ(φ)=E[J⊤∇θlog⁡p (∇θlog⁡p)⊤J]=J⊤ Iθ(θ) J.\mat{I}_\varphi(\varphi) = \E\big[\mat{J}\T\grad_\theta\log p\,(\grad_\theta\log p)\T\mat{J}\big] = \mat{J}\T\,\mat{I}_\theta(\theta)\,\mat{J}.

Taking determinants, det⁡Iφ=(det⁡J)2det⁡Iθ\det\mat{I}_\varphi = (\det\mat{J})^2\det\mat{I}_\theta, and square roots, det⁡Iφ(φ)=∣det⁡J(φ)∣det⁡Iθ(θ(φ))\sqrt{\det\mat{I}_\varphi(\varphi)} = \abs{\det\mat{J}(\varphi)}\sqrt{\det\mat{I}_\theta(\theta(\varphi))}. Factor ∣det⁡J∣\abs{\det\mat{J}} is precisely the Jacobian determinant in the change-of-variables formula. For posterior, πJφ(φ) p~(x∣φ)=πJθ(θ) p(x∣θ) ∣det⁡J∣\pi_J^\varphi(\varphi)\,\tilde p(x \given \varphi) = \pi_J^\theta(\theta)\,p(x \given \theta)\,\abs{\det\mat{J}}, the θ\theta posterior transformed by the same change.

∎

Fisher information transforms as a squared density, and its square root as a density. That is the whole trick.

The catalog

ModelI(θ)I(\theta)Jeffreys priorProper?
Bern⁡(p)\Bern(p) or Bin⁡(n,p)\Bin(n, p)np(1−p)\dfrac{n}{p(1-p)}Beta(12,12)\mathrm{Beta}(\tfrac12, \tfrac12), density 1πp(1−p)\dfrac{1}{\pi\sqrt{p(1-p)}}yes
Pois⁡(λ)\Pois(\lambda)1/λ1/\lambdaλ−1/2\lambda^{-1/2}no
Exponential with rate λ\lambda1/λ21/\lambda^21/λ1/\lambdano
N(μ,σ2)\Normal(\mu, \sigma^2), known σ\sigma1/σ21/\sigma^2flat in μ\muno
N(μ,σ2)\Normal(\mu, \sigma^2), known μ\mu2/σ22/\sigma^21/σ1/\sigma (flat in log⁡σ\log\sigma)no
N(μ,σ2)\Normal(\mu, \sigma^2), bothdiag⁡(1/σ2,2/σ2)\diag(1/\sigma^2, 2/\sigma^2)1/σ21/\sigma^2no

Three specialist observations. First, Jeffreys prior is flat for location parameters and flat in log for scale: translation- and unit-change-invariant measures, respectively. Second, the multivariate rule is not always used. For (μ,σ)(\mu, \sigma) jointly it gives 1/σ21/\sigma^2, and the marginal posterior of σ2\sigma^2 has nn rather than the classical frequentist n−1n - 1 degrees of freedom. Jeffreys preferred 1/σ1/\sigma, treating parameters separately and reproducing tt intervals. Modern generalization: Bernardo’s reference priors (1979), agreeing with Jeffreys in dimension 1 and separating interest and nuisance parameters in higher dimensions.

Third, Jeffreys prior depends on experimental design, not only observed likelihood. If instead of fixing nn trials one observes failures until the rrth success (negative binomial), I(p)=r/(p2(1−p))I(p) = r/(p^2(1-p)) and Jeffreys prior is p−1(1−p)−1/2p^{-1}(1-p)^{-1/2}, different from binomial despite proportional likelihoods. This violates the likelihood principle Bayesian analysis often claims to satisfy: the price of a prior defined using data that could have been observed.

Improper priors

Most of the catalog above consists of priors that do not integrate to 1. They are used constantly and are legitimate under one precise condition.

An improper prior is not a probability distribution: it writes the limit of increasingly vague priors or a reference measure. Simulating from it or discussing “prior probability θ>0\theta > 0” makes no sense. The posterior can make sense, but integrability must be checked each time, as it depends on data and model.

A guided exercise proves this by completing the square in likelihood. More interesting is what can fail elsewhere:

  • Haldane with extreme data. With π(p)∝p−1(1−p)−1\pi(p) \propto p^{-1}(1-p)^{-1} and k=0k = 0 successes, posterior ∝p−1(1−p)n−1\propto p^{-1}(1-p)^{n-1} is not integrable at 00, since ∫0p−1 ⁣dp\int_0 p^{-1}\dd p diverges. With 0<k<n0 < k < n it is proper Beta(k,n−k)\mathrm{Beta}(k, n-k). The same prior is valid or invalid depending on data.
  • Hierarchical models. In hierarchical normal model yj∣θj∼N(θj,sj2)y_j \given \theta_j \sim \Normal(\theta_j, s_j^2), θj∣μ,τ∼N(μ,τ2)\theta_j \given \mu, \tau \sim \Normal(\mu, \tau^2), seemingly harmless π(τ)∝1/τ\pi(\tau) \propto 1/\tau (flat in log⁡τ\log\tau, Jeffreys for scale) gives improper posterior: marginal likelihood of τ\tau tends to a positive constant as τ→0\tau \to 0, and ∫0τ−1 ⁣dτ\int_0 \tau^{-1}\dd\tau diverges. Gelman (2006) recommends a uniform prior on τ\tau or half-tt instead.
  • Priors on unidentified parameters. If likelihood is constant in some direction, a flat prior there inherits infinite mass.

Weakly informative priors and prior predictive simulation

Beyond one- or two-parameter models, the search for an “uninformative” prior is usually abandoned in favor of a more modest and useful idea.

The last sentence is key: a prior can only be understood together with likelihood (Gelman, Simpson and Betancourt, 2017). N(0,102)\Normal(0, 10^2) on logistic regression coefficients seems “vague” on the β\beta scale. But data live on the p=σ(x⊤β)p = \sigmoid(\vb{x}\T\vb{\beta}) scale, where that prior makes a specific and false claim.

InteractivePrior predictive simulation in logistic regression
Implied probability p=σ(x⊤β)p = \sigma(\vb{x}\T\vb{\beta}) in 4000 prior simulations
↑ 17.416.8 ↑
24 curves p(x1)=σ(β1x1)p(x_1) = \sigma(\beta_1 x_1) simulated from the prior
  • histogram of pp (density)
  • extreme bins, p<0.025p < 0.025 or p>0.975p > 0.975
  • uniform density for reference
10.0
Number of predictors dd
Scale used
Standard deviation of η=x⊤β\eta = \vb{x}\T\vb{\beta}22.36
Fraction with p<0.01p < 0.01 or p>0.99p > 0.9981.3 %
Fraction with 0.1<p<0.90.1 < p < 0.98.5 %
With βj∼N(0,10.002)\beta_j \sim \Normal(0, 10.00^2), 81 % of simulated individuals have probability below 1% or above 99%. Before seeing any data, this “vague” prior already says the outcome is almost deterministic: it is highly informative on the relevant scale.
Each coefficient has prior βj∼N(0,s2)\beta_j \sim \Normal(0, s^2) and the dd predictors are standardized. Left: implied probability p=σ(x⊤β)p = \sigma(\vb{x}\T\vb{\beta}) for 4000 simulated (β,x)(\vb{\beta}, \vb{x}) pairs; red bins are extreme probabilities. Right: σ(β1x1)\sigma(\beta_1 x_1) curves simulated from the prior. With s=10s = 10 almost all curves are steps and the histogram is U-shaped: the 'vague' prior claims outcomes are nearly deterministic. Reduce ss to a bell; then increase dd and check the problem returns with the same ss.

Figure numbers follow from a simple calculation. With standardized x\vb{x} and βj∼iidN(0,s2)\beta_j \iid \Normal(0, s^2) independent of x\vb{x}, linear predictor has Var⁡(η)=d s2\Var(\eta) = d\,s^2. With d=5d = 5 and s=10s = 10, standard deviation is 2222, and about 81% of simulated individuals have p<0.01p < 0.01 or p>0.99p > 0.99. With s=1s = 1 that fraction drops to 5%. With d=20d = 20 and s=2.5s = 2.5, a reasonable scale for one predictor, it returns to 67%. A coordinatewise reasonable prior is not necessarily reasonable jointly: in high dimensions think about the linear predictor prior, e.g. scaling by 1/d1/\sqrt{d} or priors distributing total variance among coefficients.

Some established recipes, always with standardized predictors:

  • Logistic coefficients: N(0,2.52)\Normal(0, 2.5^2), or Student tt or Cauchy of scale 2.52.5 to allow some large effects (Gelman, Jakulin, Pittau and Su, 2008). Use smaller scales with many predictors.
  • Scales and standard deviations: half-normal or half-tt on σ\sigma, allowing values near 0 without the 1/σ1/\sigma singularity. Avoid Gamma(ε,ε)\mathrm{Gamma}(\eps, \eps) on precisions: it seems vague, but as ε→0\eps \to 0 tends to the improper prior on log⁡τ\log\tau just discussed, and with few groups results depend on ε\eps (Gelman, 2006).
  • Intercept: center on a domain reference value (base rate) with a scale covering possible values.

The complementary tool is sensitivity analysis: fit under several reasonable priors and document how conclusions change. If unchanged, prior is not the analysis’s weak point. If they change, data cannot answer without a prior assumption, which should be stated. A systematic version raises prior (or likelihood) to a power α\alpha near 1 and measures derivatives of conclusions with respect to α\alpha (Kallioinen et al., 2023).

Marginal likelihood as evidence

To compare complete models, each with its prior, the central quantity is probability of data under the model before seeing them.

That last property is Bayesian Occam’s razor. A flexible model can explain many datasets, but its evidence is a distribution over data with total mass 1: spreading mass across many outcomes leaves little for each. A rigid model bets its mass on a few outcomes and wins if right. With n=10n = 10 Bernoulli trials, model M0:p=0.5M_0: p = 0.5 assigns (105)2−10=0.246\binom{10}{5}2^{-10} = 0.246 to k=5k = 5 and 2−10≈0.0012^{-10} \approx 0.001 to k=0k = 0. Model M1:p∼Unif⁡(0,1)M_1: p \sim \Unif(0, 1) assigns each kk equal probability,

m(k∣M1)=(nk)∫01pk(1−p)n−k ⁣dp=(nk) B(k+1,n−k+1)=1n+1=0.091,m(k \given M_1) = \binom{n}{k}\int_0^1 p^k(1-p)^{n-k}\dd p = \binom{n}{k}\,B(k+1, n-k+1) = \frac{1}{n+1} = 0.091,

an observation already in Bayes’s 1763 essay. For k=5k = 5, M0M_0 wins by 0.246/0.091=2.70.246/0.091 = 2.7; for k=0k = 0, M1M_1 wins by nearly 100. The complexity penalty is not added by hand: it comes from the prior spreading its bet.

For conjugate models the integral is explicit. With B(⋅,⋅)B(\cdot,\cdot) the beta function and Γ\Gamma the gamma function:

beta-binomial:m(k)=(nk)B(a+k, b+n−k)B(a,b),gamma-Poisson:m(x1:n)=baΓ(a) Γ(a+S)(b+n)a+S∏i=1n1xi!,S=∑ixi,normal, σ conocida:Xˉ∣M∼N(μ0, τ2+σ2/n) si μ∼N(μ0,τ2).\begin{aligned} \text{beta-binomial:}\quad & m(k) = \binom{n}{k}\frac{B(a + k,\, b + n - k)}{B(a, b)}, \\ \text{gamma-Poisson:}\quad & m(x_{1:n}) = \frac{b^a}{\Gamma(a)}\,\frac{\Gamma(a + S)}{(b + n)^{a + S}}\prod_{i=1}^n\frac{1}{x_i!}, \quad S = \textstyle\sum_i x_i, \\ \text{normal, } \sigma \text{ conocida:}\quad & \bar X \given M \sim \Normal\big(\mu_0,\ \tau^2 + \sigma^2/n\big) \text{ si } \mu \sim \Normal(\mu_0, \tau^2). \end{aligned}

In practice always calculate in logs using gammaln and betaln: with a few thousand observations, m(x)m(x) falls below the smallest representable floating-point number.

Two readings connect evidence to other course topics. By the chain rule, log⁡m(x1:n)=∑i=1nlog⁡p(xi∣x1:i−1,M)\log m(x_{1:n}) = \sum_{i=1}^n \log p(x_i \given x_{1:i-1}, M): log evidence sums log scores for predicting each datum with the posterior of previous data, forward validation exactly like information theory’s prequential coding. And by Laplace’s method, if posterior is approximately normal around MLE θ^\hat\theta with Hessian −∇2ℓ(θ^)≈n I(θ^)-\hess\ell(\hat\theta) \approx n\,\mat{I}(\hat\theta),

log⁡m(x)≈ℓ(θ^)+log⁡π(θ^)+d2log⁡(2π)−12log⁡det⁡(n I(θ^))=ℓ(θ^)−d2log⁡n+OP(1).\log m(x) \approx \ell(\hat\theta) + \log\pi(\hat\theta) + \frac{d}{2}\log(2\pi) - \frac12\log\det\big(n\,\mat{I}(\hat\theta)\big) = \ell(\hat\theta) - \frac{d}{2}\log n + \bigO_P(1).

Retaining the first two terms gives Schwarz’s BIC, ℓ(θ^)−d2log⁡n\ell(\hat\theta) - \frac{d}{2}\log n: penalty 12log⁡n\frac12\log n per parameter. Its error is O(1)\bigO(1) and does not vanish with nn; the full Laplace approximation has relative error O(1/n)\bigO(1/n). You will check this in code.

Bayes factors

When M0M_0 is nested in M1M_1 as a point value, H0:θ=θ0H_0: \theta = \theta_0, the Bayes factor is a Bayesian hypothesis test. Kass and Raftery (1995), adapting Jeffreys, proposed a verbal scale still used:

BF10\mathrm{BF}_{10}2log⁡BF102\log\mathrm{BF}_{10}Evidence against M0M_0
1 to 30 to 2barely worth mentioning
3 to 202 to 6positive
20 to 1506 to 10strong
over 150over 10very strong

Unlike a p-value, a Bayes factor can accumulate evidence for the null: with 77 successes in 1010 trials, the Bayes factor of H0:p=0.5H_0: p = 0.5 versus H1:p∼Unif⁡(0,1)H_1: p \sim \Unif(0, 1) is 1.291.29 (exercise below), slight preference for H0H_0, while two-sided p-value 0.340.34 says only there is no reason to reject it.

The normal test and Jeffreys–Lindley paradox

The simplest case explains it: X1,…,Xn∼iidN(μ,σ2)X_1, \dots, X_n \iid \Normal(\mu, \sigma^2) with known σ\sigma, H0:μ=0H_0: \mu = 0 versus H1:μ∼N(0,τ2)H_1: \mu \sim \Normal(0, \tau^2). Sample mean is sufficient; let Z=n Xˉ/σZ = \sqrt{n}\,\bar X/\sigma be the zz test statistic and r=nτ2/σ2r = n\tau^2/\sigma^2.

Z∣H0∼N(0,1)Z \given H_0 \sim \Normal(0, 1)
Under null, Xˉ∼N(0,σ2/n)\bar X \sim \Normal(0, \sigma^2/n).
1/4

This is the Jeffreys–Lindley paradox (Lindley, 1957). Fix z=2.5z = 2.5, two-sided p-value 0.0120.012. Any 5% test rejects H0H_0 for any nn. But with τ=σ\tau = \sigma, Bayes factor is BF01=0.46\mathrm{BF}_{01} = 0.46 at n=100n = 100, 1.391.39 at n=1000n = 1000 and 4444 at n=106n = 10^6: the same zz “rejecting” the null is strong evidence for it. At fixed nn the same occurs as the prior widens: with n=100n = 100, multiplying τ\tau by 10 multiplies BF01\mathrm{BF}_{01} almost by 10 (0.460.46, 4.44.4, 4444 and 439439 for τ/σ=1,10,100,1000\tau/\sigma = 1, 10, 100, 1000).

InteractiveLindley's paradox
Predictive distributions of Z=n Xˉ/σZ = \sqrt{n}\,\bar X/\sigma: area = p-value, heights = Bayes factor
z = 2.50H₀H₁heightsat z×4.40
BF01\mathrm{BF}_{01} versus nn with fixed zz (logarithmic scales)
in favor of H₀ ↑in favor of H₁ ↓
  • H0H_0: Z∼N(0,1)Z \sim \Normal(0, 1); shading is the p-value
  • H1H_1: Z∼N(0,1+r)Z \sim \Normal(0, 1 + r)
  • best possible τ\tau (lower bound on BF01\mathrm{BF}_{01})
  • Kass and Raftery thresholds 3, 20 and 150
10000
1.00
2.50
Two-sided p-value0.0124
r=nτ2/σ2r = n\tau^2/\sigma^210000
BF01\mathrm{BF}_{01} (ratio of heights)4.40
Evidence (Kass and Raftery)positive for H₀
P(H0∣data)\Pr(H_0 \given \text{data}) with P(H0)=12\Pr(H_0) = \tfrac120.815
Smallest possible BF01\mathrm{BF}_{01} with a normal prior0.1811
The test rejects H0H_0 at 5% (p=0.0124p = 0.0124), but the data are 4.4 times more likely under H0H_0 than H1H_1. The estimated effect is xˉ/σ=0.0250\bar x/\sigma = 0.0250: tiny compared with effects considered plausible by the H1H_1 prior (of order τ/σ=1.00\tau/\sigma = 1.00).
Left: predictive distributions of ZZ under each hypothesis. The p-value is shaded blue tail area beyond ∣z∣\abs{z}; Bayes factor BF01\mathrm{BF}_{01} is the ratio of curve heights at zz (vertical bars). Increase nn or prior width τ\tau: area stays fixed, but orange curve flattens and its height at zz falls. Right: BF01\mathrm{BF}_{01} versus nn on logarithmic scale with Kass–Raftery thresholds; gray line is the most the alternative can achieve with the best prior width.

The figure resolves the paradox. P-value and Bayes factor answer different questions. P-value asks whether zz is rare under H0H_0, a tail area considering only null. Bayes factor asks which model better predicted the observed value, depending on what the alternative predicted. With enormous nn, z=2.5z = 2.5 corresponds to tiny effect xˉ/σ=2.5/n\bar x/\sigma = 2.5/\sqrt{n} (at n=106n = 10^6, 0.00250.0025). Alternative μ∼N(0,σ2)\mu \sim \Normal(0, \sigma^2) bet almost all mass on effects of order σ\sigma, hundreds of times larger, poorly predicting such a small effect. The null predicts effects of order 1/n1/\sqrt{n} and does better. Both answer their own question; reading a p-value as evidence for a specific alternative is wrong.

Two quantitative consequences. First, a bound: minimizing log⁡BF01=12log⁡(1+r)−z22r1+r\log\mathrm{BF}_{01} = \frac12\log(1+r) - \frac{z^2}{2}\frac{r}{1+r} in u=1+ru = 1 + r, the minimum occurs at u=z2u = z^2 and is

min⁡τ BF01=∣z∣ e−(z2−1)/2(∣z∣>1).\min_{\tau}\ \mathrm{BF}_{01} = \abs{z}\,e^{-(z^2 - 1)/2} \qquad (\abs{z} > 1).

With p=0.05p = 0.05 (z=1.96z = 1.96) this gives 0.470.47: no normal prior centered on null achieves more than 2.1 to 1 against H0H_0. With p=0.012p = 0.012, 5.5 to 1. Sellke, Bayarri and Berger (2001) provide a universal bound for any reasonable alternative, BF10≤1/(−e plog⁡p)\mathrm{BF}_{10} \le 1/(-e\,p\log p) if p<1/ep < 1/e, yielding 2.462.46 at p=0.05p = 0.05. A 0.050.05 p-value is much weaker evidence than customary reading suggests (see lesson 10 on what a p-value is and is not).

Second, a practical point. Bayes factor is prior-sensitive forever: posterior of μ\mu under H1H_1 ceases depending on τ\tau once nτ2≫σ2n\tau^2 \gg \sigma^2, but BF01\mathrm{BF}_{01} remains proportional to τ\tau. Thus vague priors are harmless for estimation and disastrous for testing, and improper priors are forbidden for parameters not shared by both models: flat means constant cc times Lebesgue measure, with arbitrary cc, and that arbitrary cc multiplies the Bayes factor. For shared parameters (e.g. common σ\sigma), an improper prior is acceptable because its constant cancels.

Posterior predictive checks

Model comparison says which candidate predicts better, not whether any is useful. For that, check whether data generated by the fitted model resemble observations.

A pBp_B near 0 or 1 says the data aspect measured by TT is not reproduced by the model. The canonical example is counts with more zeros than Poisson can generate.

InteractivePosterior predictive check
Observed frequencies (n=80n = 80) and 90% band of replications
Zero proportion in 1000 replications versus observed value
T(y) = 0.34p_B = 0.000
  • observed data
  • replications: median and 5%–95% band
  • replications with T(yrep)≥T(y)T(y^{\text{rep}}) \ge T(y)
Statistic T(y)T(y)
0.30
Posterior mean of λ\lambda1.981
Observed zero proportion | median across replications0.338 | 0.138
pB=P(T(yrep)≥T(y)∣y)p_B = \Pr(T(y^{\text{rep}}) \ge T(y) \given y)0.000
pBp_B for mean | variance | zeros | maximum0.49 | 0.00 | 0.00 | 0.28
The observed zero proportion (0.34) is above almost all replications: pB=0.000p_B = 0.000. The data contain something the Poisson model cannot generate.
Eighty Poisson(3) counts with fraction π\pi structural zeros added, fitted with a Poisson model and Jeffreys prior. Left: observed frequencies against the 5–95% frequency band in 1000 replicates. Right: distribution of the selected statistic in replicates and its observed value; magenta marks replicates equaling or exceeding it. Zero fraction and variance expose excess zeros; mean never detects it because the model fits λ\lambda precisely to reproduce it. Take π\pi to 0 to see pBp_B for a correct model.

The figure teaches choosing a statistic that attacks what the model does not directly fit. Sample mean is sufficient for λ\lambda: posterior positions itself so replicates have the data’s mean, and pBp_B is around 0.50.5 even for a false model. Zero fraction and variance, by contrast, are features Poisson fixes as functions of mean (e−λe^{-\lambda} and λ\lambda) which data can contradict. Maximum gives little information for this failure: extra zeros do not create large values.

Why pBp_B is conservative

A classical p-value is uniform on [0,1][0, 1] under the null. A posterior predictive p-value is not, even for a correct model: data are used twice, to fit θ\theta and to compare with replicates, and replicates resemble the data more than fresh data would. Its distribution under the correct model concentrates toward 0.50.5 (Meng, 1994; Robins, van der Vaart and Ventura, 2000), increasingly so as TT depends on fitted aspects. In the code simulation, with 300 Poisson datasets and the correct model, mean predictive p-value has variance 0.00080.0008 instead of the uniform’s 1/12≈0.0831/12 \approx 0.083 and never falls below 0.050.05; variance pBp_B has 0.0750.075, nearly uniform.

Practical consequences: extreme pBp_B reliably signals poor fit, but moderate pBp_B does not guarantee good fit, and 5% thresholds do not have their usual interpretation. Predictive checks are a diagnostic revealing model failure and how to extend it (here, zero-inflated Poisson or negative binomial for overdispersion), not a formal test. If calibration is needed, alternatives include Box’s prior predictive p-values (1980), simulation-calibrated values, and cross-validation checks comparing each observation with a predictive distribution that has not seen it (the basis of module 14’s LOO-PIT).

The Bernstein–von Mises theorem

Return to the first example: with 2000 cases three priors gave the same posterior. This is no accident, and the theorem explaining it also gives the common posterior’s shape.

This is the modern Bernstein–von Mises theorem (van der Vaart, 1998, theorem 10.1). Distance is total variation, sup⁡A∣Π(A∣x)−Q(A)∣\sup_A \abs{\Pi(A \given x) - Q(A)}, the strongest reasonable distance: posterior and normal assign nearly the same probability to every set, particularly all intervals. Because total variation is unchanged by applying a bijection to both distributions, the theorem holds under any smooth parameterization, and approximating normals under two parameterizations are related by the delta method.

ProofProof sketch

Work in dimension 1 to simplify notation, on local scale h=n(θ−θ0)h = \sqrt{n}(\theta - \theta_0). Posterior density of hh is proportional to

π(θ0+h/n) ∏i=1np(Xi∣θ0+h/n)p(Xi∣θ0).\pi\big(\theta_0 + h/\sqrt{n}\big)\,\prod_{i=1}^n \frac{p(X_i \given \theta_0 + h/\sqrt{n})}{p(X_i \given \theta_0)}.

Step 1: likelihood ratio is quadratic. Regularity gives local asymptotic normality (LAN): for each hh,

∑i=1nlog⁡p(Xi∣θ0+h/n)p(Xi∣θ0)=h Δn−12I(θ0) h2+oP(1),Δn=1n∑i=1nℓ˙θ0(Xi)⇝N(0,I(θ0)),\sum_{i=1}^n \log\frac{p(X_i \given \theta_0 + h/\sqrt{n})}{p(X_i \given \theta_0)} = h\,\Delta_n - \frac12 I(\theta_0)\,h^2 + o_P(1), \qquad \Delta_n = \frac{1}{\sqrt{n}}\sum_{i=1}^n \dot\ell_{\theta_0}(X_i) \rightsquigarrow \Normal\big(0, I(\theta_0)\big),

where ℓ˙θ0\dot\ell_{\theta_0} is score. This is a second-order Taylor expansion with first term a sum of scores (normal by CLT) and second, by the law of large numbers, Fisher information. Convergence is uniform on compact sets of hh.

Step 2: prior flattens. By continuity, π(θ0+h/n)→π(θ0)>0\pi(\theta_0 + h/\sqrt{n}) \to \pi(\theta_0) > 0 uniformly on compact sets. On the posterior’s moving scale, every continuous positive prior looks constant. Prior disappears here.

Step 3: complete the square. hΔn−12Ih2=−12I (h−I−1Δn)2+12I−1Δn2h\Delta_n - \frac12 I h^2 = -\frac12 I\,(h - I^{-1}\Delta_n)^2 + \frac12 I^{-1}\Delta_n^2, and the final term does not depend on hh. On compact sets posterior density of hh is, up to factor 1+oP(1)1 + o_P(1), that of N(I−1Δn,I−1)\Normal(I^{-1}\Delta_n, I^{-1}).

Step 4: tails. We must show posterior leaves no mass outside compact sets: Π(∣h∣>Mn∣X)→0\Pi(\abs{h} > M_n \given X) \to 0 for every Mn→∞M_n \to \infty. Far from θ0\theta_0 (∣θ−θ0∣≥ε\abs{\theta - \theta_0} \ge \eps) hypothesis-2 tests guarantee this, making likelihood exponentially small there; in the intermediate region Mn/n≤∣θ−θ0∣<εM_n/\sqrt{n} \le \abs{\theta - \theta_0} < \eps, use a LAN-type bound with negative quadratic term. This is the technical part.

Step 5: from densities to total variation. Densities converging pointwise to a limiting density converge in L1L^1 (Scheffé’s lemma, applied in probability), and total variation is half L1L^1 distance. Finally, for an efficient estimator, n(θ^n−θ0)=I−1Δn+oP(1)\sqrt{n}(\hat\theta_n - \theta_0) = I^{-1}\Delta_n + o_P(1), allowing the normal to be centered at θ^n\hat\theta_n. Undoing the scaling gives the claim.

∎

Consequences justify routine Bayesian inference with much data:

  • Prior disappears. Any prior continuous and positive at θ0\theta_0 gives the same posterior to first order. Its effect on posterior mean is O(1/n)\bigO(1/n), negligible versus width O(1/n)\bigO(1/\sqrt{n}). The constant can be large: a prior worth n0n_0 fictitious observations centered distance Δ\Delta from truth shifts the mean about n0Δ/nn_0\Delta/n, small compared with width σ/n\sigma/\sqrt{n} only when n≫n02Δ2/σ2n \gg n_0^2\Delta^2/\sigma^2, with σ\sigma an observation’s standard deviation. The figure shows this.
  • Credible intervals are asymptotic confidence intervals. If CnC_n is the central level-1−α1 - \alpha credible interval, this theorem and MLE asymptotic normality give Pθ0(θ0∈Cn)→1−α\Pr_{\theta_0}(\theta_0 \in C_n) \to 1 - \alpha. Bayesians and frequentists report, to first order, the same Wald interval.
  • Posterior mean is efficient, asymptotically equivalent to MLE, provided the posterior has finite first moment with uniform integrability (total variation convergence alone does not control tails, where the mean lives).
  • Laplace approximation works, along with the preceding section’s BIC approximation.
InteractiveThe posterior becomes normal
Posterior of λ\lambda with n=2048n = 2048 (window adjusts automatically)
λ₀95% credible interval
Total variation versus nn (log-log)
∝ 1/√n
  • exact posterior
  • Bernstein–von Mises normal centered at the MLE
  • true value
  • total variation
Model
Prior for λ\lambda
n = 2048
Sample size nn2048
Total variation between posterior and normal2.5e−3
Posterior standard deviation | normal standard deviation0.0383 | 0.0383
95% interval for λ | true value[2.932, 3.082] | 3.000
Does it cover?yes
Regular fixed-dimensional model: total variation distance falls like 1/n1/\sqrt{n} (the dotted slope), the order of the gamma's remaining asymmetry. With n=2048n = 2048, TV = 2.5e−3.
One seeded data stream; player traverses n=1,2,3,4,6,…,2048n = 1, 2, 3, 4, 6, \dots, 2048. Top: exact posterior (blue) against Bernstein–von Mises normal centered at MLE (dashed orange), with truth and 95% credible interval. Second panel: total variation distance between them on log-log scale, reference slope −1/2-1/2. In Poisson with weak prior, TV falls as 1/n1/\sqrt{n}; with a strong miscentered prior it eventually falls too, but at 2048 data its bias is still one posterior standard deviation. Change model: at a boundary TV does not converge, in the nonregular model it tends to 1, and with increasing dimension posterior concentrates away from truth.

When it fails

Each theorem hypothesis has a counterexample, and the figure shows four.

  • Boundary. If θ0\theta_0 lies on the edge of Θ\Theta (random-effect variance 0, parameter μ≥0\mu \ge 0 with μ0=0\mu_0 = 0), posterior is truncated normal with shape depending on n xˉ\sqrt{n}\,\bar x, still N(0,1)\Normal(0, 1) for every nn. There is no normal limit and total variation fluctuates without tending to 0. An equal-tailed interval never contains the boundary: coverage of μ0=0\mu_0 = 0 is zero. This also breaks Wilks’s theorem at a boundary.
  • Nonregular models. In Unif⁡(0,θ)\Unif(0, \theta) support depends on parameter, likelihood is θ−n1[θ≥M]\theta^{-n}\ind[\theta \ge M] with M=max⁡ixiM = \max_i x_i and no quadratic expansion exists. With prior 1/θ1/\theta, posterior is Pareto attached to MM, narrowing as 1/n1/n, not 1/n1/\sqrt{n}, and n(θ−M)/Mn(\theta - M)/M converges to exponential, not normal. Posterior is excellent (equal-tailed interval has exactly 95% coverage for every nn since (M/θ0)n(M/\theta_0)^n is uniform), but not normal.
  • Dimension growing with nn. If Xi∼N(θi,1)X_i \sim \Normal(\theta_i, 1), i=1,…,ni = 1, \dots, n, each datum brings its own parameter. With flat prior, θi∣x∼N(xi,1)\theta_i \given x \sim \Normal(x_i, 1), and for ψ=1n∑iθi2\psi = \frac1n\sum_i\theta_i^2 we get E[ψ∣x]=x2‾+1\E[\psi \given x] = \overline{x^2} + 1. Since E[x2‾]=ψ0+1\E[\overline{x^2}] = \psi_0 + 1, posterior concentrates around ψ0+2\psi_0 + 2 with width O(1/n)\bigO(1/\sqrt{n}): increasingly certain and wrong, with coverage tending to 0. MLE x2‾\overline{x^2} is also biased. Positive results with growing dimension require dd to grow much more slowly than nn (conditions like d3/n→0d^3/n \to 0; Ghosal, 2000; Panov and Spokoiny, 2015). This is shrinkage and Stein’s paradox in the next lesson.
  • Misspecification. If the model is false, posterior concentrates at the pseudo-value minimizing Kullback–Leibler divergence with covariance 1nV−1\frac1n\mat{V}^{-1} (inverse curvature), whereas MLE distribution has sandwich variance 1nV−1BV−1\frac1n\mat{V}^{-1}\mat{B}\mat{V}^{-1} (Kleijn and van der Vaart, 2012). Credible intervals then have wrong coverage, like Fisher-information Wald intervals for misspecified MLE.
  • Priors vanishing or having atoms at θ0\theta_0, and nonparametric models, where the theorem can fail even for simple functionals (Cox, 1993; Freedman, 1999).

Frequentist versus Bayesian in practice

With all pieces in place, the map of agreement and disagreement is clear.

SituationAgree?What to do
Regular model, fixed dimension, large nn, estimationYes, to first order (Bernstein–von Mises)Either; Wald, profile-likelihood and credible intervals nearly coincide
Small nn or weakly identified parametersNo: prior mattersDefend weakly informative priors with predictive simulation and sensitivity analysis; check coverage by simulation
Point-null hypothesis testNo, even as n→∞n \to \infty (Lindley)If point H0H_0 truly matters, use a Bayes factor with alternative prior chosen for relevant effect scale; otherwise estimate the effect with its interval
Many comparable parameters (group, gene or user effects)No: flat priors failHierarchical models and shrinkage dominate MLE in risk
Boundary, parameter-dependent supportNeither is normalSpecial treatment (mixtures of χ2\chi^2 for likelihood-ratio test, exact intervals and posteriors)
Optional stoppingPosterior unchanged; classical p-values changeSee optional stopping problem and anytime-valid inference

A practical rule follows: in estimation with much data, school choice is nearly cosmetic; model choice matters. Where schools disagree, the question is often poorly posed (a point null nobody believes exactly) or data cannot answer without assumptions (honestly state them as a prior and study sensitivity).

Implementation from scratch

First, Jeffreys prior from its definition: Fisher information as expected squared score, computed by exact sum over support with centered finite differences. Check closed forms and transformation law in log odds.

[ ]Fisher information and Jeffreys priorBrowser
import numpy as np
from scipy import stats, integrate
from scipy.special import expit

def fisher_numerica(logpmf, theta, soporte, h=1e-5):
    """I(θ) = E[(∂/∂θ log p(X | θ))²]: derivada por diferencias centradas, esperanza como suma exacta."""
    x = np.asarray(soporte)
    score = (logpmf(x, theta + h) - logpmf(x, theta - h)) / (2 * h)
    return np.sum(np.exp(logpmf(x, theta)) * score**2)

bern = lambda x, p: stats.bernoulli.logpmf(x, p)
pois = lambda x, lam: stats.poisson.logpmf(x, lam)
for p in [0.1, 0.3, 0.5]:
    print(f"Bernoulli p = {p}:  I numérica = {fisher_numerica(bern, p, [0, 1]):.6f}   1/(p(1-p)) = {1 / (p * (1 - p)):.6f}")
for lam in [0.5, 2.0, 10.0]:
    print(f"Poisson λ = {lam}:  I numérica = {fisher_numerica(pois, lam, np.arange(200)):.6f}   1/λ = {1 / lam:.6f}")

# la misma Bernoulli parametrizada por los log-odds η: I_η = I_p · (dp/dη)²
bern_eta = lambda x, eta: stats.bernoulli.logpmf(x, expit(eta))
for eta in [-3.0, 0.0, 1.5]:
    p = expit(eta)
    print(f"η = {eta:+.1f}:  I_η numérica = {fisher_numerica(bern_eta, eta, [0, 1]):.6f}   "
          f"I_p (dp/dη)² = {(1 / (p * (1 - p))) * (p * (1 - p))**2:.6f}")

# √I_η = √(p(1-p)) integra π en toda la recta: es Beta(1/2, 1/2) visto en log-odds
Z, _ = integrate.quad(lambda e: np.sqrt(expit(e) * expit(-e)), -np.inf, np.inf)
print(f"∫ √I_η dη = {Z:.8f}   π = {np.pi:.8f}")

Integral of Iη\sqrt{I_\eta} over the real line is π\pi, the normalizing constant of Beta(12,12)\mathrm{Beta}(\frac12, \frac12): Jeffreys prior in log odds is proper and the same object as on the pp scale.

Now evidence of conjugate models in log scale, checked against numerical integration, the 7-success example’s Bayes factor, and comparison of Laplace and BIC approximations with exact evidence.

[ ]Marginal likelihood, Bayes factors, Laplace and BICBrowser
import numpy as np
from scipy import stats, integrate
from scipy.special import gammaln, betaln

def log_m_beta_binom(k, n, a, b):
    """log m(k) del modelo binomial con prior Beta(a, b)."""
    return gammaln(n + 1) - gammaln(k + 1) - gammaln(n - k + 1) + betaln(a + k, b + n - k) - betaln(a, b)

def log_m_gamma_pois(x, a, b):
    """log m(x_1..x_n) del modelo Poisson con prior Gamma(a, tasa b)."""
    x = np.asarray(x)
    S, n = x.sum(), len(x)
    return a * np.log(b) - gammaln(a) + gammaln(a + S) - (a + S) * np.log(b + n) - gammaln(x + 1).sum()

num, _ = integrate.quad(lambda p: stats.binom.pmf(7, 10, p) * stats.beta.pdf(p, 2, 2), 0, 1)
print(f"beta-binomial:  fórmula {np.exp(log_m_beta_binom(7, 10, 2, 2)):.10f}   cuadratura {num:.10f}")
x = np.array([2, 0, 3, 1, 4, 2])
num, _ = integrate.quad(lambda l: np.prod(stats.poisson.pmf(x, l)) * stats.gamma.pdf(l, 2, scale=1 / 0.5), 0, 60)
print(f"gamma-Poisson:  fórmula {np.exp(log_m_gamma_pois(x, 2, 0.5)):.6e}   cuadratura {num:.6e}")
print("con prior uniforme, m(k) para k = 0..3 y n = 10:", np.round(np.exp([log_m_beta_binom(k, 10, 1, 1) for k in range(4)]), 5))

# factor de Bayes de H0: p = 0.5 frente a H1: p ~ U(0, 1) con 7 de 10
log_m0 = stats.binom.logpmf(7, 10, 0.5)
log_m1 = log_m_beta_binom(7, 10, 1, 1)
print(f"\nBF01 = {np.exp(log_m0 - log_m1):.6f}")

# por qué en logaritmos: 2000 Bernoulli
y = np.random.default_rng(1).random(2000) < 0.3
print("verosimilitud directa:", np.prod(np.where(y, 0.3, 0.7)), "  log-verosimilitud:", round(np.sum(np.log(np.where(y, 0.3, 0.7))), 2))

# Laplace y BIC frente a la evidencia exacta (Bernoulli, prior uniforme, proporción observada 0.3)
print("\n     n     exacta     Laplace      BIC    error Laplace  error BIC")
for n in [10, 100, 1000, 10000]:
    k = int(0.3 * n); ph = k / n
    loglik = k * np.log(ph) + (n - k) * np.log(1 - ph)
    exacta = betaln(k + 1, n - k + 1)                    # log ∫ p^k (1-p)^(n-k) dp
    laplace = loglik + np.log(1.0) + 0.5 * np.log(2 * np.pi) - 0.5 * np.log(n / (ph * (1 - ph)))
    bic = loglik - 0.5 * np.log(n)
    print(f"{n:6d} {exacta:10.4f} {laplace:10.4f} {bic:10.4f} {laplace - exacta:12.4f} {bic - exacta:10.4f}")

The direct product of 2000 probabilities is exactly 0 in floating point; its log, −1212.4-1212.4, has no issue. Laplace error is 0.0640.064 at n=10n = 10 and falls as 1/n1/n to 10−410^{-4}, whereas BIC converges to constant error −0.139-0.139: 12log⁡(2π p^(1−p^))\frac12\log(2\pi\,\hat p(1 - \hat p)) plus log prior discarded by BIC. Log error O(1)\bigO(1) is a constant Bayes-factor multiplier: irrelevant when models differ by dozens of log-evidence units, decisive when they differ by one.

Lindley’s paradox in a table, and Bayes-factor sensitivity to prior width versus posterior insensitivity:

[ ]Prior sensitivity: Bayes factor versus posteriorBrowser
import numpy as np
from scipy import stats

def bf01_normal(z, n, tau_sobre_sigma):
    r = n * tau_sobre_sigma**2
    return np.sqrt(1 + r) * np.exp(-0.5 * z**2 * r / (1 + r))

z = 2.5
print(f"z = {z}, valor p bilateral = {2 * stats.norm.sf(z):.4f}\n")
print("BF01           n = 10      100     1000     1e4      1e5      1e6")
for t in [0.1, 1, 10, 100]:
    print(f"τ/σ = {t:<6}" + "".join(f"{bf01_normal(z, n, t):9.3f}" for n in [10, 100, 1e3, 1e4, 1e5, 1e6]))

print(f"\nmejor τ posible: BF01 >= {abs(z) * np.exp(-(z**2 - 1) / 2):.4f}")
for p in [0.05, 0.01, 0.005]:
    zz = stats.norm.isf(p / 2)
    print(f"p = {p}:  BF10 <= {1 / (zz * np.exp(-(zz**2 - 1) / 2)):.2f} (normal)   <= {1 / (-np.e * p * np.log(p)):.2f} (Sellke, Bayarri y Berger)")

# el posterior de μ bajo H1 apenas depende de τ: media y desviación con n = 100, σ = 1
n, xbar = 100, z / np.sqrt(100)
print("\nposterior de μ bajo H1 (n = 100):")
for t in [1, 10, 100, 1000]:
    prec = n + 1 / t**2
    print(f"  τ = {t:5}: media {n * xbar / prec:.5f}, desviación {1 / np.sqrt(prec):.5f},  BF01 = {bf01_normal(z, n, t):8.2f}")

The last table summarizes Bayes factors: multiplying τ\tau by 1000 moves posterior mean from 0.24750.2475 to 0.25000.2500 with unchanged standard deviation, while multiplying the Bayes factor nearly 1000-fold.

Finally, fully vectorized simulation of posterior predictive checks and their calibration under the correct model.

[ ]Posterior predictive checks and calibrationBrowser
import numpy as np

rng = np.random.default_rng(22)
n, lam0, pi0 = 80, 3.0, 0.3
y = np.where(rng.random(n) < pi0, 0, rng.poisson(lam0, n))        # Poisson inflada con ceros

ESTAD = {
    "media": lambda Y: Y.mean(axis=-1),
    "varianza": lambda Y: Y.var(axis=-1, ddof=1),
    "ceros": lambda Y: (Y == 0).mean(axis=-1),
    "máximo": lambda Y: Y.max(axis=-1),
}

def replicas(y, S, rng):
    """S conjuntos replicados del modelo Poisson con prior de Jeffreys: λ | y ~ Gamma(Σy + 1/2, tasa n)."""
    lam = rng.gamma(y.sum() + 0.5, 1 / len(y), size=S)
    return rng.poisson(lam[:, None], size=(S, len(y)))

Yrep = replicas(y, 4000, rng)
for nombre, T in ESTAD.items():
    t_obs, t_rep = T(y), T(Yrep)
    print(f"{nombre:9s} T(y) = {t_obs:6.3f}   mediana en las réplicas = {np.median(t_rep):6.3f}   p_B = {np.mean(t_rep >= t_obs):.4f}")

# calibración: datos generados por el propio modelo Poisson
M, S = 300, 300
pp = {k: np.empty(M) for k in ESTAD}
for m in range(M):
    ym = rng.poisson(lam0, n)
    Yr = replicas(ym, S, rng)
    for k, T in ESTAD.items():
        pp[k][m] = np.mean(T(Yr) >= T(ym))
print("\ncon el modelo correcto (una uniforme tendría varianza 0.0833 y un 5 % por debajo de 0.05):")
for k, v in pp.items():
    print(f"{k:9s} media {v.mean():.3f}   varianza {v.var():.4f}   fracción < 0.05: {np.mean(v < 0.05):.3f}   > 0.95: {np.mean(v > 0.95):.3f}")

With excess zeros, variance and zero proportion give pBp_B near 0, mean 0.510.51. Under the correct model, mean never gives pBp_B below 0.050.05 (variance 0.00080.0008: pinned to 0.50.5), whereas variance is almost uniform. Discrete statistics (zeros, maximum) shift upward due to ties, which the ≥\ge convention counts in the model’s favor.

Bernstein–von Mises in practice

The theorem promises credible-interval frequentist coverage 1−α1 - \alpha as n→∞n \to \infty. How much data is enough? Measure it in one-parameter logistic regression, P(Yi=1∣xi)=σ(βxi)\Pr(Y_i = 1 \given x_i) = \sigmoid(\beta x_i) with β0=1\beta_0 = 1 and fixed xi∼N(0,1)x_i \sim \Normal(0, 1), using a grid posterior and N(0,s2)\Normal(0, s^2) priors of three strengths, against a Wald interval. The speed trick: with fixed design, log-likelihood is β t−A(β)\beta\,t - A(\beta) with sufficient t=∑iyixit = \sum_i y_i x_i and A(β)=∑ilog⁡(1+eβxi)A(\beta) = \sum_i \log(1 + e^{\beta x_i}), calculated on the grid once per design. Each replicate contributes only its tt.

[ ]Coverage of credible and Wald intervalsBrowser
import numpy as np
from scipy.special import expit

beta0 = 1.0
B = np.linspace(-4, 7, 881)                                # rejilla de β

def simula(n, R, rng, escalas=(0.5, 2.5, 10)):
    x = rng.normal(size=n)                                  # diseño fijo para este n
    A = np.logaddexp(0, np.outer(B, x)).sum(axis=1)          # A(β) = Σ log(1 + e^{β x_i}) en la rejilla
    y = rng.random((R, n)) < expit(beta0 * x)
    t = y.astype(float) @ x                                   # suficiente de cada réplica
    cob = []
    for s in escalas:
        lp = np.outer(t, B) - A - 0.5 * (B / s) ** 2
        w = np.exp(lp - lp.max(axis=1, keepdims=True))
        cdf = np.cumsum(w, axis=1); cdf /= cdf[:, -1:]
        lo, hi = B[np.argmax(cdf >= 0.025, axis=1)], B[np.argmax(cdf >= 0.975, axis=1)]
        cob.append(np.mean((lo <= beta0) & (beta0 <= hi)))
    # Wald: EMV por Newton, vectorizado sobre las réplicas
    b = np.zeros(R)
    for _ in range(40):
        p = expit(np.outer(b, x))
        b = np.clip(b + (t - p @ x) / ((p * (1 - p)) @ (x * x)), -30, 30)
    info = (expit(np.outer(b, x)) * expit(-np.outer(b, x))) @ (x * x)
    existe = np.abs(b) < 25                                   # separación perfecta: el EMV no existe
    wald = np.mean(existe & (np.abs(b - beta0) <= 1.96 / np.sqrt(info)))
    return cob, wald, 1 - existe.mean()

rng = np.random.default_rng(3)
print("   n   prior s=0.5   s=2.5    s=10    Wald   sin EMV")
for n in [10, 30, 100, 300]:
    cob, wald, sep = simula(n, 600, rng)
    print(f"{n:4d}      {cob[0]:.3f}     {cob[1]:.3f}   {cob[2]:.3f}   {wald:.3f}   {sep:.3f}")

With 600 replicates each coverage has Monte Carlo error about ±0.009\pm 0.009. Strong miscentered prior (s=0.5s = 0.5 shrinks toward 0 while β0=1\beta_0 = 1 lies two prior standard deviations away) stays below 95% even at n=300n = 300: bias is O(1/n)\bigO(1/n) and width O(1/n)\bigO(1/\sqrt{n}), so the ratio falls only as 1/n1/\sqrt{n}. Weakly informative priors give near-95% coverage from n=30n = 30. At n=10n = 10 some replicates show perfect separation (nearly 4% here), where MLE does not exist and Wald gives no interval; posterior with proper prior always exists. This practical advantage of weakly informative priors has nothing to do with philosophy.

The library version

scipy.stats has conjugate predictive distributions, which are per-observation evidence: betabinom is beta-binomial and nbinom with r=ar = a and p=b/(b+1)p = b/(b+1) is gamma-Poisson predictive for one count.

[ ]Conjugate evidence in scipyBrowser
import numpy as np
from scipy import stats
from scipy.special import gammaln, betaln

a, b, n = 2.0, 3.0, 25
k = np.arange(n + 1)
mine = gammaln(n + 1) - gammaln(k + 1) - gammaln(n - k + 1) + betaln(a + k, b + n - k) - betaln(a, b)
print("beta-binomial, máxima diferencia con scipy:", np.max(np.abs(mine - stats.betabinom.logpmf(k, n, a, b))))

# gamma-Poisson con un solo recuento: binomial negativa de parámetros (a, b/(b+1))
a, b = 2.5, 0.8
x = np.arange(30)
mine = a * np.log(b) - gammaln(a) + gammaln(a + x) - (a + x) * np.log(b + 1) - gammaln(x + 1)
print("gamma-Poisson,  máxima diferencia con scipy:", np.max(np.abs(mine - stats.nbinom.logpmf(x, a, b / (b + 1)))))

For nonconjugate models this lesson’s full workflow uses a probabilistic language. In PyMC (unavailable in the browser; illustrative code):

import pymc as pm
import arviz as az

with pm.Model() as modelo:
    beta = pm.Normal("beta", 0, 2.5, shape=d)               # débilmente informativo, X estandarizada
    pm.Bernoulli("y", logit_p=X @ beta, observed=y)
    previa = pm.sample_prior_predictive(1000)               # simulación predictiva a priori
    traza = pm.sample()                                     # NUTS
    pred = pm.sample_posterior_predictive(traza)            # réplicas para las comprobaciones

az.plot_ppc(pred)                                          # comprobación predictiva gráfica
az.loo(traza)                                              # comparación de modelos por LOO, no por factor de Bayes

Evidence of a nonconjugate model is a dd-dimensional integral difficult to estimate accurately: likelihood harmonic means over posterior samples, found in old tutorials, have infinite variance in simple cases and should not be used. Serious methods include bridge sampling (R package bridgesampling), nested sampling and thermodynamic integration. In practice predictive model comparison usually uses cross-validation (LOO with PSIS), less sensitive to prior.

Common mistakes

Exercises

NumericBayes factor for 7 out of 10
Seven successes are observed in 10 Bernoulli trials. Calculate Bayes factor BF01\mathrm{BF}_{01} for H0:p=0.5H_0: p = 0.5 versus H1:p∼Unif⁡(0,1)H_1: p \sim \Unif(0, 1).
NumericThe most p = 0.05 is worth
In normal test H0:μ=0H_0: \mu = 0 versus H1:μ∼N(0,τ2)H_1: \mu \sim \Normal(0, \tau^2), observe z=1.96z = 1.96 (two-sided p-value 0.050.05). What is the smallest BF01\mathrm{BF}_{01} achievable by choosing τ\tau?
NumericPoisson with Jeffreys prior
Four Poisson counts sum to ∑ixi=10\sum_i x_i = 10. With Jeffreys prior π(λ)∝λ−1/2\pi(\lambda) \propto \lambda^{-1/2}, what is posterior mean of λ\lambda?
QuizA million observations
An experiment with n=106n = 10^6 observations gives p=0.01p = 0.01 in the zz test of H0:μ=0H_0: \mu = 0, and Bayes factor under H1:μ∼N(0,σ2)H_1: \mu \sim \Normal(0, \sigma^2) is BF01≈36\mathrm{BF}_{01} \approx 36. Which conclusion is valid?
QuizWhere does Bernstein–von Mises hold?
In which cases should posterior approach N(θ^n,I(θ^n)−1/n)\Normal(\hat\theta_n, \mat{I}(\hat\theta_n)^{-1}/n) in total variation as n→∞n \to \infty?

More than one answer may be correct.

QuizThe statistic that sees nothing
You fit a normal N(μ,σ2)\Normal(\mu, \sigma^2) model with weakly informative prior to data actually highly right-skewed. Which discrepancy statistic is most likely to produce extreme pBp_B?
ProofBernoulli Jeffreys prior and its invariance
Prove: For X∼Bern⁡(p)X \sim \Bern(p), Jeffreys prior is Beta(12,12)\mathrm{Beta}(\frac12, \frac12); generally Jeffreys prior is invariant to reparameterization: if φ=h(θ)\varphi = h(\theta) is a diffeomorphism, πJφ(φ)=πJθ(θ) ∣ ⁣dθ/ ⁣dφ∣\pi_J^\varphi(\varphi) = \pi_J^\theta(\theta)\,\abs{\dd\theta/\dd\varphi}.
0
Write ℓ(p;x)=xlog⁡p+(1−x)log⁡(1−p)\ell(p; x) = x\log p + (1-x)\log(1-p).

Step 1 of 4. What is Bernoulli Fisher information?

ProofAn improper prior with a proper posterior, and one without
Prove: If X1,…,Xn∼iidN(μ,σ2)X_1, \dots, X_n \iid \Normal(\mu, \sigma^2) with known σ\sigma and π(μ)∝1\pi(\mu) \propto 1, posterior is proper and equals N(xˉ,σ2/n)\Normal(\bar x, \sigma^2/n) for all n≥1n \ge 1. In contrast, prior π(p)∝p−1(1−p)−1\pi(p) \propto p^{-1}(1-p)^{-1} with k=0k = 0 successes in nn Bernoulli trials yields improper posterior.
0
Formal posterior is p(x∣μ)π(μ)/m(x)p(x \given \mu)\pi(\mu)/m(x) and is proper if and only if m(x)=∫p(x∣μ)π(μ) ⁣dμ<∞m(x) = \int p(x \given \mu)\pi(\mu)\dd\mu < \infty.

Step 1 of 4. How rewrite ∑i(xi−μ)2\sum_i (x_i - \mu)^2 to expose dependence on μ\mu?

CodePredictive p-value for zero proportion
Implement ppp_ceros(y, S, rng) returning posterior predictive p-value pB=P(T(yrep)≥T(y)∣y)p_B = \Pr(T(y^{\text{rep}}) \ge T(y) \given y) with TT = number (or proportion) of zeros, for a Poisson model with Jeffreys prior and posterior λ∣y∼Gamma(∑iyi+12,tasa n)\lambda \given y \sim \mathrm{Gamma}(\sum_i y_i + \frac12, \text{tasa } n). Use S replicates, each with its own λ(s)\lambda^{(s)}, and convention ≥\ge (ties count). Then implement calibracion(n, lam, M, S, rng) to generate M datasets of n Poisson(lam) counts (the correct model) and return an array of their M pBp_B values. No Python loops over replicates: generate all S replicates at once using rng.poisson(lam[:, None], size=(S, n)). Note NumPy rng.gamma takes scale, not rate.
import numpy as np

def ppp_ceros(y, S, rng):
  """p_B de la proporción de ceros para el modelo Poisson con prior de Jeffreys."""
  y = np.asarray(y)
  n = len(y)
  # tu código: S valores de lambda del posterior, S réplicas de tamaño n y la fracción con T(y_rep) >= T(y)
  return 0.5

def calibracion(n, lam, M, S, rng):
  """M valores p_B de ppp_ceros sobre conjuntos de n recuentos Poisson(lam)."""
  return np.full(M, 0.5)
Shift+Enter to run

Summary

Key idea
Prior matters greatly with little data and always in model comparison; it stops mattering for estimation with much data, where posterior becomes normal and Bayesian and frequentist intervals coincide. Knowing which regime you are in is half the work.
  • A flat prior is flat on only one scale. Jeffreys prior πJ∝det⁡I(θ)\pi_J \propto \sqrt{\det\mat{I}(\theta)} is invariant because square-root Fisher information transforms as a density; it depends on experimental design, and MAP is still not invariant.
  • An improper prior is legitimate if and only if marginal likelihood is finite, depending on model and data; MCMC does not check this.
  • Weakly informative priors exclude absurdity without dominating data. Check with prior predictive simulation on the observation scale; a vague coefficient prior can be highly informative there.
  • Marginal likelihood is data’s predictive probability and penalizes complexity automatically; Laplace approximates it with error O(1/n)\bigO(1/n) and BIC with O(1)\bigO(1). Bayes factor is the evidence ratio and remains sensitive to prior width for every nn: with fixed zz and n→∞n \to \infty it favors null (Jeffreys–Lindley). A 0.050.05 p-value is worth at most about 2.5 to 1.
  • Posterior predictive checks compare data statistics with replicates from the fitted model. They help when the statistic measures what the model does not fit, and pBp_B is conservative.
  • Bernstein–von Mises: in regular fixed-dimensional models with interior parameter and continuous positive prior, posterior is close in total variation to N(θ^,I−1/n)\Normal(\hat\theta, \mat{I}^{-1}/n). It fails at boundaries, in nonregular or misspecified models, and with growing dimension.