1D logistic regression on n = 20 points (x_i \in [0, 4]): Inside the training range at x_\star = 2, the MAP plug-in (0.524) and the posterior average (0.529) agree to within 0.01.
Orders-of-magnitude disagreement outside data: At x_\star = -3, plausible parameter vectors predict anywhere from 4 \times 10^{-5} to 0.09.
Five-fold rare-event shift: The posterior predictive average is 0.019—roughly 4.6\times larger than the MAP plug-in (0.0041), bending the log-odds curve back toward zero outside the data.
Unnormalized joint density: In Bayesian logistic regression, \widetilde{p}(\boldsymbol{\theta}) = p(\mathcal{D} \mid \boldsymbol{\theta})p(\boldsymbol{\theta}) and its derivatives \nabla \log \widetilde{p}, \mathbf{H}(\boldsymbol{\theta}) evaluate in O(n) time.
How p(\mathcal{D}) cancels: Because the evidence p(\mathcal{D}) = \int \widetilde{p}(\boldsymbol{\theta})\,d\boldsymbol{\theta} is intractable, Laplace, importance sampling, MCMC, and VI all work with ratios or differences where p(\mathcal{D}) drops out.
Slope and Curvature of the Log-Posterior
Gradient and Negative Hessian
Differentiating \log \widetilde{p}(\boldsymbol{\theta}) with respect to \boldsymbol{\theta} gives the gradient and negative Hessian matrix used by optimization, Laplace, and gradient-guided samplers:
Residual-driven gradient: Each observation i pulls \boldsymbol{\theta} along \mathbf{z}_i in proportion to its prediction error y_i - p_i, while the prior pulls \boldsymbol{\theta} radially toward the origin.
Uncertainty-weighted curvature: Because p_i(1-p_i) \le 1/4 peaks at p_i = 1/2, examples near the decision boundary contribute the most curvature to \mathbf{H}(\boldsymbol{\theta}).
Strict log-concavity: The prior adds \tau^{-2}\mathbf{I}, lifting every eigenvalue of \mathbf{H}(\boldsymbol{\theta}) to at least \tau^{-2} > 0 so the posterior has a unique, finite global mode \boldsymbol{\theta}_{\mathrm{MAP}} even on linearly separable data.
The Laplace Approximation: A Gaussian at the Mode
Method 1: Local Quadratic Fit
Second-order Taylor expansion at \boldsymbol{\theta}_{\mathrm{MAP}}: Because \nabla \log \widetilde{p}(\boldsymbol{\theta}_{\mathrm{MAP}}) = \mathbf{0}, expanding around the mode with \mathbf{H} = \mathbf{H}(\boldsymbol{\theta}_{\mathrm{MAP}}) gives: \log \widetilde{p}(\boldsymbol{\theta}) \approx \log \widetilde{p}(\boldsymbol{\theta}_{\mathrm{MAP}}) - \frac{1}{2}(\boldsymbol{\theta} - \boldsymbol{\theta}_{\mathrm{MAP}})^\top \mathbf{H}(\boldsymbol{\theta} - \boldsymbol{\theta}_{\mathrm{MAP}})
Exponentiating yields a Gaussian:p(\boldsymbol{\theta} \mid \mathcal{D}) \approx \mathcal{N}\bigl(\boldsymbol{\theta}_{\mathrm{MAP}},\, \mathbf{H}^{-1}\bigr).
Blind to skewness and boundaries: On \mathrm{Gamma}(4,1) \propto \theta^3 e^{-\theta}(\theta > 0), Laplace fits \mathcal{N}(3, 3) at the mode \theta = 3, missing the true mean 4 and leaking 4.2\% mass below \theta = 0.
Computing the Laplace Approximation by Newton’s Method
Mode and Curvature in Code
Ten Newton steps \boldsymbol{\theta} \leftarrow \boldsymbol{\theta} + \mathbf{H}(\boldsymbol{\theta})^{-1}\nabla \log \widetilde{p}(\boldsymbol{\theta}) from the origin locate \boldsymbol{\theta}_{\mathrm{MAP}}, and one matrix inverse \mathbf{H}(\boldsymbol{\theta}_{\mathrm{MAP}})^{-1} provides the covariance:
Shrinkage toward the origin: The prior pulls the fitted mode \boldsymbol{\theta}_{\mathrm{MAP}} = (-2.14, 1.12) toward zero relative to the true generating parameters \boldsymbol{\theta}^\star = (-3.0, 1.5).
Strong negative correlation (\rho = -0.86): Because all training inputs x_i \in [0, 4] are positive, increasing the slope \theta_1 requires decreasing the intercept \theta_0 so the decision boundary -\theta_0/\theta_1 \approx 2 stays inside the data cloud.
Exact Grid Benchmark: Skewness Shifts the Mean
Low-Dimensional Ground Truth
With d = 2 parameters, evaluating \widetilde{p}(\boldsymbol{\theta}) on a 241 \times 241 lattice spanning \boldsymbol{\theta}_{\mathrm{MAP}} \pm 7 Laplace standard deviations provides an exact benchmark:
Skewness separates mean from mode: Because steeper slopes remain plausible once all points far from the boundary are classified with probability near 0 or 1, the posterior is skewed toward larger slopes: the true mean slope (1.24) sits +0.25 standard deviations above the MAP slope (1.12).
Curse of dimensionality: A lattice with m points per axis requires m^d evaluations (241^2 \approx 5.8 \times 10^4 in 2\text{D}, but 241^{100} \approx 10^{238} in 100\text{D}), making grid integration purely a low-dimensional reference.
Plug-In vs. Posterior Predictive Extrapolation
Predictive Moderation
Comparing the MAP plug-in \operatorname{sigmoid}(\mathbf{z}_\star^\top \boldsymbol{\theta}_{\mathrm{MAP}}) against the exact grid posterior predictive at x_\star \in \{-3, 2, 7\} reveals how parameter uncertainty moderates extreme predictions:
Why uncertainty pulls predictions toward 1/2: For negative logits a = \mathbf{z}_\star^\top \boldsymbol{\theta} \ll 0, \operatorname{sigmoid}(a) \approx e^a is strictly convex. By Jensen’s inequality, \mathbb{E}[e^a] > e^{\mathbb{E}[a]}: models with shallower slopes produce much larger probabilities at x_\star = -3 and dominate the posterior average.
Accounting for the 1.51-Nat Predictive Shift at x = -3
Dissecting the Log-Probability
Quadratic variance boost (+2.87 nats): A Gaussian logit a \sim \mathcal{N}(\mu, s^2) has \log \mathbb{E}[e^a] = \mu + s^2/2, lifting log-probability from -6.06 to -3.19.
Three counter-shifts (-1.36 nats total): Skewness from mode to mean (-0.57), a short upper logit tail (-0.47), and sigmoid saturation \operatorname{sigmoid}(a) < e^a(-0.32) yield the net +1.51-nat (4.6\times) boost.
Rejection Sampling and Dimensional Collapse
Method 2A: Envelope Acceptance
Given a tractable proposal q(\boldsymbol{\theta}) and an upper envelope constant M such that M q(\boldsymbol{\theta}) \ge \widetilde{p}(\boldsymbol{\theta}) everywhere, rejection sampling accepts each draw \boldsymbol{\theta} \sim q with probability a(\boldsymbol{\theta}) = \frac{\widetilde{p}(\boldsymbol{\theta})}{M q(\boldsymbol{\theta})}:
acceptance 0.304, mean 0.666, sd 0.118
Exactness without knowing p(\mathcal{D}): The accepted draws follow \widetilde{p}(\boldsymbol{\theta})/p(\mathcal{D}) = p(\boldsymbol{\theta} \mid \mathcal{D}) exactly, while the unknown evidence determines only the marginal acceptance rate \int \frac{\widetilde{p}(\boldsymbol{\theta})}{M}\,d\boldsymbol{\theta} = \frac{p(\mathcal{D})}{M}.
Exponential collapse in d: Because the posterior contracts around \boldsymbol{\theta}^\star at rate n^{-1/2} along each of the d coordinates, its volume relative to the prior shrinks as n^{-d/2}(30.5\% for 9\text{H}, 4\text{T}\to10\% for 90\text{H}, 40\text{T}\to3\% for 900\text{H}, 400\text{T}).
Self-Normalized Importance Sampling
Method 2B: Reweighting All Draws
Instead of discarding proposals, importance sampling keeps every draw \boldsymbol{\theta}_1, \dots, \boldsymbol{\theta}_N \sim q and weights it by the unnormalized ratio w(\boldsymbol{\theta}) = \frac{\widetilde{p}(\boldsymbol{\theta})}{q(\boldsymbol{\theta})}:
where \bar{w}_s = \frac{w_s}{\sum_{r=1}^N w_r} are the self-normalized weights (computed stably via log-sum-exp) and \mathbb{E}_q[w] = p(\mathcal{D}) cancels in the ratio:
ESS fraction 0.420, mean 0.666, sd 0.118
Effective Sample Size and Chi-Squared Divergence
Diagnosing Weight Degeneracy
Effective sample size (ESS): When one draw carries nearly all the weight, N weighted samples are worth only one draw. The ESS quantifies this via the normalized weights \bar{w}_s: N_{\mathrm{eff}} = \frac{1}{\sum_{s=1}^N \bar{w}_s^2}
Large-sample limit: As N \to \infty, \frac{N_{\mathrm{eff}}}{N} \to \frac{(\mathbb{E}_q[w])^2}{\mathbb{E}_q[w^2]} = \frac{1}{1 + \chi^2(p \,\|\, q)} \ge \frac{p(\mathcal{D})}{M}, always beating rejection sampling (42.0\% vs 30.5\% on the coin).
The unseen-mass hazard: Empirical ESS measures weight inequality among observed draws, not whether q covered all modes of p.
Pitfall: Light Tails and Infinite Weight Variance
Proposal Tails on Logistic Regression
Comparing the broad Gaussian prior (N = 20{,}000) against the targeted Laplace Gaussian (N = 5{,}000) on our logistic posterior reveals a crucial tail hazard:
prior : ESS 4.2% of 20000, largest weight 0.0025, error in sds [0.013 0.001]
Laplace : ESS 85.5% of 5000, largest weight 0.0030, error in sds [0.006 0.003]
Why the Laplace proposal has infinite weight variance (\mathbb{E}_q[w^2] = \infty): Along any ray \boldsymbol{\theta} = t\mathbf{v}, the logistic log-likelihood decays only linearly in t, so the posterior’s tails are Gaussian with the prior’s variance \tau^2 = 4. Consequently, \int (\widetilde{p}^2 / q)\,d\boldsymbol{\theta} = \infty whenever any eigenvalue of the proposal covariance \mathbf{S} satisfies \lambda_{\min}(\mathbf{S}) \le \tau^2/2 = 2.
Defensive fixes: Both Laplace eigenvalues (1.17 and 0.05) are below 2, causing rare catastrophic ESS collapses across repeated runs. Using a heavier-tailed Student-t proposal or a defensive mixtureq = 0.9\,\mathcal{N}(\boldsymbol{\theta}_{\mathrm{MAP}}, \mathbf{H}^{-1}) + 0.1\,\text{prior} guarantees bounded weights w \le 10.
Markov Chain Monte Carlo and the Metropolis Rule
Method 3: Local Random Walks
Stationary Markov chain: Rather than one global proposal q, MCMC constructs a transition kernel T(\boldsymbol{\theta}' \mid \boldsymbol{\theta}) that leaves the posterior invariant: \int \pi(\boldsymbol{\theta})T(\boldsymbol{\theta}' \mid \boldsymbol{\theta})\,d\boldsymbol{\theta} = \pi(\boldsymbol{\theta}').
Metropolis–Hastings acceptance probability: From state \boldsymbol{\theta}, propose \boldsymbol{\theta}' \sim g(\cdot \mid \boldsymbol{\theta}) and accept with probability: \alpha(\boldsymbol{\theta}, \boldsymbol{\theta}') = \min\!\left(1,\, \frac{\widetilde{p}(\boldsymbol{\theta}')\,g(\boldsymbol{\theta} \mid \boldsymbol{\theta}')}{\widetilde{p}(\boldsymbol{\theta})\,g(\boldsymbol{\theta}' \mid \boldsymbol{\theta})}\right)
Evidence cancels in the ratio: For symmetric proposals g(\boldsymbol{\theta}'\mid\boldsymbol{\theta}) = g(\boldsymbol{\theta}\mid\boldsymbol{\theta}'), uphill moves (\widetilde{p}' \ge \widetilde{p}) always accept and downhill moves accept with probability \widetilde{p}'/\widetilde{p}.
Why Rejected Proposals Must Repeat the Current State
Two-State Metropolis Worked Example
Target \pi = (1/4, 3/4) with swap proposal: When the proposal always suggests the other state, moving 1 \to 2 is uphill (\widetilde{p}_2/\widetilde{p}_1 = 3 \implies \alpha = 1), while moving 2 \to 1 is downhill (\alpha = 1/3).
Why repeats matter: The self-loop T_{22} = 2/3 records rejected moves from state 2. Discarding rejections would alternate 2, 1, 2, 1 and converge to (1/2, 1/2).
Symmetric flux under Metropolis–Hastings: For \boldsymbol{\theta}' \ne \boldsymbol{\theta}, \pi(\boldsymbol{\theta})g(\boldsymbol{\theta}'\mid\boldsymbol{\theta})\alpha(\boldsymbol{\theta}, \boldsymbol{\theta}') = \min\bigl\{\pi(\boldsymbol{\theta})g(\boldsymbol{\theta}'\mid\boldsymbol{\theta}),\, \pi(\boldsymbol{\theta}')g(\boldsymbol{\theta}\mid\boldsymbol{\theta}')\bigr\}.
Detailed balance \implies stationarity: Integrating both sides over \boldsymbol{\theta} gives \int \pi(\boldsymbol{\theta})T(\boldsymbol{\theta}'\mid\boldsymbol{\theta})\,d\boldsymbol{\theta} = \pi(\boldsymbol{\theta}').
Implementing Preconditioned Metropolis in NumPy
Cholesky-Scaled Random Walk
Shaping local Gaussian proposals \boldsymbol{\theta}' = \boldsymbol{\theta} + s\mathbf{L}\boldsymbol{\epsilon} with the Cholesky factor \mathbf{L}\mathbf{L}^\top = \mathbf{H}^{-1} of the Laplace covariance aligns the random walk with the posterior’s -0.86 correlation:
def metropolis(log_target, start, proposal_chol, n_steps): current = np.array(start, dtype=float) current_logp = log_target(current) states, accepted = np.empty((n_steps, len(current))), 0for t inrange(n_steps): proposal = current + proposal_chol @ rng.standard_normal(len(current)) proposal_logp = log_target(proposal)if np.log(rng.random()) < proposal_logp - current_logp: # accept current, current_logp = proposal, proposal_logp accepted +=1 states[t] = current # a rejection repeats the statereturn states, accepted / n_steps
Launching 4 chains from over-dispersed starts \boldsymbol{\theta}_{\mathrm{MAP}} + 2\mathbf{L}\boldsymbol{\epsilon} with scale s = 1.1 and discarding 2{,}000 warm-up steps yields roughly 50\% acceptance:
acceptance rates: [0.523 0.529 0.533 0.526]
Three Diagnostics for MCMC Mixing and Accuracy
Split R-Hat, Autocorrelation Time, and MCSE
Because Markov chain states are serially correlated and start away from equilibrium, every MCMC run requires three quantitative checks:
1. Split \widehat{R} (potential scale reduction factor): Split c chains of length N into 2c half-chains of length N/2, and compare between-chain variance B to average within-chain variance W: \widehat{R} = \sqrt{\frac{\frac{N-1}{N}W + \frac{1}{N}B}{W}} \qquad (\text{require } \widehat{R} < 1.01)
2. Integrated autocorrelation time \kappa and N_{\mathrm{eff}}: With lag-k autocorrelation \rho_k, \kappa = 1 + 2\sum_{k \ge 1} \rho_k counts how many correlated steps equal one independent draw, giving N_{\mathrm{eff}} = \frac{cN}{\kappa}. For an AR(1) chain x_t = \phi x_{t-1} + \varepsilon_t, \rho_k = \phi^k \implies \kappa = \frac{1+\phi}{1-\phi}(\phi = 0.9 \implies \kappa = 19;\phi = 0.99 \implies \kappa = 199).
3. Monte Carlo standard error (MCSE): By the Markov chain CLT, the standard error of the chain mean is \mathrm{MCSE} = \frac{\hat{\sigma}_{\mathrm{post}}}{\sqrt{N_{\mathrm{eff}}}}.
Verifying MCMC Convergence on the Logistic Posterior
Healthy mixing: Split \widehat{R} \le 1.002, and the 4 chains interleave tightly in the trace plot.
Calibrated uncertainty: With \rho_1 \approx 0.80, \kappa \approx 10(N_{\mathrm{eff}} \approx 4{,}000 of 40{,}000 steps), and the MCMC mean lands within \sim 1\ \mathrm{MCSE} of the exact grid mean.
The Goldilocks Proposal Scale and Gradient Guidance
Step-Size Trade-Offs
Why does the acceptance rate alone never certify convergence? Rerunning our 4 chains at extreme proposal scales s = 0.05 and s = 10 exposes both failure modes:
scale 0.05: acceptance 0.975, max R-hat 1.13, min ESS 43
scale 10: acceptance 0.020, max R-hat 1.00, min ESS 689
Tiny steps (s = 0.05, acceptance 97\%): Almost every step is accepted, but the random walk diffuses so slowly that \widehat{R} > 1.04 and 40{,}000 steps yield only \sim 40 effective draws.
Huge steps (s = 10, acceptance 2\%): Proposals almost always jump into low-density tails and reject, leaving the chain stuck at the same state for dozens of steps.
Variational Inference: Integration via Optimization
Method 4: Parametric ELBO Maximization
Instead of drawing correlated samples, variational inference (VI) posits a tractable family of densities q_{\boldsymbol{\psi}}(\boldsymbol{\theta}) and optimizes \boldsymbol{\psi} to minimize KL divergence to the posterior. Treating \boldsymbol{\theta} as the latent variable in our §36.7 ELBO identity yields:
Unknown evidence drops out: Because \log p(\mathcal{D}) does not depend on \boldsymbol{\psi}, every 1-nat increase in the computable ELBO \mathcal{L}(\boldsymbol{\psi}) reduces D_{\mathrm{KL}}(q_{\boldsymbol{\psi}} \,\|\, p(\cdot \mid \mathcal{D})) by 1 nat.
Reverse KL (D_{\mathrm{KL}}(q \,\|\, p) = \int q \log\frac{q}{p}, used by VI): Blows up to +\infty wherever p(\boldsymbol{\theta} \mid \mathcal{D}) \approx 0 and q(\boldsymbol{\theta}) > 0. This zero-avoiding penalty forces q to lock onto a single mode and underestimate support width.
Forward KL (D_{\mathrm{KL}}(p \,\|\, q) = \int p \log\frac{p}{q}): Blows up wherever p > 0 and q \approx 0. This mass-covering penalty forces q to bridge across all modes (putting its peak in an empty valley), and requires expectations under the intractable p.
Why Mean-Field VI Underestimates Posterior Uncertainty
Conditional vs. Marginal Variance
Mean-field theorem on a correlated Gaussian: When p = \mathcal{N}(\boldsymbol{\mu}, \boldsymbol{\Lambda}^{-1}) has precision matrix \boldsymbol{\Lambda} and correlation \rho, minimizing D_{\mathrm{KL}}(q \,\|\, p) over factorized Gaussians q = \mathcal{N}(\mathbf{m}, \operatorname{diag}(\mathbf{s}^2)) yields \mathbf{m} = \boldsymbol{\mu} and: s_j^2 = \frac{1}{\Lambda_{jj}} = \sigma_j^2(1 - \rho^2)
Slice width vs. projection width: Because an axis-aligned ellipse cannot tilt, reverse KL shrinks each s_j by \sqrt{1 - \rho^2}(0.51\times for \rho = -0.86) to avoid low-density corners:
Metropolis (histogram): Faithfully recovers the exact grid marginal, including its rightward skew and true width.
Laplace (orange): Centered at the MAP mode (1.12) to the left of the posterior mean (1.24), and 4\% too narrow.
Mean-field VI (green): Captures the posterior mean (1.22) accurately, but contracts to half the true marginal width (s_1 = 0.25 vs 0.48) and assumes \rho = 0.
Concept Check: Bayesian Computation
Check Your Understanding
Autocorrelation and effective sample size: An MCMC chain of N = 19{,}000 post-warm-up steps behaves like an AR(1) process with lag-1 autocorrelation \phi = 0.90. What is its integrated autocorrelation time \kappa, and how many independent draws is the chain worth?
Diagnosing a 97\% acceptance rate: Why is a Metropolis random walk with a 97\% acceptance rate almost certainly failing to explore the posterior, and which diagnostic reveals the failure?
Mean-field variance contraction: A 2\text{D} Gaussian posterior has marginal standard deviations (\sigma_1, \sigma_2) = (2.0, 1.0) and correlation \rho = -0.80. What standard deviations (s_1, s_2) will mean-field variational inference converge to?
Answers:
\kappa = \frac{1 + \phi}{1 - \phi} = \frac{1.90}{0.10} = 19, so N_{\mathrm{eff}} = \frac{19{,}000}{19} = 1{,}000 independent draws (reducing Monte Carlo standard errors by \sqrt{1000} \approx 31.6, not \sqrt{19000} \approx 137.8).
A 97\% acceptance rate means the proposal step size is tiny (s \ll 1), so the chain creeps diffusively; split \widehat{R} \gg 1.01 and a tiny N_{\mathrm{eff}} immediately expose the slow mixing.
By s_j = \sigma_j\sqrt{1 - \rho^2} with \sqrt{1 - (-0.80)^2} = \sqrt{0.36} = 0.60, mean-field VI converges to (s_1, s_2) = (1.20, 0.60)—underestimating marginal uncertainty by 40\%.
Summary: Bayesian Computation Methods
Key Takeaways
Method
Posterior Representation
How Normalizer p(\mathcal{D}) Cancels
Primary Diagnostic
Characteristic Failure Mode
Laplace Approximation
\mathcal{N}(\boldsymbol{\theta}_{\mathrm{MAP}}, \mathbf{H}^{-1}) at mode
Additive constant \log p(\mathcal{D}) vanishes in \nabla, \nabla^2
Compare against MCMC samples
Misses skewness, heavy tails, boundaries, multimodality
Rejection Sampling
Independent exact draws
Appears only in acceptance rate p(\mathcal{D})/M
Empirical acceptance rate
Rate collapses as n^{-d/2}; requires global bound M
Importance Sampling
Weighted draws (\boldsymbol{\theta}_s, \bar{w}_s)
Cancels in self-normalized ratio \frac{\sum w_s h_s}{\sum w_s}
Weight ESS 1/\sum \bar{w}_s^2 & max weight
Infinite weight variance if q has lighter tails than p
Metropolis–Hastings
Correlated Markov chain states
Cancels in acceptance ratio \frac{\widetilde{p}(\boldsymbol{\theta}')}{\widetilde{p}(\boldsymbol{\theta})}
Split \widehat{R} < 1.01, ESS cN/\kappa, MCSE
Slow random-walk mixing in high d; trapped in single mode