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 θ\theta.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 yy 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 𝒴\mathcal{Y} denote the sample space of all possible datasets and Θ\Theta the parameter space of all candidate values describing the population. Idealized Bayesian learning rests on three objects:

  1. Prior distribution p(θ)p(\theta): a probability distribution on Θ\Theta encoding beliefs about θ\theta before observing the dataset.
  2. Sampling model p(y∣θ)p(y \mid \theta): a family of distributions on 𝒴\mathcal{Y} specifying how probable each dataset yy would be if θ\theta were the true parameter value.
  3. Posterior distribution p(θ∣y)p(\theta \mid y): the updated distribution on Θ\Theta after observing yy, 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:
p(θ∣y)=p(y∣θ) p(θ)∫Θp(y∣θ~) p(θ~) dθ~. p(\theta \mid y) = \frac{p(y \mid \theta)\,p(\theta)}{\int_{\Theta} p(y \mid \tilde{\theta})\,p(\tilde{\theta})\,d\tilde{\theta}}. (1.1)

Remark 1.1 (Updating, not dictating). Bayes’ rule in (1.1) does not tell you what your prior beliefs p(θ)p(\theta) ought to be; it tells you the unique rationally coherent way your beliefs must change in response to new evidence yy.

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 p(θ)p(\theta) and p(y∣θ)p(y \mid \theta) 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 nn 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 θ∈[0,1]\theta \in [0, 1], the prevalence of an infectious disease in a small city, from a random sample of n=20n = 20 residents. The observed count Y∈{0,1,…,20}Y \in \{0, 1, \dots, 20\} follows a binomial sampling model, Y∣θ∼binomial⁡(20,θ)Y \mid \theta \sim \operatorname{binomial}(20, \theta).

Prior epidemiological studies from comparable cities put typical prevalence between 0.050.05 and 0.200.20 with mean around 0.100.10. For analytical convenience (justified in Chapter 3), we encode this information with a beta⁡(2,20)\operatorname{beta}(2, 20) prior:

θ∼beta⁡(2,20),E[θ]=222≈0.091,mode⁡[θ]=120=0.05,Pr⁡(θ<0.10)≈0.64. \theta \sim \operatorname{beta}(2, 20), \qquad E[\theta] = \frac{2}{22} \approx 0.091, \qquad \operatorname{mode}[\theta] = \frac{1}{20} = 0.05, \qquad \Pr(\theta < 0.10) \approx 0.64. (1.2)

Now suppose the survey observes zero infected individuals (Y=0Y = 0). Under beta–binomial conjugacy, the posterior is simply θ∣{Y=0}∼beta⁡(2+0, 20+20)=beta⁡(2,40)\theta \mid \{Y = 0\} \sim \operatorname{beta}(2 + 0,\, 20 + 20) = \operatorname{beta}(2, 40), yielding:

E[θ∣Y=0]=242≈0.048,mode⁡[θ∣Y=0]=140=0.025,Pr⁡(θ<0.10∣Y=0)≈0.926. E[\theta \mid Y = 0] = \frac{2}{42} \approx 0.048, \qquad \operatorname{mode}[\theta \mid Y = 0] = \frac{1}{40} = 0.025, \qquad \Pr(\theta < 0.10 \mid Y = 0) \approx 0.926. (1.3)
Three panels showing Binomial(20, theta) likelihoods, Beta(2, 20) prior updated to Beta(2, 40) posterior given y equals 0, and sensitivity contours of Pr(theta < 0.10 | Y = 0) over prior sample size w and prior mean theta_0
Figure 1.1: Left: binomial⁡(20,θ)\operatorname{binomial}(20, \theta) sampling distributions for three candidate prevalences. Center: updating beta⁡(2,20)\operatorname{beta}(2, 20) to beta⁡(2,40)\operatorname{beta}(2, 40) after observing Y=0Y = 0 shifts probability mass left and sharpens the peak. Right: sensitivity contours of Pr⁡(θ<0.10∣Y=0)\Pr(\theta < 0.10 \mid Y = 0) across prior mean θ0\theta_0 and prior sample size w=a+bw = a + b.

1.2.1Shrinkage as a Weighted Average and Prior Sensitivity

Writing θ0=a/(a+b)\theta_0 = a/(a+b) for the prior mean and w=a+bw = a + b for the prior sample size, the posterior expectation for any observed count yy decomposes cleanly into a convex combination of the sample mean y¯=y/n\bar{y} = y/n and the prior guess θ0\theta_0:

E[θ∣Y=y]=a+ya+b+n=nn+w y¯+wn+w θ0. E[\theta \mid Y = y] = \frac{a + y}{a + b + n} = \frac{n}{n + w}\,\bar{y} + \frac{w}{n + w}\,\theta_0. (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 y¯\bar{y} whenever the prior guess θ0\theta_0 lies within a surprisingly wide neighborhood of the truth.

  • When n≫wn \gg w, the data weight n/(n+w)→1n/(n+w) \to 1 and the prior washes out.
  • When nn is small, y¯\bar{y} is noisy (or degenerate, as when y=0y = 0), and borrowing weight ww from θ0\theta_0 stabilizes estimation.
  • Conversely, a strongly miscalibrated prior with large ww can dominate small-sample data—which is why checking prior sensitivity is essential:
Table 1.1: Prior sensitivity when n = 20 and y = 0: a diffuse prior and a well-calibrated epidemiological prior agree closely, whereas a strongly miscalibrated prior with w = n = 20 pulls the posterior away from the data.
Prior p(θ)p(\theta)Prior Mean θ0\theta_0Prior Weight wwPosterior (n=20,y=0n = 20, y = 0)E[θ∣Y=0]E[\theta \mid Y = 0]Pr⁡(θ<0.10∣Y=0)\Pr(\theta < 0.10 \mid Y = 0)
beta⁡(1,1)\operatorname{beta}(1, 1) (uniform)0.5000.50022beta⁡(1,21)\operatorname{beta}(1, 21)0.0450.0450.8910.891
beta⁡(2,20)\operatorname{beta}(2, 20) (epidemiological)0.0910.0912222beta⁡(2,40)\operatorname{beta}(2, 40)0.0480.0480.9260.926
beta⁡(10,10)\operatorname{beta}(10, 10) (strong, miscalibrated)0.5000.5002020beta⁡(10,30)\operatorname{beta}(10, 30)0.2500.2500.0040.004

1.2.2Why Classical Intervals Fail at Y=0Y = 0

The standard asymptotic 95% Wald confidence interval y¯±1.96y¯(1−y¯)/n\bar{y} \pm 1.96\sqrt{\bar{y}(1-\bar{y})/n} collapses to the single point [0,0][0, 0] when y=0y = 0, absurdly claiming near-certainty that nobody in the city is infected. Even across all possible outcomes Y∼binomial⁡(20,θ)Y \sim \operatorname{binomial}(20, \theta), its exact frequentist coverage at n=20n = 20 is severely erratic near the boundary: 0.6390.639 at θ=0.05\theta = 0.05, 0.8760.876 at θ=0.10\theta = 0.10, and 0.9210.921 at θ=0.20\theta = 0.20.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 z0.9752/2≈1.92z_{0.975}^2/2 \approx 1.92 pseudo-successes and pseudo-failures (rounded to 22 each in the popular “plus-four” rule), replacing y¯\bar{y} with

θ^=nn+4 y¯+4n+4⋅12, \hat{\theta} = \frac{n}{n+4}\,\bar{y} + \frac{4}{n+4}\cdot\frac{1}{2}, (1.5)

which achieves exact coverage 0.9840.984 at θ=0.05\theta = 0.05, 0.9570.957 at θ=0.10\theta = 0.10, and 0.9560.956 at θ=0.20\theta = 0.20 for n=20n = 20. 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 beta⁡(2,2)\operatorname{beta}(2, 2) prior!

1.3Example 2: High-Dimensional Predictive Modeling

Hoff’s second motivating example previews Chapter 9: predicting diabetes progression YiY_i from p=64p = 64 baseline predictors (10 main effects, 45 pairwise interactions, 9 quadratics) using n=342n = 342 training patients and evaluating on 100100 held-out test patients:

Yi=β1xi,1+β2xi,2+⋯+β64xi,64+σϵi. Y_i = \beta_1 x_{i,1} + \beta_2 x_{i,2} + \dots + \beta_{64} x_{i,64} + \sigma \epsilon_i. (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 βj\beta_j a 50% prior point mass at zero (a spike-and-slab prior).Note a subtlety we revisit in Chapter 9: independent Pr⁡(βj≠0)=1/2\Pr(\beta_j \neq 0) = 1/2 across p=64p = 64 predictors actually induces a binomial⁡(64,1/2)\operatorname{binomial}(64, 1/2) prior on model size centered at 32 active predictors. True multiplicity-adjusting sparsity places a hierarchical beta⁡(1,1)\operatorname{beta}(1, 1) 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:

Table 1.2: Why structural priors matter in high dimensions: comparing OLS, Bayesian model averaging, and Lasso on the 64-predictor diabetes task.
MethodStructural IdeaDiabetes Test MSE
Ordinary Least Squares (β^ols\hat{\beta}_{\text{ols}})Minimizes SSR⁡(β)=∑i=1n(yi−𝐱iTβ)2\operatorname{SSR}(\beta) = \sum_{i=1}^n (y_i - \mathbf{x}_i^T \beta)^2 with all 64 predictors0.670.67
Bayesian Model Averaging (β^Bayes=E[β∣y,X]\hat{\beta}_{\text{Bayes}} = E[\beta \mid y, X])Point mass at βj=0\beta_j = 0; averages over high-probability sparse models0.450.45
Lasso (β^lasso\hat{\beta}_{\text{lasso}})Robert Tibshirani. Regression Shrinkage and Selection via the Lasso. Journal of the Royal Statistical Society, Series B, 58(1):267–288, 1996Minimizes SSR⁡(β)+λ∑j=1p∣βj∣\operatorname{SSR}(\beta) + \lambda \sum_{j=1}^p \lvert \beta_j \rvert; equivalent to posterior mode under i.i.d. Laplace (double-exponential) priors on βj\beta_jSparse MAP shrinkage (not reported in Hoff)

1.4Key Takeaways & Python Check

  • Prior + Likelihood →\to Posterior: Bayes’ rule (1.1) converts prior uncertainty and a sampling model into a complete posterior distribution over θ\theta.
  • Shrinkage protects small samples: Posterior means naturally interpolate between y¯\bar{y} and θ0\theta_0 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 n/(n+w)n/(n+w) in (1.4) is the same however badly y¯\bar{y} disagrees with θ0\theta_0. Instead, let p1=beta⁡(a,b)p_1 = \operatorname{beta}(a, b) be the informative prior, p0=beta⁡(1,1)p_0 = \operatorname{beta}(1, 1) a vague one, and ω\omega the prior probability that the informative component is relevant:

p(θ)=ω p1(θ)+(1−ω) p0(θ),p(θ∣y)=ω∗p1(θ∣y)+(1−ω∗) p0(θ∣y),ω∗=ω m1(y)ω m1(y)+(1−ω) m0(y),mj(y)=∫01p(y∣θ) pj(θ) dθ. \begin{gathered} p(\theta) = \omega\,p_1(\theta) + (1 - \omega)\,p_0(\theta), \qquad p(\theta \mid y) = \omega^{*} p_1(\theta \mid y) + (1 - \omega^{*})\,p_0(\theta \mid y), \\ \omega^{*} = \frac{\omega\,m_1(y)}{\omega\,m_1(y) + (1 - \omega)\,m_0(y)}, \qquad m_j(y) = \int_0^1 p(y \mid \theta)\,p_j(\theta)\,d\theta. \end{gathered} (1.7)

Why it holds: p(y∣θ) pj(θ)=mj(y) pj(θ∣y)p(y \mid \theta)\,p_j(\theta) = m_j(y)\,p_j(\theta \mid y) for each component, so Bayes’ rule (1.1) reweights the components by how well each predicted yy. Take n=20n = 20 and ω=0.8\omega = 0.8. With beta⁡(2,20)\operatorname{beta}(2, 20) as p1p_1, observing y=0y = 0 raises the weight to ω∗=0.956\omega^{*} = 0.956 (posterior mean 0.04750.0475), whereas a conflicting y=10y = 10 drops it to 0.0640.064 (mean 0.4860.486, against 0.2860.286 for the informative prior alone). With the miscalibrated beta⁡(10,10)\operatorname{beta}(10, 10) and y=0y = 0, ω∗=0.012\omega^{*} = 0.012 and the mean is 0.0480.048, not the 0.2500.250 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 n≫wn \gg w. Since ω\omega 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 α\alpha near 11:

pαprior(θ∣y)∝p(y∣θ) p(θ)α,pαlik(θ∣y)∝p(y∣θ)α p(θ). p_{\alpha}^{\text{prior}}(\theta \mid y) \propto p(y \mid \theta)\,p(\theta)^{\alpha}, \qquad p_{\alpha}^{\text{lik}}(\theta \mid y) \propto p(y \mid \theta)^{\alpha}\,p(\theta). (1.8)

Why it works: pαprior(θ∣y)/p(θ∣y)∝p(θ)α−1p_{\alpha}^{\text{prior}}(\theta \mid y)/p(\theta \mid y) \propto p(\theta)^{\alpha - 1}, 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 beta⁡(α(a−1)+1+y, α(b−1)+1+n−y)\operatorname{beta}\bigl(\alpha(a-1) + 1 + y,\, \alpha(b-1) + 1 + n - y\bigr) and beta⁡(a+αy, b+α(n−y))\operatorname{beta}\bigl(a + \alpha y,\, b + \alpha(n - y)\bigr). For n=20n = 20, y=0y = 0 and α=12,1,2\alpha = \tfrac12, 1, 2, the beta⁡(2,20)\operatorname{beta}(2, 20) posterior mean barely moves under prior scaling (0.0470.047, 0.0480.048, 0.0480.048). For beta⁡(10,10)\operatorname{beta}(10, 10) it moves up under prior scaling (0.1770.177, 0.2500.250, 0.3280.328) and down under likelihood scaling (0.3330.333, 0.2500.250, 0.1670.167): 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 p(θ)αp(\theta)^{\alpha} 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 n=20n = 20, ω=0.8\omega = 0.8; 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}")
Write the marginal likelihood mj(y)m_j(y) of a beta⁡(a,b)\operatorname{beta}(a, b) component, up to the common binomial coefficient.
// Chapter 1 (modern): robust mixture weights & power-scaled tail probabilities
const mj = await show`Beta[a + y, b + n - y] / Beta[a, b]`
mj(y)∝B(a+y,b+n−y)B(a,b) m_j(y) \propto \frac{B(a+y,b+n-y)}{B(a,b)} Confirm that mjm_j is the integral of the likelihood kernel against the beta⁡(a,b)\operatorname{beta}(a, b) density.
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})]]`
1mj(y)∫01θy(1−θ)n−y pj(θ) dθ=1 \frac{1}{m_j(y)}\int_0^1 \theta^y(1-\theta)^{n-y}\,p_j(\theta)\,d\theta = 1 Write the posterior weight ω∗\omega^* of the informative component against the uniform one, m0(y)=B(1+y,1+n−y)m_0(y) = B(1 + y, 1 + n - y).
const wStar = await show`om*(${mj}) / (om*(${mj}) + (1 - om)*Beta[1 + y, 1 + n - y])`
ω∗=ω B(a+y, b+n−y)B(a,b)ω B(a+y, b+n−y)B(a,b)+(1−ω) B(1+y, 1+n−y) \omega^{*} = \frac{\omega\,\dfrac{B(a+y,\,b+n-y)}{B(a,b)}}{\omega\,\dfrac{B(a+y,\,b+n-y)}{B(a,b)} + (1-\omega)\,B(1+y,\,1+n-y)} Write the mixture posterior mean: the ω∗\omega^*-weighted average of the two component posterior means.
const mixMean = await show`(${wStar})*(a + y)/(a + b + n) + (1 - (${wStar}))*(1 + y)/(2 + n)`
𝔼[θ∣y]=ω∗ a+ya+b+n+(1−ω∗) 1+y2+n \mathbb{E}[\theta \mid y] = \omega^{*}\,\frac{a+y}{a+b+n} + \bigl(1-\omega^{*}\bigr)\,\frac{1+y}{2+n} Evaluate (ω∗,E[θ∣y])(\omega^*, E[\theta \mid y]) for (a,b,y)=(2,20,0)(a, b, y) = (2, 20, 0), (2,20,10)(2, 20, 10), (10,10,0)(10, 10, 0).
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}}}]]`
(ω∗,  𝔼[θ∣y])(2,20,0), (2,20,10), (10,10,0)=(0.955580.04752290.06434410.4862120.01205860.0479211) \begin{aligned} &\bigl(\omega^{*},\; \mathbb{E}[\theta \mid y]\bigr)_{(2,20,0),\,(2,20,10),\,(10,10,0)} \\ &= \left( \begin{array}{cc} 0.95558 & 0.0475229 \\ 0.0643441 & 0.486212 \\ 0.0120586 & 0.0479211 \\ \end{array} \right) \end{aligned} Tabulate the exact prior-scaled posterior means: nearly flat for beta⁡(2,20)\operatorname{beta}(2, 20), rising for beta⁡(10,10)\operatorname{beta}(10, 10).
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}}]`
𝔼αprior[θ∣y=0]∣α=1/2, 1, 2=(3641213621162141958) \mathbb{E}_{\alpha}^{\text{prior}}[\theta \mid y=0]\big|_{\alpha = 1/2,\,1,\,2} = \left( \begin{array}{ccc} \frac{3}{64} & \frac{1}{21} & \frac{3}{62} \\ \frac{11}{62} & \frac{1}{4} & \frac{19}{58} \\ \end{array} \right) Evaluate the likelihood-scaled Pr⁡(θ<0.1∣y=0)\Pr(\theta < 0.1 \mid y = 0) for α=12,1,2\alpha = \tfrac12, 1, 2 under each prior.
await show`N[Table[BetaRegularized[1/10, p[[1]], p[[2]] + 20*al], {p, {{2, 20}, {10, 10}}}, {al, {1/2, 1, 2}}]]`
Pr⁡αlik(θ<0.1∣y=0)∣α=1/2, 1, 2=(0.8304350.9260960.9874210.0003325960.004164720.0665894) \begin{aligned} &\Pr\nolimits_{\alpha}^{\text{lik}}(\theta < 0.1 \mid y=0)\big|_{\alpha = 1/2,\,1,\,2} \\ &= \left( \begin{array}{ccc} 0.830435 & 0.926096 & 0.987421 \\ 0.000332596 & 0.00416472 & 0.0665894 \\ \end{array} \right) \end{aligned}

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 ZZ, posterior mean, posterior variance, mode (for a+y>1a+y > 1, b+n−y>1b+n-y > 1), and symbolic tail probability Pr⁡(θ<c∣Y=y)\Pr(\theta < c \mid Y = y) completely symbolically, then instantiate the symbolic formulas at (n,y,c)=(20,0,1/10)(n, y, c) = (20, 0, 1/10) to cross-check the Python output above.

Integrate the unnormalized Beta–Binomial kernel over θ∈(0,1)\theta \in (0, 1) to obtain the normalizing constant ZZ.
// 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}]]]`
∫01θa+y−1(1−θ)b+n−y−1 dθ=Γ(b+n−y)Γ(a+y)Γ(a+b+n) \begin{aligned} &\int_0^1 \theta^{a+y-1}(1-\theta)^{b+n-y-1}\,d\theta \\ &= \frac{\Gamma (b+n-y) \Gamma (a+y)}{\Gamma (a+b+n)} \end{aligned} Compute the symbolic posterior mean E[θ∣y]E[\theta \mid y] by integrating θ\theta against the normalized posterior.
const mean = await show`Assuming[a > 0 && b > 0 && y >= 0 && n >= y,
  FullSimplify[Integrate[th * ${kernel}, {th, 0, 1}] / ${Z}]]`
𝔼[θ∣y]=a+ya+b+n \mathbb{E}[\theta \mid y] = \frac{a+y}{a+b+n} Compute the symbolic posterior variance Var⁡(θ∣y)=E[θ2∣y]−(E[θ∣y])2\operatorname{Var}(\theta \mid y) = E[\theta^2 \mid y] - (E[\theta \mid y])^2.
const postVar = await show`Assuming[a > 0 && b > 0 && y >= 0 && n >= y,
  FullSimplify[Integrate[th^2 * ${kernel}, {th, 0, 1}] / ${Z} - (${mean})^2]]`
Var⁡(θ∣y)=(b+n−y)(a+y)(a+b+n)2(1+a+b+n) \operatorname{Var}(\theta \mid y) = \frac{(b+n-y) (a+y)}{(a+b+n)^2 (1+a+b+n)} Differentiate the log-kernel to find the closed-form posterior mode θ^MAP\hat{\theta}_{\text{MAP}}.
// 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]]]`
θ^MAP=−1+a+y−2+a+b+n \hat{\theta}_{\text{MAP}} = \frac{-1+a+y}{-2+a+b+n} Integrate the Beta density up to cc to express Pr⁡(θ<c∣y)\Pr(\theta < c \mid y) via the incomplete Beta function.
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}`
Pr⁡(θ<c∣y)=Bc(a+y,b+n−y)B(a+y,b+n−y) \Pr(\theta < c \mid y) = \frac{B_c(a+y,b+n-y)}{B(a+y,b+n-y)} Verify that the posterior mean is a precision-weighted average of the sample proportion and prior mean.
await show`Simplify[${mean} - (n/(n + w)*(y/n) + w/(n + w)*(a/w)) /. w -> a + b]`
𝔼[θ∣y]−(nn+wyn+wn+waw)=0 \mathbb{E}[\theta \mid y] - \left(\frac{n}{n+w}\frac{y}{n} + \frac{w}{n+w}\frac{a}{w}\right) = 0 Instantiate the posterior mean and Pr⁡(θ<0.10∣y=0)\Pr(\theta < 0.10 \mid y=0) across the uniform, epidemiological, and strong-wrong priors.
// 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}}}]]`
(𝔼[θ∣y=0],  Pr⁡(θ<0.10∣y=0))Unif, Epi, Strong=(0.04545450.8905810.0476190.9260960.250.00416472) \begin{aligned} &\bigl(\mathbb{E}[\theta \mid y=0],\; \Pr(\theta < 0.10 \mid y=0)\bigr)_{\text{Unif, Epi, Strong}} \\ &= \left( \begin{array}{cc} 0.0454545 & 0.890581 \\ 0.047619 & 0.926096 \\ 0.25 & 0.00416472 \\ \end{array} \right) \end{aligned}

1.7Exercises

Exercise 1.2. In the rare-event survey (n=20n = 20, y=0y = 0), suppose a skeptical colleague insists on a prior centered at θ0=0.20\theta_0 = 0.20. How large can their prior sample size w=a+bw = a + b be before Pr⁡(θ<0.10∣Y=0)\Pr(\theta < 0.10 \mid Y = 0) drops below 0.500.50? Verify your answer numerically in Python using scipy.stats.beta.cdf.

Symbolic Solution & InstantiationWrite Pr⁡(θ<c∣y=0)\Pr(\theta < c \mid y = 0) symbolically as a regularized incomplete Beta ratio in prior weight ww.
// 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]`
Pr⁡(θ<c∣y=0)=Bc(θ0w,n+(1−θ0)w)B(θ0w,n+(1−θ0)w) \begin{aligned} &\Pr(\theta < c \mid y = 0) \\ &= \frac{B_c(\theta_0 w,n+(1-\theta_0) w)}{B(\theta_0 w,n+(1-\theta_0) w)} \end{aligned} Solve numerically for the critical prior sample size w∗w^* where Pr⁡(θ<0.10∣y=0)=1/2\Pr(\theta < 0.10 \mid y = 0) = 1/2.
await show`w /. FindRoot[(${cdf} /. {c -> 1/10, th0 -> 1/5, n -> 20}) == 1/2, {w, 15, 35}]`
w∗∣c=0.1,  θ0=0.2,  n=20=22.6228 w^*\big|_{c=0.1,\;\theta_0=0.2,\;n=20} = 22.6228 Evaluate Pr⁡(θ<0.10∣y=0)\Pr(\theta < 0.10 \mid y = 0) at the straddling integers w=22w = 22 and w=23w = 23.
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}}]`
(Pr⁡(θ<0.1∣y=0,w=22),  Pr⁡(θ<0.1∣y=0,w=23))={0.512971,0.492266} \begin{aligned} &\bigl(\Pr(\theta < 0.1 \mid y=0, w=22),\;\Pr(\theta < 0.1 \mid y=0, w=23)\bigr) \\ &= \{0.512971,0.492266\} \end{aligned}

Exercise 1.3. Show that if Y∣β,σ2∼𝒩n(Xβ,σ2In)Y \mid \beta, \sigma^2 \sim \mathcal{N}_n(X\beta, \sigma^2 I_n) and β1,…,βp∼i.i.d.Laplace⁡(0,b)\beta_1, \dots, \beta_p \stackrel{\text{i.i.d.}}{\sim} \operatorname{Laplace}(0, b) with density p(βj)=12bexp⁡(−∣βj∣/b)p(\beta_j) = \frac{1}{2b}\exp(-\lvert \beta_j \rvert / b), then maximizing log⁡p(β∣y,X,σ2)\log p(\beta \mid y, X, \sigma^2) is equivalent to minimizing SSR⁡(β)+λ∑j=1p∣βj∣\operatorname{SSR}(\beta) + \lambda \sum_{j=1}^p \lvert \beta_j \rvert. Express λ\lambda in terms of σ2\sigma^2 and bb.

Symbolic Solution & InstantiationMultiply the negative log-posterior under a Laplace prior by 2σ22\sigma^2 to reveal the ℓ1\ell_1-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)]`
−2σ2log⁡p(β∣y,σ2,b)+const=2∥β∥1σ2b+SSR⁡ \begin{aligned} &-2\sigma^2 \log p(\beta \mid y, \sigma^2, b) + \text{const} \\ &= \frac{2 \|\beta\|_1 \sigma^2}{b}+\operatorname{SSR} \end{aligned} Extract the coefficient of ∥β∥1\|\beta\|_1 to identify the exact Lasso penalty λ=2σ2/b\lambda = 2\sigma^2/b.
const lam = await show`Coefficient[${obj}, l1]`
λ=2σ2b \lambda = \frac{2 \sigma^2}{b} Instantiate λ\lambda at σ2=1\sigma^2 = 1 and Laplace scale b=1/2b = 1/2.
await show`${lam} /. {s2 -> 1, b -> 1/2}`
λ∣σ2=1,  b=1/2=4 \lambda\big|_{\sigma^2=1,\; b=1/2} = 4

Exercise 1.4. Plot the exact frequentist coverage of the 95% Wald interval and the 95% plus-four interval as functions of θ∈(0,1)\theta \in (0, 1) for n=20n = 20 and n=100n = 100. Why does the coverage curve oscillate sharply even for n=100n = 100?

Symbolic Solution & InstantiationExpress the exact finite-sample Binomial coverage probability as a sum over accepted counts kk.
// 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}]`
Covg⁡n(θ)=∑k=0n(1−θ)−k+nθk(nk)𝟏[∣−θ+p^(k)∣≤zse⁡(k)] \begin{aligned} &\operatorname{Covg}_n(\theta) \\ &= \sum_{k=0}^n (1-\theta)^{-k+n} \theta^k \binom{n}{k} \mathbf{1} [| -\theta +\hat{p} (k)| \leq z \operatorname{se} (k)] \end{aligned} Evaluate exact coverage at θ=0.10\theta = 0.10 for n∈{20,100}n \in \{20, 100\}, comparing Wald versus plus-four intervals.
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}}]]`
(Covg⁡n,Wald(0.1),  Covg⁡n,plus-4(0.1))n∈{20, 100}=(0.8760370.9568260.9324160.952273) \begin{aligned} &\bigl(\operatorname{Covg}_{n,\text{Wald}}(0.1),\; \operatorname{Covg}_{n,\text{plus-4}}(0.1)\bigr)_{n \in \{20,\,100\}} \\ &= \left( \begin{array}{cc} 0.876037 & 0.956826 \\ 0.932416 & 0.952273 \\ \end{array} \right) \end{aligned}