Chapter 1
Introduction and Examples
Bayesian statistical inference begins with a deceptively simple shift in viewpoint: probability does not apply only to repeatable physical coin flips; it is a coherent numerical language for quantifying uncertainty about any unknown quantity—including a fixed but unknown population parameter .Peter D. Hoff. A First Course in Bayesian Statistical Methods. Springer Texts in Statistics. Springer, New York, 2009. ISBN 978-0-387-92299-7. doi: 10.1007/978-0-387-92407-6 When new data arrive, Bayes’ rule tells us how our state of uncertainty should update, turning prior beliefs into posterior beliefs.
1.1The Triad of Bayesian Learning#
Let denote the sample space of all possible datasets and the parameter space of all candidate values describing the population. Idealized Bayesian learning rests on three objects:
- Prior distribution : a probability distribution on encoding beliefs about before observing the dataset.
- Sampling model : a family of distributions on specifying how probable each dataset would be if were the true parameter value.
- Posterior distribution : the updated distribution on after observing , obtained from the first two via Bayes’ ruleThomas Bayes. An Essay towards Solving a Problem in the Doctrine of Chances. Philosophical Transactions of the Royal Society of London, 53:370–418, 1763; and Pierre-Simon Laplace. A Philosophical Essay on Probabilities. Dover Publications, New York, 1995. Originally published in French in 1814:
Remark 1.1 (Updating, not dictating). Bayes’ rule in (1.1) does not tell you what your prior beliefs ought to be; it tells you the unique rationally coherent way your beliefs must change in response to new evidence .
Why use Bayesian methods when exact prior beliefs are hard to elicit? Hoff highlights three distinct justifications that echo throughout the rest of the book:
- Normative coherence: Theorems of CoxRichard T. Cox. Probability, Frequency and Reasonable Expectation. American Journal of Physics, 14:1–13, 1946; and Richard T. Cox. The Algebra of Probable Inference. The Johns Hopkins Press, Baltimore, 1961 and SavageLeonard J. Savage. The Foundations of Statistics. John Wiley & Sons, New York, 1954; and Leonard J. Savage. The Foundations of Statistics. Dover Publications, New York, second edition, 1972 show that if and faithfully capture a rational agent’s beliefs, Bayes’ rule is the unique coherent update rule.
- Useful approximation and sensitivity: Just as Box and Draper noted that *“all models are wrong, but some are useful”*George E. P. Box and Norman R. Draper. Empirical Model-Building and Response Surfaces. John Wiley & Sons, New York, 1987, a weakly informative or approximate prior is often adequate when data are moderately informative—and when is small, sensitivity analysis explicitly reveals how different priors map to different posteriors.
- Frequentist regularization in hard problems: In small samples or high-dimensional models where classical estimators break down, Bayes’ rule automatically generates regularized estimators with strong non-Bayesian (frequentist) risk properties.
1.2Example 1: Estimating the Probability of a Rare Event#
Suppose a public health team wants to estimate , the prevalence of an infectious disease in a small city, from a random sample of residents. The observed count follows a binomial sampling model, .
Prior epidemiological studies from comparable cities put typical prevalence between and with mean around . For analytical convenience (justified in Chapter 3), we encode this information with a prior:
(1.2)Now suppose the survey observes zero infected individuals (). Under beta–binomial conjugacy, the posterior is simply , yielding:
(1.3)1.2.1Shrinkage as a Weighted Average and Prior Sensitivity#
Writing for the prior mean and for the prior sample size, the posterior expectation for any observed count decomposes cleanly into a convex combination of the sample mean and the prior guess :
(1.4)This single formula (1.4) recurs in one guise or another throughout the entire textbook:In Chapter 5 we prove that for the normal mean, this shrinkage estimator achieves strictly lower frequentist Mean Squared Error than whenever the prior guess lies within a surprisingly wide neighborhood of the truth.
- When , the data weight and the prior washes out.
- When is small, is noisy (or degenerate, as when ), and borrowing weight from stabilizes estimation.
- Conversely, a strongly miscalibrated prior with large can dominate small-sample data—which is why checking prior sensitivity is essential:
| Prior | Prior Mean | Prior Weight | Posterior () | ||
|---|---|---|---|---|---|
| (uniform) | |||||
| (epidemiological) | |||||
| (strong, miscalibrated) |
1.2.2Why Classical Intervals Fail at #
The standard asymptotic 95% Wald confidence interval collapses to the single point when , absurdly claiming near-certainty that nobody in the city is infected. Even across all possible outcomes , its exact frequentist coverage at is severely erratic near the boundary: at , at , and at .Lawrence D. Brown, T. Tony Cai, and Anirban DasGupta. Interval Estimation for a Binomial Proportion. Statistical Science, 16(2):101–133, 2001
The Agresti–Coull adjusted Wald intervalAlan Agresti and Brent A. Coull. Approximate Is Better than “Exact” for Interval Estimation of Binomial Proportions. The American Statistician, 52(2):119–126, 1998 repairs this by adding pseudo-successes and pseudo-failures (rounded to each in the popular “plus-four” rule), replacing with
(1.5)which achieves exact coverage at , at , and at for . Though motivated purely by frequentist coverage, the plus-four point estimate (1.5) is algebraically identical to the Bayes posterior mean under a weakly informative prior!
1.3Example 2: High-Dimensional Predictive Modeling#
Hoff’s second motivating example previews Chapter 9: predicting diabetes progression from baseline predictors (10 main effects, 45 pairwise interactions, 9 quadratics) using training patients and evaluating on held-out test patients:
(1.6)Specifying a full 65-dimensional subjective prior is practically impossible. Instead, we encode one structural belief—sparsity: many of the 64 coefficients are probably zero—by giving each a 50% prior point mass at zero (a spike-and-slab prior).Note a subtlety we revisit in Chapter 9: independent across predictors actually induces a prior on model size centered at 32 active predictors. True multiplicity-adjusting sparsity places a hierarchical prior on the inclusion probability itself, inducing a uniform prior over model size. Beyond Hoff (2009). That analysis of multiplicity appeared in 2010 and is not in Hoff’s book.James G. Scott and James O. Berger. Bayes and Empirical-Bayes Multiplicity Adjustment in the Variable-Selection Problem. The Annals of Statistics, 38(5):2587–2619, 2010 Comparing test-set mean squared prediction error on the 100 held-out patients demonstrates the practical power of Bayesian regularization:
| Method | Structural Idea | Diabetes Test MSE |
|---|---|---|
| Ordinary Least Squares () | Minimizes with all 64 predictors | |
| Bayesian Model Averaging () | Point mass at ; averages over high-probability sparse models | |
| Lasso ()Robert Tibshirani. Regression Shrinkage and Selection via the Lasso. Journal of the Royal Statistical Society, Series B, 58(1):267–288, 1996 | Minimizes ; equivalent to posterior mode under i.i.d. Laplace (double-exponential) priors on | Sparse MAP shrinkage (not reported in Hoff) |
1.4Key Takeaways & Python Check#
- Prior + Likelihood Posterior: Bayes’ rule (1.1) converts prior uncertainty and a sampling model into a complete posterior distribution over .
- Shrinkage protects small samples: Posterior means naturally interpolate between and via (1.4), and sensitivity analysis (Table 1.1) checks how much conclusions depend on the prior.
- Structural priors prevent overfitting: Even coarse structural priors (such as sparsity) yield substantial out-of-sample gains over unregularized maximum likelihood / OLS.
import numpy as np
from scipy import stats
# Compare three Beta(a, b) priors updated with n=20, y=0
n, y = 20, 0
for name, a, b in [("Uniform", 1, 1), ("Epidemiological", 2, 20), ("Strong wrong", 10, 10)]:
ap, bp = a + y, b + n - y
print(f"{name:16s} -> Beta({ap:2d},{bp:2d}) | "
f"mean={ap/(ap+bp):.3f} | Pr(theta<0.10)={stats.beta.cdf(0.10, ap, bp):.3f}")
# Exact frequentist coverage at n=20 for Wald vs. plus-four intervals
k = np.arange(n + 1)
for theta in [0.05, 0.10, 0.20]:
pmf = stats.binom.pmf(k, n, theta)
p_w = k / n
se_w = np.sqrt(p_w * (1 - p_w) / n)
cov_w = pmf[(p_w - 1.96 * se_w <= theta) & (theta <= p_w + 1.96 * se_w)].sum()
p_ac = (k + 2) / (n + 4)
se_ac = np.sqrt(p_ac * (1 - p_ac) / (n + 4))
cov_ac = pmf[(p_ac - 1.96 * se_ac <= theta) & (theta <= p_ac + 1.96 * se_ac)].sum()
print(f"theta={theta:.2f}: Wald coverage={cov_w:.3f}, Plus-four coverage={cov_ac:.3f}")1.5Modern Developments: Robust Priors and Prior Sensitivity#
1.5.1Robust Mixture Priors#
A robust mixture prior keeps the benefit of an informative prior while letting the data overrule it.Beyond Hoff (2009). This material is not in Hoff’s book; it follows the robust meta-analytic-predictive (MAP) priors of Schmidli et al., which modernize shrinkage toward a single beta prior. Here MAP stands for “meta-analytic-predictive”, not “maximum a posteriori”.Heinz Schmidli, Sandro Gsteiger, Satrajit Roychoudhury, Anthony O’Hagan, David Spiegelhalter, and Beat Neuenschwander. Robust meta‐analytic‐predictive priors in clinical trials with historical control information. Biometrics, 70(4):1023–1032, 2014. doi: 10.1111/biom.12242 The fixed data weight in (1.4) is the same however badly disagrees with . Instead, let be the informative prior, a vague one, and the prior probability that the informative component is relevant:
(1.7)Why it holds: for each component, so Bayes’ rule (1.1) reweights the components by how well each predicted . Take and . With as , observing raises the weight to (posterior mean ), whereas a conflicting drops it to (mean , against for the informative prior alone). With the miscalibrated and , and the mean is , not the of Table 1.1.
When to use it. Prefer the mixture when the prior summarizes historical data that may not be exchangeable with the new sample. Hoff’s single beta suffices when conflict is implausible or . Since is itself a prior choice, report how results vary with it.
1.5.2Power-Scaling Sensitivity Analysis#
Power-scaling turns the prior-by-prior comparison of Table 1.1 into a local diagnostic that needs no list of alternative priors.Beyond Hoff (2009). This material is not in Hoff’s book; it follows Kallioinen et al. and modernizes sensitivity analysis by hand-picked alternative priors.Noa Kallioinen, Topi Paananen, Paul-Christian Bürkner, and Aki Vehtari. Detecting and diagnosing prior and likelihood sensitivity with power-scaling. Statistics and Computing, 34(1):57, 2024. doi: 10.1007/s11222-023-10366-5 Raise either ingredient of (1.1) to a power near :
(1.8)Why it works: , so reweighting one set of posterior draws explores the whole family without refitting. The discrepancy from the original posterior is measured by the cumulative Jensen–Shannon distance, which compares distribution functions. Sensitivity to both prior and likelihood suggests prior–data conflict; sensitivity to the prior but not to the likelihood suggests a likelihood that is non-informative relative to the prior.
In the beta–binomial model the families are and . For , and , the posterior mean barely moves under prior scaling (, , ). For it moves up under prior scaling (, , ) and down under likelihood scaling (, , ): the signature of conflict.
When to use it. Use it as a routine first screen, especially with many parameters. Hoff’s explicit table and contours remain preferable when a specific alternative prior matters, because power-scaling explores only one direction and is blind to a flat prior, for which never changes.
1.5.3Computational & Symbolic Check#
The Python block evaluates the weights of (1.7) and both power-scaled families of (1.8) at , ; the Wolfram sequence repeats them from the symbolic marginals.Beyond Hoff (2009). This computational check and its Wolfram symbolic counterpart below verify the modern methods in this section and are not in Hoff’s book.
import numpy as np
from scipy import stats
from scipy.special import betaln
n, om = 20, 0.8
for a, b, y in [(2, 20, 0), (2, 20, 10), (10, 10, 0)]:
m1 = np.exp(betaln(a + y, b + n - y) - betaln(a, b))
m0 = np.exp(betaln(1 + y, 1 + n - y))
ws = om * m1 / (om * m1 + (1 - om) * m0)
mean = ws * (a + y) / (a + b + n) + (1 - ws) * (1 + y) / (2 + n)
print(f"Beta({a},{b}), y={y}: w*={ws:.4f}, mean={mean:.4f}")
for a, b in [(2, 20), (10, 10)]: # power-scaling at y = 0
for al in (0.5, 1, 2):
pr = stats.beta.cdf(0.1, al * (a - 1) + 1, al * (b - 1) + 1 + n)
lik = stats.beta.cdf(0.1, a, b + al * n)
print(f"Beta({a},{b}), alpha={al}: prior-scaled {pr:.4f}, lik-scaled {lik:.4f}")// Chapter 1 (modern): robust mixture weights & power-scaled tail probabilities
const mj = await show`Beta[a + y, b + n - y] / Beta[a, b]`await show`Assuming[a > 0 && b > 0 && y >= 0 && n >= y, FullSimplify[
Integrate[th^(a + y - 1)*(1 - th)^(b + n - y - 1)/Beta[a, b], {th, 0, 1}] / (${mj})]]`const wStar = await show`om*(${mj}) / (om*(${mj}) + (1 - om)*Beta[1 + y, 1 + n - y])`const mixMean = await show`(${wStar})*(a + y)/(a + b + n) + (1 - (${wStar}))*(1 + y)/(2 + n)`await show`N[Table[{${wStar}, ${mixMean}} /. {n -> 20, om -> 4/5, a -> p[[1]], b -> p[[2]], y -> p[[3]]},
{p, {{2, 20, 0}, {2, 20, 10}, {10, 10, 0}}}]]`await show`Table[(al*(p[[1]] - 1) + 1)/(al*(p[[1]] + p[[2]] - 2) + 2 + 20), {p, {{2, 20}, {10, 10}}}, {al, {1/2, 1, 2}}]`await show`N[Table[BetaRegularized[1/10, p[[1]], p[[2]] + 20*al], {p, {{2, 20}, {10, 10}}}, {al, {1/2, 1, 2}}]]`1.6Symbolic Check in Wolfram Language#
Run the following wolfram-ws-bridge JavaScript-mode sequence (W, wl, show, toJS) to derive the Beta–Binomial normalizer , posterior mean, posterior variance, mode (for , ), and symbolic tail probability completely symbolically, then instantiate the symbolic formulas at to cross-check the Python output above.
// Chapter 1: Symbolic Beta-Binomial posterior, variance, CDF, and numeric check
const { Times, Power, Plus, Subtract, Minus, th, a, b, n, y } = W
const kernel = Times(
Power(th, Plus(a, y, -1)),
Power(Subtract(1, th), Plus(b, n, Minus(y), -1))
)
const Z = await show`Assuming[a > 0 && b > 0 && y >= 0 && n >= y,
FullSimplify[Integrate[${kernel}, {th, 0, 1}]]]`const mean = await show`Assuming[a > 0 && b > 0 && y >= 0 && n >= y,
FullSimplify[Integrate[th * ${kernel}, {th, 0, 1}] / ${Z}]]`const postVar = await show`Assuming[a > 0 && b > 0 && y >= 0 && n >= y,
FullSimplify[Integrate[th^2 * ${kernel}, {th, 0, 1}] / ${Z} - (${mean})^2]]`// Posterior mode (valid when a + y > 1 and b + n - y > 1) and symbolic CDF Pr(th < c | y)
await show`FullSimplify[th /. First[Solve[D[Log[${kernel}], th] == 0, th]]]`const cdfSym = await show`Assuming[al > 0 && be > 0 && 0 < c < 1,
FullSimplify[Integrate[th^(al - 1)*(1 - th)^(be - 1), {th, 0, c}] / Beta[al, be]]] /. {al -> a + y, be -> b + n - y}`await show`Simplify[${mean} - (n/(n + w)*(y/n) + w/(n + w)*(a/w)) /. w -> a + b]`// Instantiate symbolic mean & CDF at n = 20, y = 0, c = 1/10 for Uniform (1,1), Epi (2,20), Strong wrong (10,10)
await show`N[Table[{${mean}, ${cdfSym}} /. {a -> p[[1]], b -> p[[2]], n -> 20, y -> 0, c -> 1/10}, {p, {{1, 1}, {2, 20}, {10, 10}}}]]`1.7Exercises#
Exercise 1.2. In the rare-event survey (, ), suppose a skeptical colleague insists on a prior centered at . How large can their prior sample size be before drops below ? Verify your answer numerically in Python using scipy.stats.beta.cdf.
Symbolic Solution & Instantiation
Write symbolically as a regularized incomplete Beta ratio in prior weight .// Ex 1.1: Prior dominance threshold w* where Pr(theta < c | y = 0) == 1/2
const cdf = await show`Beta[c, w*th0, w*(1 - th0) + n] / Beta[w*th0, w*(1 - th0) + n]`await show`w /. FindRoot[(${cdf} /. {c -> 1/10, th0 -> 1/5, n -> 20}) == 1/2, {w, 15, 35}]`await show`N[{${cdf} /. {c -> 1/10, th0 -> 1/5, n -> 20, w -> 22}, ${cdf} /. {c -> 1/10, th0 -> 1/5, n -> 20, w -> 23}}]`Exercise 1.3. Show that if and with density , then maximizing is equivalent to minimizing . Express in terms of and .
Symbolic Solution & Instantiation
Multiply the negative log-posterior under a Laplace prior by to reveal the -penalized objective.// Ex 1.2: Equivalence of Laplace MAP and Lasso penalty lambda = 2*sigma^2 / b
const obj = await show`Expand[-2*s2 * (-ssr/(2*s2) - l1/b)]`const lam = await show`Coefficient[${obj}, l1]`await show`${lam} /. {s2 -> 1, b -> 1/2}`Exercise 1.4. Plot the exact frequentist coverage of the 95% Wald interval and the 95% plus-four interval as functions of for and . Why does the coverage curve oscillate sharply even for ?
Symbolic Solution & Instantiation
Express the exact finite-sample Binomial coverage probability as a sum over accepted counts .// Ex 1.3: Exact Binomial coverage sum (Wald vs. plus-four) & lattice oscillation
await show`Sum[Binomial[n, k]*th^k*(1 - th)^(n - k)*Boole[Abs[pHat[k] - th] <= z*se[k]], {k, 0, n}]`await show`N[Table[Sum[Binomial[nVal, k]*(1/10)^k*(9/10)^(nVal - k)*Boole[
Abs[(k + c0)/(nVal + 2*c0) - 1/10] <= (196/100)*Sqrt[((k + c0)/(nVal + 2*c0))*(1 - (k + c0)/(nVal + 2*c0))/(nVal + 2*c0)]],
{k, 0, nVal}], {nVal, {20, 100}}, {c0, {0, 2}}]]`