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 , and all say they do not want to “add information” in the prior:
- Ana uses uniform , . By conjugacy her posterior is : mean , central 95% credible interval .
- Bruno argues a probability’s natural scale is log odds, , and puts a flat prior on . This means , yielding posterior : mean , interval .
- Carla uses Jeffreys prior , introduced shortly: mean , interval .
Three “uninformative” priors, three answers. Differences are a substantial fraction of posterior standard deviation (about ); had the model never failed, Bruno’s posterior would not even exist: is not integrable near . With 300 failures in 2000 cases, however, Ana, Bruno and Carla obtain means , and , standard deviation : 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, . 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 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 , all values are equally probable. The problem is that “equally probable values” depends on the parameter scale. If and , the density change-of-variables formula gives
the standard logistic density: a bell centered at 0 that considers unlikely, i.e. or . Conversely a flat prior on (improper, since spans the real line) corresponds to , Haldane’s prior, piling mass at boundaries. Neither choice is “neutral”: each is flat on one scale, not all others.
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 and another to , 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: measures how many parameter values “distinguishable by data” fit in an interval . Where information is high, a small change in 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: . By the chain rule, . Thus
Taking determinants, , and square roots, . Factor is precisely the Jacobian determinant in the change-of-variables formula. For posterior, , the 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
| Model | Jeffreys prior | Proper? | |
|---|---|---|---|
| or | , density | yes | |
| no | |||
| Exponential with rate | no | ||
| , known | flat in | no | |
| , known | (flat in ) | no | |
| , both | no |
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 jointly it gives , and the marginal posterior of has rather than the classical frequentist degrees of freedom. Jeffreys preferred , treating parameters separately and reproducing 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 trials one observes failures until the th success (negative binomial), and Jeffreys prior is , 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 ” 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 and successes, posterior is not integrable at , since diverges. With it is proper . The same prior is valid or invalid depending on data.
- Hierarchical models. In hierarchical normal model , , seemingly harmless (flat in , Jeffreys for scale) gives improper posterior: marginal likelihood of tends to a positive constant as , and diverges. Gelman (2006) recommends a uniform prior on or half- 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). on logistic regression coefficients seems “vague” on the scale. But data live on the scale, where that prior makes a specific and false claim.
Figure numbers follow from a simple calculation. With standardized and independent of , linear predictor has . With and , standard deviation is , and about 81% of simulated individuals have or . With that fraction drops to 5%. With and , 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 or priors distributing total variance among coefficients.
Some established recipes, always with standardized predictors:
- Logistic coefficients: , or Student or Cauchy of scale 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- on , allowing values near 0 without the singularity. Avoid on precisions: it seems vague, but as tends to the improper prior on just discussed, and with few groups results depend on (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 near 1 and measures derivatives of conclusions with respect to (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 Bernoulli trials, model assigns to and to . Model assigns each equal probability,
an observation already in Bayes’s 1763 essay. For , wins by ; for , 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 the beta function and the gamma function:
In practice always calculate in logs using gammaln and betaln: with a few thousand observations, falls below the smallest representable floating-point number.
Two readings connect evidence to other course topics. By the chain rule, : 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 with Hessian ,
Retaining the first two terms gives Schwarz’s BIC, : penalty per parameter. Its error is and does not vanish with ; the full Laplace approximation has relative error . You will check this in code.
Bayes factors
When is nested in as a point value, , the Bayes factor is a Bayesian hypothesis test. Kass and Raftery (1995), adapting Jeffreys, proposed a verbal scale still used:
| Evidence against | ||
|---|---|---|
| 1 to 3 | 0 to 2 | barely worth mentioning |
| 3 to 20 | 2 to 6 | positive |
| 20 to 150 | 6 to 10 | strong |
| over 150 | over 10 | very strong |
Unlike a p-value, a Bayes factor can accumulate evidence for the null: with successes in trials, the Bayes factor of versus is (exercise below), slight preference for , while two-sided p-value says only there is no reason to reject it.
The normal test and Jeffreys–Lindley paradox
The simplest case explains it: with known , versus . Sample mean is sufficient; let be the test statistic and .
This is the Jeffreys–Lindley paradox (Lindley, 1957). Fix , two-sided p-value . Any 5% test rejects for any . But with , Bayes factor is at , at and at : the same “rejecting” the null is strong evidence for it. At fixed the same occurs as the prior widens: with , multiplying by 10 multiplies almost by 10 (, , and for ).
The figure resolves the paradox. P-value and Bayes factor answer different questions. P-value asks whether is rare under , a tail area considering only null. Bayes factor asks which model better predicted the observed value, depending on what the alternative predicted. With enormous , corresponds to tiny effect (at , ). Alternative bet almost all mass on effects of order , hundreds of times larger, poorly predicting such a small effect. The null predicts effects of order 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 in , the minimum occurs at and is
With () this gives : no normal prior centered on null achieves more than 2.1 to 1 against . With , 5.5 to 1. Sellke, Bayarri and Berger (2001) provide a universal bound for any reasonable alternative, if , yielding at . A 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 under ceases depending on once , but remains proportional to . 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 times Lebesgue measure, with arbitrary , and that arbitrary multiplies the Bayes factor. For shared parameters (e.g. common ), 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 near 0 or 1 says the data aspect measured by is not reproduced by the model. The canonical example is counts with more zeros than Poisson can generate.
The figure teaches choosing a statistic that attacks what the model does not directly fit. Sample mean is sufficient for : posterior positions itself so replicates have the data’s mean, and is around even for a false model. Zero fraction and variance, by contrast, are features Poisson fixes as functions of mean ( and ) which data can contradict. Maximum gives little information for this failure: extra zeros do not create large values.
Why is conservative
A classical p-value is uniform on under the null. A posterior predictive p-value is not, even for a correct model: data are used twice, to fit and to compare with replicates, and replicates resemble the data more than fresh data would. Its distribution under the correct model concentrates toward (Meng, 1994; Robins, van der Vaart and Ventura, 2000), increasingly so as depends on fitted aspects. In the code simulation, with 300 Poisson datasets and the correct model, mean predictive p-value has variance instead of the uniform’s and never falls below ; variance has , nearly uniform.
Practical consequences: extreme reliably signals poor fit, but moderate 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, , 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 . Posterior density of is proportional to
Step 1: likelihood ratio is quadratic. Regularity gives local asymptotic normality (LAN): for each ,
where 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 .
Step 2: prior flattens. By continuity, uniformly on compact sets. On the posterior’s moving scale, every continuous positive prior looks constant. Prior disappears here.
Step 3: complete the square. , and the final term does not depend on . On compact sets posterior density of is, up to factor , that of .
Step 4: tails. We must show posterior leaves no mass outside compact sets: for every . Far from () hypothesis-2 tests guarantee this, making likelihood exponentially small there; in the intermediate region , 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 (Scheffé’s lemma, applied in probability), and total variation is half distance. Finally, for an efficient estimator, , allowing the normal to be centered at . Undoing the scaling gives the claim.
∎Consequences justify routine Bayesian inference with much data:
- Prior disappears. Any prior continuous and positive at gives the same posterior to first order. Its effect on posterior mean is , negligible versus width . The constant can be large: a prior worth fictitious observations centered distance from truth shifts the mean about , small compared with width only when , with an observation’s standard deviation. The figure shows this.
- Credible intervals are asymptotic confidence intervals. If is the central level- credible interval, this theorem and MLE asymptotic normality give . 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.
When it fails
Each theorem hypothesis has a counterexample, and the figure shows four.
- Boundary. If lies on the edge of (random-effect variance 0, parameter with ), posterior is truncated normal with shape depending on , still for every . There is no normal limit and total variation fluctuates without tending to 0. An equal-tailed interval never contains the boundary: coverage of is zero. This also breaks Wilks’s theorem at a boundary.
- Nonregular models. In support depends on parameter, likelihood is with and no quadratic expansion exists. With prior , posterior is Pareto attached to , narrowing as , not , and converges to exponential, not normal. Posterior is excellent (equal-tailed interval has exactly 95% coverage for every since is uniform), but not normal.
- Dimension growing with . If , , each datum brings its own parameter. With flat prior, , and for we get . Since , posterior concentrates around with width : increasingly certain and wrong, with coverage tending to 0. MLE is also biased. Positive results with growing dimension require to grow much more slowly than (conditions like ; 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 (inverse curvature), whereas MLE distribution has sandwich variance (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 , 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.
| Situation | Agree? | What to do |
|---|---|---|
| Regular model, fixed dimension, large , estimation | Yes, to first order (Bernstein–von Mises) | Either; Wald, profile-likelihood and credible intervals nearly coincide |
| Small or weakly identified parameters | No: prior matters | Defend weakly informative priors with predictive simulation and sensitivity analysis; check coverage by simulation |
| Point-null hypothesis test | No, even as (Lindley) | If point 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 fail | Hierarchical models and shrinkage dominate MLE in risk |
| Boundary, parameter-dependent support | Neither is normal | Special treatment (mixtures of for likelihood-ratio test, exact intervals and posteriors) |
| Optional stopping | Posterior unchanged; classical p-values change | See 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.
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 over the real line is , the normalizing constant of : Jeffreys prior in log odds is proper and the same object as on the 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.
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, , has no issue. Laplace error is at and falls as to , whereas BIC converges to constant error : plus log prior discarded by BIC. Log error 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:
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 by 1000 moves posterior mean from to 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.
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 near 0, mean . Under the correct model, mean never gives below (variance : pinned to ), whereas variance is almost uniform. Discrete statistics (zeros, maximum) shift upward due to ties, which the convention counts in the model’s favor.
Bernstein–von Mises in practice
The theorem promises credible-interval frequentist coverage as . How much data is enough? Measure it in one-parameter logistic regression, with and fixed , using a grid posterior and priors of three strengths, against a Wald interval. The speed trick: with fixed design, log-likelihood is with sufficient and , calculated on the grid once per design. Each replicate contributes only its .
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 . Strong miscentered prior ( shrinks toward 0 while lies two prior standard deviations away) stays below 95% even at : bias is and width , so the ratio falls only as . Weakly informative priors give near-95% coverage from . At 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 and is gamma-Poisson predictive for one count.
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 -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
More than one answer may be correct.
Step 1 of 4. What is Bernoulli Fisher information?
Step 1 of 4. How rewrite to expose dependence on ?
ppp_ceros(y, S, rng) returning posterior predictive p-value with = number (or proportion) of zeros, for a Poisson model with Jeffreys prior and posterior . Use S replicates, each with its own , and convention (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 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)Summary
- A flat prior is flat on only one scale. Jeffreys prior 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 and BIC with . Bayes factor is the evidence ratio and remains sensitive to prior width for every : with fixed and it favors null (Jeffreys–Lindley). A 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 is conservative.
- Bernstein–von Mises: in regular fixed-dimensional models with interior parameter and continuous positive prior, posterior is close in total variation to . It fails at boundaries, in nonregular or misspecified models, and with growing dimension.