Neural Network vs INLA
A detailed mathematical comparison of Frequentist Neural Networks, Bayesian Neural Networks, and INLA, applied to the same regression problem, with the same likelihood.
By Esmail Abdul Fattah
The Shared Starting Point
We observe \(n = 200\) pairs \((x_i, y_i)\) generated by:
with true values \(w_0 = 1\), \(w_1 = 2\), \(\sigma = 0.5\). The log-likelihood is:
Central Fact
All three methods start from this same log-likelihood. The only difference is what each method does with it.
Method 1: Frequentist Neural Network
A neural network with one input node, no hidden layers, and one output node computes \(f(x; w_0, w_1) = w_0 + w_1\,x\). This is identical to linear regression, but trained via gradient descent.
The Loss Function: MSE
MSE = Maximum Likelihood
For any fixed \(\sigma^2\), the log-likelihood can be rewritten as:
Since the first term is constant with respect to \(w_0, w_1\):
MSE = Maximum Likelihood
Minimizing MSE is mathematically identical to maximizing the Gaussian log-likelihood. Every neural network trained with MSE loss is implicitly doing maximum likelihood estimation under a Gaussian noise model.
Gradient Derivation
Define \(r_i = y_i - w_0 - w_1 x_i\) (residual). Then:
At iteration \(t\), with learning rate \(\eta\):
Noise Estimate
After convergence, \(\hat{\sigma}_{\text{MLE}} = \sqrt{\mathcal{L}_{\text{MSE}}}\).
- Single numbers: \(\hat{w}_0 = 1.0331\), \(\hat{w}_1 = 1.9902\), \(\hat{\sigma} = 0.4832\)
- No uncertainty on \(\hat{w}_0\) or \(\hat{w}_1\)
- No credible intervals, no posterior distribution
Implementation
The complete frequentist NN in NumPy. Each line maps directly to the equations above.
import numpy as np
import pandas as pd
# ── Load shared data ──
data = pd.read_csv("shared_data.csv")
x = data["x"].values # shape (200,), the covariate
y = data["y"].values # shape (200,), the response
n = len(x) # 200 observations
Data setup
We load the shared CSV with 200 observations. Both x and y are simple 1-D NumPy arrays. The data was generated by run_all.py with \(y = 1 + 2x + \mathcal{N}(0, 0.25)\).
# ── Initialize weights and hyperparameters ──
w0, w1 = 0.0, 0.0 # start at zero (arbitrary)
lr = 0.01 # learning rate η
n_epochs = 1000 # number of gradient descent iterations
Initialization
Weights start at zero. The learning rate \(\eta = 0.01\) controls the step size. For this simple convex problem, 1000 epochs is more than sufficient for convergence. A deep network would need careful initialization and learning rate scheduling; this simplicity is the advantage of a one-neuron model.
# ── Training loop: gradient descent on MSE ──
for epoch in range(n_epochs):
# Forward pass: compute predictions
pred = w0 + w1 * x # f(x; w0, w1) = w0 + w1·x
residual = pred - y # r_i = (w0 + w1·x_i) - y_i
# MSE loss = (1/n) Σ r_i² (this IS the negative log-likelihood)
loss = np.mean(residual ** 2)
# Gradients: ∂MSE/∂w0 = (2/n) Σ r_i
# ∂MSE/∂w1 = (2/n) Σ r_i · x_i
grad_w0 = 2.0 * np.mean(residual)
grad_w1 = 2.0 * np.mean(residual * x)
# Parameter update: w ← w - η · ∇MSE
w0 -= lr * grad_w0
w1 -= lr * grad_w1
What this loop does
Each iteration performs three steps. First, we compute predictions using the current weights and measure how far off they are from the observed data (the residuals). Then we compute the MSE loss, which is the average squared residual, and take its derivatives with respect to each weight. The gradient for \(w_0\) averages the residuals, and the gradient for \(w_1\) averages the residuals weighted by \(x\). Finally, we nudge each weight in the direction that reduces the loss, scaled by the learning rate. After enough iterations, the weights settle at values that minimize the squared error.
# ── After convergence: estimate noise σ ──
# MLE estimate (divides by n)
sigma_hat = np.sqrt(np.mean((y - w0 - w1 * x) ** 2))
# σ̂_MLE = √( (1/n) Σ(y_i - ŵ0 - ŵ1·x_i)² )
# Unbiased estimate (divides by n - 2)
residuals = y - w0 - w1 * x
sigma_unbiased = np.sqrt(np.sum(residuals**2) / (n - 2))
# σ̂_unbiased = √( (1/(n-2)) Σ(y_i - ŵ0 - ŵ1·x_i)² )
Noise estimate
After training, the root-mean-square residual gives \(\hat{\sigma}_{\text{MLE}} = \sqrt{\mathcal{L}_{\text{MSE}}} = 0.4832\), close to the true \(\sigma = 0.5\). This is the MLE of the noise standard deviation.
The MLE divides by \(n\), but the unbiased estimator divides by \(n - 2\) to account for the two parameters (\(w_0, w_1\)) estimated from the data. For \(n = 200\), the difference is negligible (~1%):
- \(\hat{\sigma}_{\text{MLE}} = 0.4832\) (divides by \(n = 200\))
- \(\hat{\sigma}_{\text{unbiased}} = 0.4856\) (divides by \(n - 2 = 198\))
Method 2: Bayesian Neural Network
Instead of finding single "best" weights, a Bayesian Neural Network models each weight as a random variable. We need a prior, Bayes' theorem, and an approximation strategy.
Step 1: Specify the Prior
This encodes: "before seeing data, we believe each weight is somewhere near zero."
Step 2: Bayes' Theorem
The denominator (marginal likelihood) requires integrating over all possible weight values, which is intractable for general neural networks.
Step 3: Variational Approximation
Choose a parameterized family of distributions (the mean-field approximation):
where \(\phi = \{\mu_{w_0}, \sigma_{w_0}, \mu_{w_1}, \sigma_{w_1}\}\) are variational parameters to be optimized.
Step 4: The ELBO Objective
We want \(q_\phi\) to be "close" to the true posterior. Start from the KL divergence \(\mathrm{KL}[q_\phi \| p(\cdot \mid \mathbf{y})]\) and expand using Bayes' theorem:
Since \(\ln p(\mathbf{y})\) is constant and \(\mathrm{KL} \geq 0\), maximizing the ELBO is equivalent to minimizing the KL divergence from \(q_\phi\) to the true posterior:
The Two Terms
- Expected log-likelihood: pushes \(q\) toward weights that explain the data
- KL penalty: penalizes \(q\) for deviating from the prior (analogous to L2 weight decay)
Step 5: KL Divergence in Closed Form
For our prior \(p = \mathcal{N}(0, 1)\) and variational posterior \(q = \mathcal{N}(\mu, \sigma^2)\):
For both weights combined:
Step 6: Monte Carlo Estimation
The expected log-likelihood has no closed form in general. Approximate with Monte Carlo:
Step 7: The Reparameterization Trick
To differentiate through sampling, rewrite as a deterministic function of parameters plus external noise:
Now \(w_j\) is differentiable with respect to \(\mu_{w_j}\) and \(\sigma_{w_j}\), and we can apply the chain rule.
Step 8: Gradient Derivation
Parameterize \(\sigma_{w_j} = e^{\rho_j}\) (ensuring positivity). The gradients are:
where the likelihood gradients for our Gaussian model are:
Step 9: The Complete Update
- Sample: Draw \(S\) samples \(\epsilon_j^{(s)} \sim \mathcal{N}(0,1)\), compute \(w_j^{(s)} = \mu_{w_j} + \sigma_{w_j}\,\epsilon_j^{(s)}\).
- Evaluate: For each sample, compute \(\frac{\partial\ell}{\partial w_0}\) and \(\frac{\partial\ell}{\partial w_1}\).
- Gradients: Combine into ELBO gradients (with KL contribution).
- Ascend: Update \(\mu_{w_j} \leftarrow \mu_{w_j} + \eta \cdot \nabla_\mu\,\text{ELBO}\) and \(\rho_j \leftarrow \rho_j + \eta \cdot \nabla_\rho\,\text{ELBO}\).
Note: this is gradient ascent (maximizing ELBO), not descent.
- Approximate posterior: \(q(w_0) = \mathcal{N}(1.0395,\; 0.0341^2)\), \(q(w_1) = \mathcal{N}(1.9826,\; 0.0295^2)\)
- 95% CI from Gaussian: \(w_0 \in [0.973, 1.106]\), \(w_1 \in [1.925, 2.040]\)
- These are approximate, the true posterior shape may differ
- Required tuning: learning rate, 3000 epochs, 20 MC samples, gradient clipping
Implementation
The complete Bayesian Neural Network with variational inference in NumPy. Every line maps to a specific equation from the derivation above.
import numpy as np
import pandas as pd
# ── Load shared data ──
data = pd.read_csv("shared_data.csv")
x = data["x"].values
y = data["y"].values
n = len(x)
# ── Estimate noise σ from data (treat as known) ──
X_mat = np.column_stack([np.ones(n), x])
beta_ols = np.linalg.lstsq(X_mat, y, rcond=None)[0]
sigma_noise = np.sqrt(np.mean((y - X_mat @ beta_ols) ** 2))
Why estimate sigma first?
The Neural Network treats the noise level \(\sigma\) as known (fixed) during variational inference. We estimate it from the OLS residuals so the Neural Network focuses on learning the weight posteriors. This is a simplification; in contrast, INLA treats \(\sigma\) (via precision \(\tau\)) as an unknown hyperparameter and estimates its full posterior.
# ── Variational parameters ──
# Each weight has: mean (μ) and log-std-dev (ρ = log σ)
mu_w0, log_s_w0 = 0.0, -2.0 # q(w0) = N(μ_w0, exp(ρ_w0)²)
mu_w1, log_s_w1 = 0.0, -2.0 # q(w1) = N(μ_w1, exp(ρ_w1)²)
lr = 0.001 # learning rate (smaller than freq. NN due to stochastic gradients)
n_epochs = 3000 # more epochs needed for stochastic optimization
n_samples = 20 # S = 20 Monte Carlo samples per ELBO estimate
clip_val = 5.0 # gradient clipping threshold
Parameterization choices
log_s_w0 = -2.0: we optimize \(\rho = \ln\sigma\) instead of \(\sigma\) directly. This ensures \(\sigma = e^\rho > 0\) always. Starting at \(\rho = -2\) means \(\sigma_{\text{init}} = e^{-2} \approx 0.135\).lr = 0.001: 10× smaller than the frequentist NN. Stochastic gradients (from MC sampling) add noise, so smaller steps prevent divergence.n_samples = 20: more samples = lower variance gradient estimates, but slower. This is the \(S\) in the MC estimator \(\frac{1}{S}\sum_{s=1}^{S}\ell(w^{(s)})\).clip_val = 5.0: gradient clipping prevents rare large MC samples from causing parameter explosions.
for epoch in range(n_epochs):
elbo = 0.0
g_mu_w0, g_ls_w0 = 0.0, 0.0 # gradient accumulators
g_mu_w1, g_ls_w1 = 0.0, 0.0
# Current std devs (clipped for numerical stability)
s_w0 = np.exp(np.clip(log_s_w0, -10, 5)) # σ_w0 = exp(ρ_w0)
s_w1 = np.exp(np.clip(log_s_w1, -10, 5)) # σ_w1 = exp(ρ_w1)
for _ in range(n_samples):
# ── Reparameterization trick (Eq. 7) ──
# w = μ + σ · ε, where ε ~ N(0,1)
eps0 = np.random.randn()
eps1 = np.random.randn()
w0_s = mu_w0 + s_w0 * eps0 # sampled w0
w1_s = mu_w1 + s_w1 * eps1 # sampled w1
# ── Log-likelihood for this sample ──
# ℓ(w0,w1) = -1/(2σ²) Σ(y_i - w0 - w1·x_i)²
pred = w0_s + w1_s * x
ll = -0.5 * np.sum((y - pred) ** 2) / sigma_noise ** 2
# ── KL divergence (Eq. 5, closed form) ──
# KL[N(μ,σ²) || N(0,1)] = ½(μ² + σ² - 1 - log σ²)
kl = 0.5 * (mu_w0**2 + s_w0**2 - 1 - 2 * log_s_w0
+ mu_w1**2 + s_w1**2 - 1 - 2 * log_s_w1)
# ── ELBO = E[log-lik] - KL (Eq. 4) ──
elbo += (ll - kl) / n_samples
What the core loop does
For each Monte Carlo sample, we draw random noise \(\epsilon\) and use it to generate a set of weights from our current variational distribution (the reparameterization trick). With those sampled weights, we compute predictions and evaluate how well they explain the data through the log-likelihood. We also compute the KL divergence, which measures how far our variational distribution has drifted from the prior. The ELBO is the difference: it rewards explaining the data while penalizing departure from the prior. By averaging this over multiple samples, we get a stable estimate of the ELBO for this iteration.
# ── Gradients via reparameterization (Eqs. 8–9) ──
# ∂ℓ/∂w0 = (1/σ²) Σ(y_i - pred_i)
dll_dw0 = np.sum((y - pred)) / sigma_noise ** 2
# ∂ℓ/∂w1 = (1/σ²) Σ(y_i - pred_i)·x_i
dll_dw1 = np.sum((y - pred) * x) / sigma_noise ** 2
# ∂ELBO/∂μ_wj = ∂ℓ/∂wj - μ_wj (chain rule + KL gradient)
g_mu_w0 += (dll_dw0 - mu_w0) / n_samples
g_mu_w1 += (dll_dw1 - mu_w1) / n_samples
# ∂ELBO/∂ρ_wj = ∂ℓ/∂wj · ε · σ - σ² + 1
g_ls_w0 += (dll_dw0 * eps0 * s_w0 - s_w0**2 + 1) / n_samples
g_ls_w1 += (dll_dw1 * eps1 * s_w1 - s_w1**2 + 1) / n_samples
How the gradient update works
We need gradients of the ELBO with respect to both the mean and the spread of each weight's distribution. The gradient for the mean combines two forces: the likelihood gradient (which pushes the mean toward values that fit the data) and the KL gradient (which pulls it back toward the prior mean of zero). The gradient for the log-standard-deviation balances how much the spread helps explore the likelihood surface against how much the KL penalty discourages wide distributions. These two forces, data fit versus prior regularization, are what make the posterior a compromise between what the data says and what we believed beforehand.
# ── Clip gradients (prevent explosion from rare MC samples) ──
g_mu_w0 = np.clip(g_mu_w0, -clip_val, clip_val)
g_mu_w1 = np.clip(g_mu_w1, -clip_val, clip_val)
g_ls_w0 = np.clip(g_ls_w0, -clip_val, clip_val)
g_ls_w1 = np.clip(g_ls_w1, -clip_val, clip_val)
# ── Gradient ASCENT on ELBO (not descent!) ──
mu_w0 += lr * g_mu_w0 # μ_w0 ← μ_w0 + η · ∂ELBO/∂μ_w0
mu_w1 += lr * g_mu_w1
log_s_w0 += lr * g_ls_w0 # ρ_w0 ← ρ_w0 + η · ∂ELBO/∂ρ_w0
log_s_w1 += lr * g_ls_w1
Gradient clipping and ascent
- Clipping: Without clipping, a rare large \(\epsilon\) sample can produce an enormous gradient, causing the parameters to jump to unstable values.
clip_val = 5.0caps each gradient component. - Ascent not descent: We maximize the ELBO, so we add the gradient (
+= lr * g), unlike MSE minimization which subtracts.
# ── Extract final posteriors ──
final_s_w0 = np.exp(log_s_w0) # σ_w0 = exp(ρ_w0)
final_s_w1 = np.exp(log_s_w1) # σ_w1 = exp(ρ_w1)
# Approximate 95% CI from Gaussian posterior
# CI = [μ - 1.96σ, μ + 1.96σ]
w0_ci = (mu_w0 - 1.96 * final_s_w0, mu_w0 + 1.96 * final_s_w0)
w1_ci = (mu_w1 - 1.96 * final_s_w1, mu_w1 + 1.96 * final_s_w1)
Final output
After 3000 epochs, the variational parameters \((\mu_{w_0}, \sigma_{w_0}, \mu_{w_1}, \sigma_{w_1})\) define Gaussian posteriors. The 95% credible intervals use the Gaussian quantile \(\pm 1.96\sigma\). These intervals are forced symmetric by the Gaussian assumption: they cannot be asymmetric like INLA's intervals can be for non-Gaussian posteriors.
lr, n_epochs, n_samples, clip_val), plus the log-std initialization. Poor choices cause divergence, slow convergence, or inaccurate posteriors. INLA needs none of this.
Method 3: INLA
INLA is designed for Latent Gaussian Models (LGMs) with three hierarchical levels:
Observations
\(y_i \mid \eta_i, \boldsymbol{\theta} \sim p(y_i \mid \eta_i, \boldsymbol{\theta})\)
Data are conditionally independent given the latent field.
Latent Gaussian Field
\(\mathbf{x} \mid \boldsymbol{\theta} \sim \mathcal{N}(\boldsymbol{\mu}, \mathbf{Q}(\boldsymbol{\theta})^{-1})\)
All unobserved variables form a Gaussian field with sparse precision.
Hyperparameters
\(\boldsymbol{\theta} \sim p(\boldsymbol{\theta})\)
Low-dimensional vector controlling variance, correlation, etc.
Our Model as an LGM
where \(\tau = 1/\sigma^2\) is the precision (the single hyperparameter).
The Target: Posterior Marginals
INLA computes the marginal posterior distribution for each parameter individually:
Step 1: Laplace Approximation for Hyperparameters
INLA uses the identity \(p(\boldsymbol{\theta} \mid \mathbf{y}) = p(\mathbf{x}, \boldsymbol{\theta} \mid \mathbf{y}) \,/\, p(\mathbf{x} \mid \boldsymbol{\theta}, \mathbf{y})\) and replaces the denominator with its Laplace approximation.
Given a log-concave density \(\pi(\mathbf{x})\) with mode \(\hat{\mathbf{x}}\), expand \(\ln\pi(\mathbf{x})\) in a Taylor series:
where \(\mathbf{H} = -\nabla^2 \ln\pi(\mathbf{x})\big|_{\hat{\mathbf{x}}}\) is the negative Hessian. Exponentiating gives a Gaussian: \(\pi(\mathbf{x}) \approx \mathcal{N}(\hat{\mathbf{x}},\; \mathbf{H}^{-1})\).
The INLA formula evaluates at \(\mathbf{x} = \hat{\mathbf{x}}(\boldsymbol{\theta})\):
Step 2: Conditional Latent Marginals
INLA offers strategies of increasing accuracy:
| Strategy | Description | Speed |
|---|---|---|
gaussian | Uses only mean and variance from the Gaussian approximation | Fastest |
simplified.laplace | Skewness-corrected Gaussian (default) | Fast |
laplace | Full Laplace approximation at each point | Slower |
vb | Variational Bayes correction to the Gaussian mean | Fast |
Step 3: Numerical Integration
The final marginal integrates out the hyperparameters:
This is feasible because \(\boldsymbol{\theta}\) is low-dimensional. In our example \(\boldsymbol{\theta} = \tau\) is a scalar, so this is simple 1D quadrature.
INLA Has No Objective to Optimize
- No optimization loop
- No learning rate
- No stochastic sampling in the inference
- No convergence criterion to monitor
The posterior is computed directly via analytical approximations (Laplace) and numerical integration (quadrature). The output is deterministic: identical inputs always produce identical results.
- Full posterior marginals \(p(w_0 \mid \mathbf{y})\) and \(p(w_1 \mid \mathbf{y})\) (not restricted to Gaussian)
- \(w_0\): mean \(= 1.0331\), sd \(= 0.0343\), 95% CI \(= [0.966, 1.101]\)
- \(w_1\): mean \(= 1.9902\), sd \(= 0.0291\), 95% CI \(= [1.933, 2.047]\)
- Precision posterior: \(\tau\): mean \(= 4.2833\), mode \(= 4.2406\), sd \(= 0.4283\)
- \(\sigma = 1/\sqrt{\tau} \approx 0.4832\)
- Marginal log-likelihood \(= -157.21\) (for model comparison)
- No tuning required
Mathematical Comparison
What Each Method Computes
Frequentist NN
- Objective: \(\min \frac{1}{n}\sum r_i^2\)
- Output: Point estimate \(\hat{w}_j\)
- Uncertainty: None
- Inference: Gradient descent
- Stochastic: No
Neural Network
- Objective: \(\max \mathbb{E}_q[\ell] - \mathrm{KL}\)
- Output: \(q(w_j) = \mathcal{N}(\mu_j, \sigma_j^2)\)
- Uncertainty: Gaussian (forced)
- Inference: Stochastic VI
- Stochastic: Yes (MC sampling)
INLA
- Objective: Direct computation
- Output: \(\tilde{p}(w_j \mid \mathbf{y})\) (any shape)
- Uncertainty: Full posterior shape
- Inference: Laplace + quadrature
- Stochastic: No
Geometric Interpretation
Consider the joint posterior \(p(w_0, w_1 \mid \mathbf{y})\) as a surface in 3D:
- Frequentist NN finds the peak of this surface: a single point. All information about the shape is discarded.
- Neural Network fits the best axis-aligned ellipse (bivariate Gaussian) to the surface. It captures some spread but cannot represent correlation, skewness, or multimodality.
- INLA computes the shadow (marginal projection) of the surface onto each axis. Each shadow captures the full shape (asymmetry, heavy tails, etc.) without any distributional assumption.
Connection 1: Neural Network Reduces to Regularized Frequentist NN
If we force \(\sigma_{w_j} \to 0\) in the variational posterior, then \(q(w_j)\) collapses to a point mass, and:
This is exactly the MAP (Maximum A Posteriori) objective: log-likelihood plus log-prior. The \(\frac{1}{2}(\mu_{w_0}^2 + \mu_{w_1}^2)\) term is L2 regularization (weight decay).
Connection 2: Perfect Neural Network Recovers the Exact Posterior
If the variational family \(q\) were expanded to include all distributions, minimizing \(\mathrm{KL}[q \| p(\cdot \mid \mathbf{y})]\) would yield \(q^* = p(\mathbf{w} \mid \mathbf{y})\) exactly. INLA approximates this exact posterior directly via analytical methods, bypassing the optimization entirely.
When to Use Which
INLA Wins When
- Speed: Single deterministic computation vs 60,000 forward passes (3000 epochs × 20 MC samples)
- Accuracy: Laplace approximation is exact for Gaussian likelihoods; highly accurate for exponential families
- Reproducibility: Same output every time; Neural Network varies due to MC sampling
- Calibration: Correct frequentist coverage for LGMs; Neural Network credible intervals may be miscalibrated
Neural Network Wins When
- Non-LGM models: Nonlinear activations (ReLU, tanh) with multiple hidden layers are not LGMs
- High-dimensional inputs: Images, text, and other complex inputs require flexible function approximators
- Unknown model structure: When you don't know the form of \(f(x)\), a neural network can learn it from data
Experimental Results
All three methods were run on the same synthetic dataset: \(n = 200\) observations from \(y_i = 1.0 + 2.0\,x_i + \varepsilon_i\), \(\varepsilon_i \sim \mathcal{N}(0, 0.25)\).
| True | Freq. NN | Neural Network (VI) | INLA | |
|---|---|---|---|---|
| \(w_0\) (mean) | 1.000 | 1.0331 | 1.0395 | 1.0331 |
| \(w_0\) (std) | — | — | 0.0341 | 0.0343 |
| \(w_0\) (95% CI) | — | — | [0.973, 1.106] | [0.966, 1.101] |
| \(w_0\) (mode) | — | — | — | 1.0331 |
| \(w_1\) (mean) | 2.000 | 1.9902 | 1.9826 | 1.9902 |
| \(w_1\) (std) | — | — | 0.0295 | 0.0291 |
| \(w_1\) (95% CI) | — | — | [1.925, 2.040] | [1.933, 2.047] |
| \(w_1\) (mode) | — | — | — | 1.9902 |
| \(\hat\sigma\) | 0.500 | 0.4832 | — | 0.4832 |
| Precision \(\tau\) (mean) | 4.000 | — | — | 4.2833 |
| Precision \(\tau\) (mode) | — | — | — | 4.2406 |
| MSE | — | 0.2335 | — | — |
| ELBO | — | — | −109.65 | — |
| Marg. log-lik. | — | — | — | −157.21 |
Key Observations
- Freq. NN and INLA means are identical (1.0331) because both are deterministic and converge to the exact posterior mode/mean. The Neural Network mean (1.0395) differs due to stochastic gradient noise from MC sampling.
- Neural Network std ≈ INLA std (0.034 vs 0.034 for \(w_0\)). This agreement is expected because the true posterior is Gaussian for this model, so the Neural Network's Gaussian assumption happens to be correct.
- INLA captures asymmetry: the precision posterior has mode (4.24) ≠ mean (4.28), revealing right-skewness that only INLA can detect.
- All 95% credible intervals contain the true values, confirming proper calibration.
Available Output Comparison
| Available output | Freq. NN | Neural Network | INLA |
|---|---|---|---|
| Point estimate (mean) | ✓ | ✓ | ✓ |
| Posterior standard deviation | — | ✓ | ✓ |
| 95% credible interval | — | ✓ | ✓ |
| Posterior mode | — | — | ✓ |
| Full posterior density shape | — | — | ✓ |
| Noise/precision posterior | — | — | ✓ |
| Marginal log-likelihood | — | — | ✓ |
| Deterministic / reproducible | ✓ | — | ✓ |
PyINLA Implementation
The INLA approach requires just a few lines of Python with pyINLA. Here is the complete implementation with detailed explanation.
import numpy as np
import pandas as pd
from pyinla import pyinla
# ── Load shared data ──
data = pd.read_csv("shared_data.csv")
Same data, same starting point
We load the exact same 200 observations used by the frequentist NN and Bayesian Neural Network. pyINLA works directly with pandas DataFrames, no need to extract NumPy arrays or precompute anything.
# ── Specify the model ──
model = {
"response": "y", # column name of the response variable
"fixed": ["1", "x"], # "1" = intercept (w0), "x" = slope (w1)
}
Model specification
"response": "y": tells pyINLA which DataFrame column contains the observations \(y_i\)."fixed": ["1", "x"]: specifies the fixed effects in the linear predictor \(\eta_i = w_0 \cdot 1 + w_1 \cdot x_i\). The string"1"adds an intercept;"x"adds the covariate. This is equivalent to writing \(\eta_i = w_0 + w_1 x_i\) in the LGM framework.- No random effects, no spatial terms, no temporal components: the simplest possible LGM.
# ── Run INLA ──
result = pyinla(model=model, family="gaussian", data=data)
What happens inside this single call
This one line triggers the entire INLA algorithm:
- family="gaussian": sets the observation model to \(y_i \mid \eta_i, \tau \sim \mathcal{N}(\eta_i, \tau^{-1})\). The precision \(\tau = 1/\sigma^2\) becomes the hyperparameter \(\boldsymbol{\theta}\).
- Step 1: Constructs the Laplace approximation \(\tilde{p}(\tau \mid \mathbf{y})\) by finding the conditional mode \(\hat{\mathbf{x}}(\tau)\) and evaluating the Hessian.
- Step 2: At each integration point \(\tau_k\), computes conditional marginals \(\tilde{p}(w_j \mid \tau_k, \mathbf{y})\).
- Step 3: Numerical quadrature integrates out \(\tau\) to produce \(\tilde{p}(w_0 \mid \mathbf{y})\) and \(\tilde{p}(w_1 \mid \mathbf{y})\).
No learning rate. No epochs. No MC samples. No gradient clipping. Fully deterministic.
# ── Extract fixed effect posteriors ──
sf = result.summary_fixed # DataFrame with mean, sd, quantiles, mode, kld
w0_mean = sf.loc["(Intercept)", "mean"] # E[w0 | y] = 1.0331
w0_sd = sf.loc["(Intercept)", "sd"] # posterior std dev = 0.0343
w0_lo = sf.loc["(Intercept)", "0.025quant"] # 2.5% quantile = 0.9657
w0_hi = sf.loc["(Intercept)", "0.975quant"] # 97.5% quantile = 1.1005
w0_mode = sf.loc["(Intercept)", "mode"] # posterior mode = 1.0331
w1_mean = sf.loc["x", "mean"] # E[w1 | y] = 1.9902
w1_sd = sf.loc["x", "sd"] # posterior std dev = 0.0291
w1_lo = sf.loc["x", "0.025quant"] # 2.5% quantile = 1.9330
w1_hi = sf.loc["x", "0.975quant"] # 97.5% quantile = 2.0475
w1_mode = sf.loc["x", "mode"] # posterior mode = 1.9902
What summary_fixed contains
result.summary_fixed is a pandas DataFrame indexed by effect name. Each row provides the complete summary of the posterior marginal \(p(w_j \mid \mathbf{y})\):
- mean: the posterior expectation \(\mathbb{E}[w_j \mid \mathbf{y}]\), optimal under squared-error loss
- sd: the posterior standard deviation, quantifying uncertainty about \(w_j\)
- 0.025quant / 0.975quant: the 95% credible interval endpoints. Unlike the Neural Network's symmetric \(\mu \pm 1.96\sigma\), these come from the actual posterior quantiles and can be asymmetric
- mode: the MAP estimate. Equals the mean for Gaussian posteriors, but differs for skewed posteriors
- kld: KL divergence from the posterior marginal to its best Gaussian fit. Near zero means the posterior is nearly Gaussian
# ── Extract hyperparameter posterior ──
sh = result.summary_hyperpar # DataFrame with precision τ = 1/σ² posterior
prec_mean = sh.iloc[0]["mean"] # E[τ | y] = 4.2833
prec_sd = sh.iloc[0]["sd"] # posterior std dev = 0.4283
prec_mode = sh.iloc[0]["mode"] # posterior mode = 4.2406 (≠ mean → skewed!)
prec_lo = sh.iloc[0]["0.025quant"] # 2.5% quantile = 3.486
prec_hi = sh.iloc[0]["0.975quant"] # 97.5% quantile = 5.163
# Convert precision to σ
sigma_from_prec = 1.0 / np.sqrt(prec_mean) # σ ≈ 1/√4.2833 = 0.4832
Precision posterior: something only INLA provides
The Neural Network treated \(\sigma\) as known and fixed. INLA treats \(\tau = 1/\sigma^2\) as an unknown hyperparameter and computes its full posterior. Note that mode (4.24) ≠ mean (4.28): the precision posterior is right-skewed. This asymmetry is captured by INLA but would be impossible to represent with the Neural Network's Gaussian assumption.
# ── Marginal log-likelihood (for model comparison) ──
mlik = result.mlik.iloc[0] # ln p(y | model) = -157.21
Marginal log-likelihood
This is \(\ln p(\mathbf{y}) = \ln \int p(\mathbf{y} \mid \mathbf{x}, \boldsymbol{\theta})\, p(\mathbf{x} \mid \boldsymbol{\theta})\, p(\boldsymbol{\theta})\, d\mathbf{x}\, d\boldsymbol{\theta}\). It measures how well the entire model (structure + priors) predicts the data, with all parameter uncertainty integrated out. Use it for Bayesian model comparison via Bayes factors: the model with the higher marginal log-likelihood is preferred. Neither the frequentist NN nor the Neural Network can compute this quantity.
pyinla(), read results. Zero hyperparameters, zero tuning, deterministic output.
Conclusion
| Uses likelihood? | Uses prior? | Output | |
|---|---|---|---|
| Frequentist NN | Yes (maximizes it) | No | Point estimates |
| Neural Network | Yes (averages in ELBO) | Yes (via KL term) | Gaussian posteriors |
| INLA | Yes (in Laplace approx.) | Yes (full Bayesian) | Full posterior marginals |
For models within the Latent Gaussian Model class, which includes linear regression, generalized linear models, mixed effects models, spatial models (SPDE, BYM), temporal models (AR1, RW1/RW2), and survival models, INLA provides the most complete and most accurate answer with the least computational cost and zero tuning.
Neural Networks are the appropriate tool when the model structure itself must be learned from data (deep nonlinear architectures) and the LGM assumption does not hold.