Chapter 9
Linear Regression
Regression asks a conditional question: how does the distribution of change as changes? Up to now every observation in a group shared the same mean. Here each observation carries its own mean, tied to the others through a short coefficient vector .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 The Bayesian treatment of estimation turns out to be the multivariate normal update of Chapter 7 in a new costume. The genuinely new idea is what comes next: treating which variables belong in the model as one more unknown with a posterior distribution.
9.1The Normal Linear Model#
A linear regression model asserts that the conditional mean is linear in the parameters, ; the regressors themselves may be squares, products, or indicators of anything we measured. Stacking observations, with the matrix whose -th row is , the normal linear model is
(9.1)where . Setting its gradient to zero gives the ordinary least squares estimate , whose sampling variance is . Completing the square around it yields the regression analogue of the sum-of-squares decomposition from Chapter 5:
(9.2)the cross term vanishing because the OLS residual is orthogonal to the columns of . Hence is sufficient for .
Running example. Twelve men were randomized to twelve weeks of flat-terrain running or step aerobics; is the change in maximal oxygen uptake. With for aerobics and equal to age, Hoff fits
(9.3)that is, two unrelated lines: for runners and for aerobics.Page 151 of the 2009 printing indexes the two lines by ; since is the intercept column, the switch is . See Appendix C. Least squares gives with standard errors and . Read coefficient by coefficient, the group effect looks negligible. We shall see that this reading is wrong.
9.2Semiconjugate Priors and the Gibbs Sampler#
As a function of , the likelihood (9.1) is an exponentiated quadratic, so a normal prior is conditionally conjugate.
Proposition 9.1 (Semiconjugate Full Conditionals). Under independent priors and ,
(9.4)Proof. Collecting the terms in from prior and likelihood gives the exponent
whose precision matrix and linear term are read off directly. With , the second conditional is proportional to , a gamma kernel. □
Alternating these two draws is a complete Gibbs sampler. Precisions add and means average by precision, exactly as in one dimension: a vague prior () returns , and a noisy experiment () returns . The obstacle is not computation but elicitation: has variances and correlations, and few of us hold opinions about the prior correlation between an intercept and an interaction.
9.3Default Priors: Unit Information and the -Prior#
Two principles let the design matrix supply the prior covariance for us.
One observation’s worth of information. The data contribute precision , the work of observations. A unit information priorRobert E. Kass and Larry Wasserman. A Reference Bayesian Test for Nested Hypotheses and Its Relationship to the Schwarz Criterion. Journal of the American Statistical Association, 90(431):928–934, 1995 therefore uses . Kass and Wasserman also center it at , so it borrows a little from and is not a prior in the strict sense; plays the same role for the variance.
Invariance to units. Recording age in months rather than years should not change what we believe about the effect of aging. Suppose the regressors are transformed as with invertible. The same mean vector is , so coherent priors must satisfy .
Proposition 9.2 (Invariance of the g-Prior). Let the prior rule assign to the coefficients of any full-rank design , with not depending on the units. Then analysts using and reach the same prior, and hence the same posterior, for .
Proof. The second analyst has , so , and the mean is in both cases. The likelihood depends on the coefficients only through , so the posteriors agree as well. □
Choosing gives the zero-centered Zellner -prior:Arnold Zellner. On Assessing Prior Distributions and Bayesian Regression Analysis with -Prior Distributions. In Bayesian Inference and Decision Techniques, pages 233–243. North-Holland, Amsterdam, 1986
(9.5)with carrying one observation’s information. Scaling the prior by restores full conjugacy, so Gibbs sampling is unnecessary.
Theorem 9.3 (Exact Posterior under the g-Prior). Under (9.1) and (9.5), define
(9.6)Then
and
(9.7)Proof. Let . Completing the square in the combined exponent,
The first term gives the conditional distribution of . Integrating it over contributes , while the prior’s normalizing constant is ; their product is . What remains, as a function of , is , which multiplies the prior to give the stated gamma posterior. □
The shrinkage factor is the same scalar in every direction, and interpolates between the residual sum of squares and the total sum of squares.On p. 157 of Hoff (2009) the normalizing constant of the -prior is printed as ; the exponent should be , as the factor on the next page requires. See Appendix C. To sample the joint posterior, draw and then given : every pair is an independent exact draw.
9.3.1Collinearity and the Right Contrast#
For the oxygen data with and , (9.6) gives , the posterior mean is , and the exact posterior standard deviations are about .Marginally is multivariate with degrees of freedom, and . Hoff’s Monte Carlo values come from 1,000 draws of a heavy-tailed quantity and agree within simulation error. Both marginal intervals for and comfortably contain zero.
But is the group difference at age zero, an extrapolation of more than two decades, and it is almost perfectly confounded with : the posterior correlation is . The estimand a scientist cares about is the group contrast at an attainable age, , and its posterior follows from the same joint draws. At age 24 its posterior mean is close to with a standard deviation near , not . The exact 95% intervals exclude zero at ages 22 through 25, where both groups contributed data, and widen on either side (Figure 9.1, right). Two coefficients that are individually uncertain can have a sharply determined linear combination; never judge a joint hypothesis from marginal intervals.
9.4Model Selection and the Backward-Elimination Trap#
Hoff’s second example has 442 diabetes patients and candidate regressors (10 main effects, 45 interactions, 9 squares), split into 342 training and 100 test cases with all variables standardized. Full OLS attains test error , against for predicting zero. Backward elimination, which repeatedly drops the regressor with the smallest until every survivor exceeds , keeps 20 variables and lowers the test error to . So far, so good.
Now permute at random, so that no regressor has any true association with the response. Initially only one -statistic exceeds . Yet after elimination Hoff is left with 18 regressors, 17 of them with and four with . The procedure manufactures significance: each deletion discards a noise direction whose estimate happened to be small, and the survivors are exactly those whose noise happened to be large. A -statistic computed after selection no longer has a distribution, and nothing in the output warns us.
9.5Spike-and-Slab: Models as Parameters#
The Bayesian response is to place the question inside the model. Write with and , so that each indexes one regression model. The induced prior on has an atom at zero and a continuous part, a spike-and-slab prior; George and McCulloch pioneered Gibbs sampling over such indicators.Edward I. George and Robert E. McCulloch. Variable Selection via Gibbs Sampling. Journal of the American Statistical Association, 88:881–889, 1993Their original spike is a narrow normal rather than a point mass at zero. The point-mass version used here is Hoff’s, and it permits the exact integration below. Let be the matrix of included columns and apply the -prior to them: .
Proposition 9.4 (Exact Marginal Likelihood of a Model). With and as in (9.6) computed from (and when ),
(9.8)Proof. Multiply from Theorem 9.3 by the gamma prior density and integrate over :
and the powers of combine to , turning into . □
Two details deserve care. First, the exponent of the bracket is exactly .The intermediate gamma-normalizer on p. 165 of Hoff (2009) is printed with exponent (and there lacks a transpose on its last ); the final formula on the same page is correct. See Appendix C. Second, keep the factor . It cancels from ratios only when is the same for all models. Under Hoff’s model-specific choice , (the OLS residual variance of model ), , it survives, and the Bayes factor is
(9.9)The first factor charges about per extra regressor, the same penalty rate as BIC; the last rewards fit. No test and no stopping rule is involved.
| Model for | |||
|---|---|---|---|
| constant | |||
| group | |||
| age | |||
| group + age (parallel lines) | |||
| group + age + interaction |
Age is essentially certain to matter, and parallel lines beat the interaction model by a factor of . The three models containing a group effect total , up from a prior : modest evidence, honestly reported (Table 9.1).
Remark 9.5 (Two paradoxes, and what uniform model priors really say). Hold common to all models.
- Lindley’s paradox. For fixed data, the Bayes factor of a larger model against a nested one is as . A “noninformative” slab is therefore maximally informative: it forces the smaller model. Diffuse proper priors are harmless for estimation but not for comparison, and improper ones leave the Bayes factor undefined.
- The information paradox. For fixed , , so the Bayes factor of against the empty model never exceeds , no matter how perfectly the model fits. Placing a prior on can remove this defect; Liang et al. study such mixtures of -priors and their consistency.Feng Liang, Rui Paulo, German Molina, Merlise A. Clyde, and James O. Berger. Mixtures of Priors for Bayesian Variable Selection. Journal of the American Statistical Association, 103(481):410–423, 2008
- Multiplicity. Setting is a binomial prior on model size: for it expects active regressors. Letting a common inclusion probability be instead gives , which penalizes the number of opportunities for a false discovery automatically.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 The factor penalizes complexity within a model; it is not a correction for how many models were tried.
9.6Collapsed Gibbs Sampling and Model Averaging#
With there are models. But (9.8) evaluates any one of them in closed form, so we can run a Markov chain on alone with and integrated out, a collapsed Gibbs sampler.
Algorithm 9.6 (Collapsed Gibbs Sampler for Variable Selection). Given , set and proceed as follows.
The draws of never feed back into the chain: they are ancestral samples given , so only needs to mix. (A sampler that alternated with would be stuck, since forces .) Averaging over the chain gives the Bayesian model averaged estimateDavid Madigan and Adrian E. Raftery. Model Selection and Accounting for Model Uncertainty in Graphical Models Using Occam’s Window. Journal of the American Statistical Association, 89:1535–1546, 1994
(9.11)On the diabetes data, scans find six regressors with inclusion probability above , and the model-averaged test error is , better than full OLS () and backward elimination (). On the permuted response, every inclusion probability is below and all but two are below : the trap does not spring. A sobering count accompanies this success. Only 32 models were visited more than once, so the chain estimates one-dimensional margins of , not the probabilities of individual models.
Remark 9.7 (An inclusion probability is not an effect size). The posterior inclusion probability measures evidence that within the considered family and given the slab width . A negligible effect measured on a million cases can have probability near ; two nearly duplicate regressors can share one strong effect and each show a probability near . Report it beside the posterior of itself, and inspect joint inclusion for correlated regressors.
import itertools
import numpy as np
from scipy.special import gammaln
rng = np.random.default_rng(9)
age = np.array([23, 22, 22, 25, 27, 20, 31, 23, 27, 28, 22, 24], dtype=float)
grp = np.repeat([0.0, 1.0], 6) # 0 = running, 1 = aerobics
y = np.array([-0.87, -10.74, -3.27, -1.97, 7.50, -7.25,
17.05, 4.96, 10.40, 11.05, 0.26, 2.51])
X = np.column_stack([np.ones(12), grp, age, grp * age])
n, p = X.shape
g, nu0 = float(n), 1.0
def summaries(X):
"""Return OLS coefficients, residual variance, and SSR_g for design X."""
if X.shape[1] == 0:
return np.zeros(0), y @ y / n, y @ y
b = np.linalg.solve(X.T @ X, X.T @ y)
fit = y @ X @ b # y' H y
return b, (y @ y - fit) / (n - X.shape[1]), y @ y - g / (g + 1) * fit
# 1. Exact i.i.d. posterior sampling under the g-prior (no Markov chain)
b_ols, s20, ssr_g = summaries(X)
S = 20_000
sig2 = 1.0 / rng.gamma((nu0 + n) / 2, 2.0 / (nu0 * s20 + ssr_g), size=S) # scale = 1/rate
L = np.linalg.cholesky(g / (g + 1) * np.linalg.inv(X.T @ X))
beta = g / (g + 1) * b_ols + np.sqrt(sig2)[:, None] * (rng.normal(size=(S, p)) @ L.T)
print("posterior mean", beta.mean(0).round(2), " corr(b2,b4) =",
np.corrcoef(beta[:, 1], beta[:, 3])[0, 1].round(3))
for a in (20, 24, 30):
print(f"contrast at age {a}:", np.quantile(beta[:, 1] + beta[:, 3] * a, [.025, .5, .975]).round(2))
# 2. Log marginal likelihood, retaining (nu0 * s20)^(nu0/2) since s20 varies by model
def log_marg(z):
_, s2, ssr = summaries(X[:, z])
return (-0.5 * n * np.log(np.pi) - 0.5 * z.sum() * np.log1p(g)
+ 0.5 * nu0 * np.log(nu0 * s2) - 0.5 * (nu0 + n) * np.log(nu0 * s2 + ssr)
+ gammaln((nu0 + n) / 2) - gammaln(nu0 / 2))
# 3. Collapsed Gibbs over all 2^4 models (uniform prior), checked by enumeration
z = np.ones(p, dtype=bool)
lp, pip, bma = log_marg(z), np.zeros(p), np.zeros(p)
for s in range(5_000):
for j in rng.permutation(p):
zp = z.copy()
zp[j] = not zp[j]
lpp = log_marg(zp)
if np.log(rng.uniform()) < -np.logaddexp(0.0, lp - lpp): # Pr(flip) = 1/(1+e^(lp-lpp))
z, lp = zp, lpp
pip += z / 5_000
bma[z] += g / (g + 1) * summaries(X[:, z])[0] / 5_000 # Rao-Blackwellized mean
models = [np.array(m, dtype=bool) for m in itertools.product([0, 1], repeat=p)]
lps = np.array([log_marg(m) for m in models])
w = np.exp(lps - lps.max())
w /= w.sum()
print("inclusion (Gibbs):", pip.round(3), " (exact):", (w @ np.array(models)).round(3))
print("model-averaged beta:", bma.round(2))9.7Modern Developments: Shrinkage, Correlated Selection, and Stacking#
9.7.1The Horseshoe and Regularized Horseshoe Priors#
The -prior shrinks every coefficient by the same factor in (9.7), whereas a global–local prior gives each coefficient a shrinkage factor of its own.Beyond Hoff (2009). This material is not in Hoff’s book; the horseshoe of Carvalho, Polson, and Scott (2010) and its regularized form (Piironen and Vehtari, 2017) offer a continuous alternative to the spike-and-slab of Section 9.5. The horseshoeC. M. Carvalho, N. G. Polson, and J. G. Scott. The horseshoe estimator for sparse signals. Biometrika, 97(2):465–480, 2010. doi: 10.1093/biomet/asq017 takes half-Cauchy scales; for an orthogonal design with ,
(9.12)Why it holds. Each coordinate is a normal update with data precision and prior precision , and is the prior’s share. At the half-Cauchy makes : mass piles up at (keep) and (discard). Writing each as a mixture of inverse-gammas restores Gibbs sampling,Enes Makalic and Daniel F. Schmidt. A Simple Sampler for the Horseshoe Estimator. IEEE Signal Processing Letters, 23(1):179–182, 2016. doi: 10.1109/LSP.2015.2503725 and can be drawn in operations.Anirban Bhattacharya, Antik Chakraborty, and Bani K. Mallick. Fast sampling with Gaussian scale mixture priors in high-dimensional regression. Biometrika, 103(4):985–991, 2016. doi: 10.1093/biomet/asw042 A guess of relevant regressors suggests , and replacing by caps the slab at width , the regularized horseshoe.Juho Piironen and Aki Vehtari. Sparsity information and regularization in the horseshoe and other shrinkage priors. Electronic Journal of Statistics, 11(2):5018–5051, 2017. doi: 10.1214/17-EJS1337SI Beware the Bayesian lasso, with its double-exponential prior of rate : its mode (the lassoRobert Tibshirani. Regression Shrinkage and Selection via the Lasso. Journal of the Royal Statistical Society, Series B, 58(1):267–288, 1996) is sparse, but its full posterior is not. In the sequence model (, ) with true and , each coordinate keeps posterior spread of order , so is of order while the mode’s error vanishes.Ismaël Castillo, Johannes Schmidt-Hieber, and Aad van der Vaart. Bayesian linear regression with sparse priors. The Annals of Statistics, 43(5):1986–2018, 2015. doi: 10.1214/15-AOS1334
When to use it. Prefer the horseshoe for prediction or estimation with large or comparable to and no need for exact zeros. Keep Hoff’s Algorithm 9.6 when model probabilities are themselves the question.
9.7.2Sum of Single Effects (SuSiE)#
Remark 9.7 warned that two nearly duplicate regressors share one strong effect, each showing an inclusion probability near ; SuSiE turns that warning into a reportable answer, the set of regressors that holds the effect.Beyond Hoff (2009). This material is not in Hoff’s book; the sum-of-single-effects model is due to Wang, Sarkar, Carbonetto, and Stephens (2020) and complements per-variable inclusion probabilities. It writes as vectors with one nonzero entry each:Gao Wang, Abhishek Sarkar, Peter Carbonetto, and Matthew Stephens. A Simple New Approach to Variable Selection in Regression, with Application to Genetic Fine Mapping. Journal of the Royal Statistical Society Series B: Statistical Methodology, 82(5):1273–1300, 2020. doi: 10.1111/rssb.12388
(9.13)with , , and the residual after subtracting the other expected effects.
Why it holds. With a single effect there are only models, so Bayes’ rule enumerates them exactly, and is a ratio of normal marginals. Cycling over (iterative Bayesian stepwise selection) is coordinate ascent on a variational objective in which the effects are independent but the choice within each is not. If and , then . When they carry a strong effect, and the 95% credible set is : we are sure there is an effect, and unsure which column carries it.
When to use it. Choose SuSiE for sparse problems with strongly correlated regressors, such as genetic fine mapping. Because it is variational, dependence between effects is lost and local optima are possible; for moderate , or dense signals, Algorithm 9.6 targets the exact posterior.
9.7.3Bayesian Stacking in -Open Settings#
The average (9.11) weights models by , the right weights when one of the candidates is true (-closed) but not when all are wrong (-open).Beyond Hoff (2009). This material is not in Hoff’s book; stacking is a much older idea for point predictions, extended to full predictive distributions by Yao, Vehtari, Simpson, and Gelman (2018) as an alternative to model averaging. As grows, model averaging typically puts all its weight on the single model closest to the truth in Kullback–Leibler divergence, even if a mixture predicts better. Stacking chooses the mixture directly by its leave-one-out log score:Yuling Yao, Aki Vehtari, Daniel Simpson, and Andrew Gelman. Using Stacking to Average Bayesian Predictive Distributions (with Discussion). Bayesian Analysis, 13(3):917–1007, 2018. doi: 10.1214/17-BA1091
(9.14)Why it holds. Each held-out term estimates the mixture’s expected log score on new data without using twice, and the objective is concave on the simplex. Under the -prior, the leave-one-out terms need no refitting. Hold the prior, including , fixed and let be the matrix in (9.6). Marginally is multivariate with scale matrix , so
(9.15)with location and squared scale; the location does not depend on , which cancels. The choice behind Table 9.1 uses all of , so it would have to be recomputed, or fixed, for an honest hold-out score.
When to use it. Stack when the goal is prediction and no model is believed. Keep Hoff’s averaging when a true model is plausible or the posterior probabilities answer the scientific question: stacking weights are not probabilities, and near-identical models split theirs arbitrarily.
9.7.4Computational & Symbolic Check#
The script compares draws of the shrinkage factor in (9.12) with , and evaluates the single-effect probabilities of (9.13) for two identical regressors and one unrelated regressor.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
rng = np.random.default_rng(91)
# 1. Horseshoe: lambda ~ C+(0,1) with n tau^2 = 1 gives kappa ~ Beta(1/2, 1/2)
kappa = 1.0 / (1.0 + rng.standard_cauchy(100_000) ** 2)
print("KS distance:", round(stats.kstest(kappa, stats.beta(0.5, 0.5).cdf).statistic, 4),
" mean, var:", kappa.mean().round(3), kappa.var().round(3), "(exact 0.5, 0.125)")
# 2. SuSiE single effect: columns 1 and 2 are identical, column 3 is noise
n, sig2, v0 = 200, 1.0, 1.0
x = rng.normal(size=n)
X = np.column_stack([x, x, rng.normal(size=n)])
y = 0.8 * x + rng.normal(size=n)
xx = (X ** 2).sum(axis=0)
bhat, s2 = X.T @ y / xx, sig2 / xx
lbf = 0.5 * np.log(s2 / (s2 + v0)) + bhat ** 2 / (2 * s2) * v0 / (s2 + v0)
alpha = np.exp(lbf - lbf.max())
print("PIPs:", (alpha / alpha.sum()).round(3), "(exact 1/2, 1/2, ~0)")// Horseshoe: the half-Cauchy prior on lambda induces kappa = 1/(1 + lambda^2) ~ Beta(1/2, 1/2)
const lamK = await show`Sqrt[1 - k]/Sqrt[k]`const densK = await show`Assuming[0 < k < 1, FullSimplify[-D[${lamK}, k] * 2/(Pi*(1 + (${lamK})^2))]]`await show`Assuming[0 < k < 1, FullSimplify[(${densK}) / (k^(-1/2)*(1 - k)^(-1/2)/Beta[1/2, 1/2])]]`await show`{Integrate[k*(${densK}), {k, 0, 1}], Integrate[(k - 1/2)^2*(${densK}), {k, 0, 1}]}`// SuSiE: Bayes factor as a ratio of normal marginals, then PIPs of two duplicate regressors
const bfOne = await show`Assuming[s2 > 0 && v > 0 && Element[bh, Reals], FullSimplify[Exp[bh^2/(2*s2)]
*Integrate[Exp[-(bh - b)^2/(2*s2)]*Exp[-b^2/(2*v)]/Sqrt[2*Pi*v], {b, -Infinity, Infinity}]]]`await show`Assuming[s2 > 0 && v > 0 && Element[bh, Reals],
FullSimplify[(${bfOne}) / (Sqrt[s2/(s2 + v)]*Exp[bh^2/(2*s2)*v/(s2 + v)])]]`await show`FullSimplify[{w1*(${bfOne}), w2*(${bfOne})} / (w1*(${bfOne}) + w2*(${bfOne}))] /. w2 -> w1`9.8Symbolic Check in Wolfram Language#
Integrates symbolically in wolfram-ws-bridge JavaScript mode to derive and the general symbolic Bayes factor (retaining model-specific ), verifies both the Lindley limit () and the information-paradox supremum, and instantiates margZ directly to reproduce Table 9.1.
// Chapter 9: Symbolic g-prior marginal likelihood, general Bayes factor & exact Table 9.1
const margZ = await show`Assuming[nu0 > 0 && s20 > 0 && ssr > 0 && g > 0 && n > 0,
FullSimplify[Integrate[(1 + g)^(-pz/2)*(2*Pi)^(-n/2)*((nu0*s20/2)^(nu0/2)/Gamma[nu0/2])
*gam^((nu0 + n)/2 - 1)*Exp[-gam*(nu0*s20 + ssr)/2], {gam, 0, Infinity}]]]`// General symbolic Bayes factor BF_{a,b} retaining model-specific s20_a, s20_b
await show`Assuming[nu0 > 0 && sa > 0 && sb > 0 && ssra > 0 && ssrb > 0 && g > 0 && n > 0,
FullSimplify[(${margZ} /. {pz -> pa, s20 -> sa, ssr -> ssra}) / (${margZ} /. {pz -> pb, s20 -> sb, ssr -> ssrb})]]`const bf = await show`FullSimplify[
(${margZ} /. {pz -> p1, ssr -> (g/(g+1))*r1 + (1/(g+1))*yy}) / (${margZ} /. {pz -> 0, ssr -> yy})]`await show`Assuming[p1 > 0 && nu0 > 0 && s20 > 0 && yy > 0 && r1 > 0 && n > 0, Limit[${bf}, g -> Infinity]]`await show`Assuming[p1 > 0 && g > 0 && nu0 > 0 && yy > 0 && n > 0,
FullSimplify[Limit[${bf} /. s20 -> 0, r1 -> 0]]]`// Instantiate margZ directly on Hoff's Oxygen uptake Table 9.1 (g = n = 12, nu0 = 1, s20 = s_z^2)
const age = [23, 22, 22, 25, 27, 20, 31, 23, 27, 28, 22, 24]
const grp = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
const y = [-0.87, -10.74, -3.27, -1.97, 7.50, -7.25, 17.05, 4.96, 10.40, 11.05, 0.26, 2.51]
const Xfull = age.map((a, i) => [1, grp[i], a, grp[i] * a])
const olsB = await show`Function[{xm, yv}, LinearSolve[Transpose[xm].xm, Transpose[xm].yv]]`const s2Fn = await show`Function[{xm, yv, bv}, (yv - xm.bv).(yv - xm.bv) / (Length[yv] - Length[bv])]`const ssrFn = await show`Function[{xm, yv, bv, g}, yv.yv - (g/(g + 1))*(yv.xm.bv)]`const logMargs = await show`N[Table[With[{xz = ${Xfull}[[All, cols]]}, With[{bh = ${olsB}[xz, ${y}]},
Log[${margZ} /. {n -> 12, g -> 12, nu0 -> 1, pz -> Length[cols],
s20 -> ${s2Fn}[xz, ${y}, bh], ssr -> ${ssrFn}[xz, ${y}, bh, 12]}]]],
{cols, {{1}, {1, 2}, {1, 3}, {1, 2, 3}, {1, 2, 3, 4}}}]]`await show`N[Exp[${logMargs} - Max[${logMargs}]] / Total[Exp[${logMargs} - Max[${logMargs}]]]]`9.9Exercises#
Exercise 9.8. Integrate out of (9.7) to show that any contrast has a Student- posterior with degrees of freedom, location , and squared scale . Use it to reproduce the claim that the 95% interval for excludes zero at ages only.
Symbolic Solution & Instantiation
Write the squared Student- marginal scale of a linear contrast under the -prior.// Ex 9.1: Exact Student-t marginal CI for oxygen contrast beta2 + beta4*age across ages 20..31
const age = [23, 22, 22, 25, 27, 20, 31, 23, 27, 28, 22, 24]
const grp = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
const y = [-0.87, -10.74, -3.27, -1.97, 7.50, -7.25, 17.05, 4.96, 10.40, 11.05, 0.26, 2.51]
const X = age.map((a, i) => [1, grp[i], a, grp[i] * a])
const scale2 = await show`(g/(g + 1))*cXtXinvC * (nu0*s20 + ssrG) / (nu0 + n)`const olsB = await show`Function[{xm, yv}, LinearSolve[Transpose[xm].xm, Transpose[xm].yv]]`const s2Fn = await show`Function[{xm, yv, bv}, (yv - xm.bv).(yv - xm.bv) / (Length[yv] - Length[bv])]`const ssrFn = await show`Function[{xm, yv, bv, g}, yv.yv - (g/(g + 1))*(yv.xm.bv)]`const t13 = await show`t /. FindRoot[1 - Beta[13/(13 + t^2), 13/2, 1/2]/Beta[13/2, 1/2] == 95/100, {t, 2.16}]`await show`With[{bh = ${olsB}[${X}, ${y}]},
Select[Range[20, 31], (12/13)*({0, 1, 0, #}.bh) - ${t13}*Sqrt[${scale2} /. {g -> 12, n -> 12, nu0 -> 1,
cXtXinvC -> {0, 1, 0, #}.Inverse[Transpose[${X}].${X}].{0, 1, 0, #},
s20 -> ${s2Fn}[${X}, ${y}, bh], ssrG -> ${ssrFn}[${X}, ${y}, bh, 12]}] > 0 &]]`Exercise 9.9. The zero-centered -prior also shrinks the intercept. Show that the fitted values are times the OLS fitted values, so that adding a constant to every changes the posterior of the slopes’ variance (through ) although it should be irrelevant. Propose a version with a flat prior on the intercept and centered regressors, and explain why a common improper prior on the intercept does not harm Bayes factors while one on the slopes would.
Symbolic Solution & Instantiation
Compute symbolically to expose shift non-invariance under a zero-centered -prior.// Ex 9.2: Shift non-invariance of zero-centered g-prior under y -> y + c*1
const shiftDiff = await show`FullSimplify[((g/(g + 1))*ssrOls + (1/(g + 1))*(yy + 2*c*n*yb + n*c^2)) - ((g/(g + 1))*ssrOls + (1/(g + 1))*yy)]`await show`{${shiftDiff}, N[${shiftDiff}]} /. {n -> 12, g -> 12, yb -> 0, c -> 10}`Exercise 9.10. Verify both halves of Remark 9.5. Derive the bound , and plot the log Bayes factor of against for the oxygen data (common ) as ranges from to . At what does the preferred model switch?
Symbolic Solution & Instantiation
Write the Bayes factor comparing (group + age) against (age only) as a function of .// Ex 9.3: Exact switch point g* where Lindley's paradox flips A=(1,1,1,0) vs B=(1,0,1,0) on oxygen data (nu0 = 1)
const bfG = await show`(1 + g)^(-1/2) * ((s20 + yy - (g/(g + 1))*fB) / (s20 + yy - (g/(g + 1))*fA))^((n + 1)/2)`const age = [23, 22, 22, 25, 27, 20, 31, 23, 27, 28, 22, 24]
const grp = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
const y = [-0.87, -10.74, -3.27, -1.97, 7.50, -7.25, 17.05, 4.96, 10.40, 11.05, 0.26, 2.51]
const Xfull = age.map((a, i) => [1, grp[i], a, grp[i] * a])
const fitSum = await show`Function[{xm, yv}, yv.xm.LinearSolve[Transpose[xm].xm, Transpose[xm].yv]]`await show`g /. FindRoot[(${bfG} /. {s20 -> 8.54, yy -> N[${y}.${y}], n -> 12,
fA -> N[${fitSum}[${Xfull}[[All, {1, 2, 3}]], ${y}]], fB -> N[${fitSum}[${Xfull}[[All, {1, 3}]], ${y}]]}) == 1, {g, 200}]`Exercise 9.11. Simulate with , independent standard normal columns and an independent response . Apply backward elimination with cutoff and record the number of survivors; then run Algorithm 9.6 under both the uniform prior and the prior . (For the latter, show that the prior odds in (9.10) equal when other regressors are included.) Compare the three answers.
Symbolic Solution & Instantiation
Simplify the Beta–Binomial multiplicity-adjusting prior odds for adding one predictor to a model of size .// Ex 9.4: Symbolic prior odds under Beta-Binomial multiplicity-adjusting prior
const odds = await show`FullSimplify[FunctionExpand[(1/((p + 1)*Binomial[p, k + 1])) / (1/((p + 1)*Binomial[p, k]))]]`await show`{${odds} /. {p -> 64, k -> 0}, ${odds} /. {p -> 64, k -> 5}}`