贝叶斯估计系统推导:从先验到后验

引言

贝叶斯估计是统计推断的核心范式,与频率派并立。其核心思想是:

数据出现之前,我们对参数 先验信念 ;数据 出现后,我们更新信念得到后验分布 ;对未来做预测时,我们对后验求平均

贝叶斯公式:

其中:

  • 先验(prior)
  • 似然(likelihood)
  • 后验(posterior)
  • 证据(evidence)或边缘似然

2024-2026 的发展

  • ICML 2024 立场论文:在大模型时代论证贝叶斯深度学习的必要性
  • SVGD 理论成熟:有限粒子收敛率、指数收敛、加速方法
  • DDVI:扩散模型作为变分后验
  • FSP-Laplace:函数空间先验取代权重空间先验
  • BNN 实证质疑:MC Dropout、Deep Ensembles 真的遵循贝叶斯后验吗?

本文系统推导贝叶斯估计的数学基础,并介绍现代贝叶斯深度学习。[^1]


一、贝叶斯定理基础

1.1 条件概率与全概率公式

条件概率

全概率公式:如果 是样本空间的一个划分:

贝叶斯定理

直观理解:

  • :在看到数据之前 的信念
  • :在给定 时看到数据 的可能性
  • :在看到数据之后 的信念

1.2 似然与对数似然

似然函数,视为 的函数。

对数似然(更易处理):

import numpy as np
from scipy import stats
 
def bayes_theorem_demo():
    """贝叶斯定理示例:医学诊断"""
    # 假设:疾病患病率 1%,检测灵敏度 95%,特异度 90%
    p_disease = 0.01      # 先验
    p_pos_given_disease = 0.95   # 灵敏度
    p_pos_given_healthy = 0.10   # 假阳性率
    
    # 全概率公式
    p_pos = (p_pos_given_disease * p_disease + 
             p_pos_given_healthy * (1 - p_disease))
    
    # 贝叶斯定理
    p_disease_given_pos = (p_pos_given_disease * p_disease) / p_pos
    
    print(f"检测为阳性时实际患病的概率: {p_disease_given_pos:.4f}")
    # 约 0.087:即使检测阳性,患病概率只有 8.7%
    return p_disease_given_pos

1.3 共轭先验

共轭先验:如果 属于同一分布族,则称它们共轭。

似然共轭先验后验
二项 Beta Beta
泊松 Gamma Gamma
高斯 已知)
高斯 已知)Inv-GammaInv-Gamma
指数族自然共轭指数族
def beta_binomial_update(alpha, beta, n, k):
    """Beta-Binomial 共轭更新"""
    # 先验: Beta(α, β)
    # 数据: n 次试验, k 次成功
    # 后验: Beta(α + k, β + n - k)
    return alpha + k, beta + n - k
 
def normal_normal_update(mu_0, sigma_0_sq, sigma_sq, x_bar, n):
    """Normal-Normal 共轭更新(已知方差)"""
    # 先验精度 + 数据精度 = 后验精度
    tau_0 = 1 / sigma_0_sq
    tau = n / sigma_sq
    tau_n = tau_0 + tau
    
    # 后验均值
    mu_n = (tau_0 * mu_0 + tau * x_bar) / tau_n
    
    # 后验方差
    sigma_n_sq = 1 / tau_n
    return mu_n, sigma_n_sq

二、先验选择

2.1 三大类先验

信息先验(Informative Prior):基于领域知识,反映强信念。

弱信息先验(Weakly Informative Prior):仅编码部分信息(如支持范围),避免极端值。

无信息先验(Non-informative Prior):让数据主导推断。

2.2 Jeffreys 先验

Jeffreys 先验满足不变性:参数化变换下保持不变:

其中 Fisher 信息

例子

  • Bernoulli :Jeffreys 先验
  • Poisson :Jeffreys 先验
  • 高斯 已知):Jeffreys 先验均匀
  • 高斯 已知):Jeffreys 先验

2.3 最大熵先验

最大熵先验在满足约束(如已知均值、方差)下最大化信息熵:

例子:

  • 无约束:均匀分布
  • 已知均值:高斯分布
  • 已知均值和正性:指数分布

2.4 经验贝叶斯

经验贝叶斯:从数据中估计先验参数。

:估计高斯先验的超参数:


三、似然函数

3.1 常见似然

高斯似然(连续值):

二项似然(二分类):

多项似然(多分类):

泊松似然(计数数据):

p(k | \lambda) = \frac{\lambda^k e^{-\lambda}}{k!} ``` ### 3.2 充分统计量 **充分统计量** $T(\mathcal{D})$ 满足:$p(\theta | \mathcal{D}) = p(\theta | T(\mathcal{D}))$,即 $T$ 包含了 $\theta$ 推断所需的全部信息。 **Neyman-Fisher 因子化定理**:

p(\mathcal{D} | \theta) = g(T(\mathcal{D}), \theta) h(\mathcal{D})

### 3.3 指数族分布 **指数族**统一形式:

p(x | \theta) = h(x) \exp(\eta(\theta)^T T(x) - A(\theta))

其中: - $\eta(\theta)$:**自然参数** - $T(x)$:**充分统计量** - $A(\theta)$:**对数配分函数** - $h(x)$:**基础测度** **例子**: - 高斯 $\mathcal{N}(\mu, \sigma^2)$:$\eta = (\mu/\sigma^2, -1/(2\sigma^2))$,$T = (x, x^2)$ - 二项:$\eta = \log(p/(1-p))$,$T = x$ - 泊松:$\eta = \log \lambda$,$T = x$ **指数族的共轭先验**:

p(\theta | \nu, \tau) \propto \exp(\eta^T \nu - \tau A(\theta))

--- ## 四、后验计算 ### 4.1 解析解(共轭情形) 对于共轭先验,后验解析可求: **Beta-Binomial**:

p | \mathcal{D} \sim \text{Beta}(\alpha + k, \beta + n - k)

**Normal-Normal**(已知 $\sigma^2$):

\mu | \mathcal{D} \sim \mathcal{N}(\mu_n, \sigma_n^2)

\mu_n = \frac{\sigma^2 \mu_0 + n \sigma_0^2 \bar{x}}{\sigma^2 + n \sigma_0^2}, \quad \sigma_n^2 = \frac{\sigma^2 \sigma_0^2}{\sigma^2 + n \sigma_0^2}

### 4.2 解析后验的困难 大多数情况下后验没有解析解:

p(\theta | \mathcal{D}) = \frac{p(\mathcal{D} | \theta) p(\theta)}{\int p(\mathcal{D} | \theta) p(\theta) d\theta}

分母中的积分(**证据**)通常难以计算。需要近似方法。 ### 4.3 三类近似方法 **1. 拉普拉斯近似**:用高斯近似后验 **2. 变分推断**:用简单分布族近似后验 **3. MCMC 采样**:从后验生成样本 ### 4.4 拉普拉斯近似 **核心思想**:在后验众数 $\theta^*$ 处用二阶 Taylor 展开:

\log p(\theta | \mathcal{D}) \approx \log p(\theta^* | \mathcal{D}) - \frac{1}{2} (\theta - \theta^)^T H (\theta - \theta^)

其中 $H$ 是 **Hessian 矩阵**:

H = -\nabla^2_\theta \log p(\theta | \mathcal{D}) |_{\theta = \theta^*}

p(\theta | \mathcal{D}) \approx \mathcal{N}(\theta^*, H^{-1})

**MAP 估计**:$\theta^* = \arg\max_\theta p(\theta | \mathcal{D})$。 ```python def laplace_approximation(log_posterior_fn, theta_init, n_iter=100, lr=0.01): """ 拉普拉斯近似 log_posterior_fn: 函数,输入 theta,输出 log p(θ|D) """ theta = torch.tensor(theta_init, dtype=torch.float32, requires_grad=True) optimizer = torch.optim.Adam([theta], lr=lr) for _ in range(n_iter): optimizer.zero_grad() loss = -log_posterior_fn(theta) loss.backward() optimizer.step() # 计算 Hessian theta_star = theta.detach().requires_grad_(True) log_p = log_posterior_fn(theta_star) grad = torch.autograd.grad(log_p, theta_star, create_graph=True)[0] hessian = torch.autograd.grad(grad.sum(), theta_star)[0].reshape(len(theta_star), -1) # 后验近似 theta_MAP = theta_star.detach().numpy() covariance = torch.inverse(-hessian).detach().numpy() return theta_MAP, covariance ``` --- ## 五、贝叶斯点估计 ### 5.1 后验均值(贝叶斯估计)

\hat{\theta}_{BE} = \mathbb{E}[\theta | \mathcal{D}] = \int \theta \cdot p(\theta | \mathcal{D}) d\theta

\hat{\theta}{BE} = \arg\min{\hat{\theta}} \mathbb{E}_{\theta | \mathcal{D}}[(\theta - \hat{\theta})^2]

### 5.2 后验中位数

\hat{\theta}{med} : \int{-\infty}^{\hat{\theta}_{med}} p(\theta | \mathcal{D}) d\theta = 1/2

最小化**绝对误差**。 ### 5.3 后验众数(MAP)

\hat{\theta}{MAP} = \arg\max\theta p(\theta | \mathcal{D}) = \arg\max_\theta [\log p(\mathcal{D} | \theta) + \log p(\theta)]

这是**正则化最大似然**:后验 = 似然 × 先验。 ### 5.4 三种估计的关系 | 估计 | 准则 | 计算难度 | |------|------|----------| | 后验均值 | 平方误差 | 需要积分 | | 后验中位数 | 绝对误差 | 需要分位数 | | MAP | 0-1 损失 | 优化问题 | 当后验对称时,三者相同。 --- ## 六、贝叶斯预测 ### 6.1 后验预测分布 **核心问题**:给定数据 $\mathcal{D}$,预测新数据 $\tilde{x}$。 **频率派**:点估计 $\hat{\theta}$,然后 $p(\tilde{x} | \hat{\theta})$。 **贝叶斯**:对**整个后验**求平均:

p(\tilde{x} | \mathcal{D}) = \int p(\tilde{x} | \theta) p(\theta | \mathcal{D}) d\theta

**优势**: - 自然地**量化不确定性** - 避免**过拟合**(对参数后验求平均相当于正则化) ### 6.2 后验预测的分解

p(\tilde{x} | \mathcal{D}) = \underbrace{\mathbb{E}{p(\theta | \mathcal{D})}[p(\tilde{x} | \theta)]}{\text{aleatoric + epistemic}}

- **Aleatoric 不确定性**:$p(\tilde{x} | \theta)$(数据本身的噪声) - **Epistemic 不确定性**:$p(\theta | \mathcal{D})$(参数的不确定) ### 6.3 边缘似然(模型选择) **边缘似然**(evidence):

p(\mathcal{D}) = \int p(\mathcal{D} | \theta) p(\theta) d\theta

用于**模型选择**:比较不同模型 $\mathcal{M}_i$:

p(\mathcal{M}_i | \mathcal{D}) \propto p(\mathcal{D} | \mathcal{M}_i) p(\mathcal{M}_i)

其中 $p(\mathcal{D} | \mathcal{M}_i)$ 是模型 $\mathcal{M}_i$ 下的边缘似然。 **奥卡姆剃刀的自然体现**:复杂模型需要更多数据来解释,边缘似然自动惩罚复杂度。 ```python def model_comparison(models, data): """ 贝叶斯模型比较 models: list of (name, log_likelihood_fn, log_prior_fn) """ log_evidences = [] for name, log_lik, log_prior in models: # 用数值积分或 MCMC 估计 log p(D|M) # 简化:用 Laplace 近似 theta_MAP, sigma_sq = laplace_approximation( lambda t: log_lik(t, data) + log_prior(t), theta_init=0.0 ) # 边缘似然近似 log_evidence = (log_lik(theta_MAP, data) + log_prior(theta_MAP) - 0.5 * np.log(2 * np.pi * sigma_sq)) log_evidences.append(log_evidence) print(f"{name}: log p(D|M) ≈ {log_evidence:.2f}") # 归一化 log_evidences = np.array(log_evidences) log_priors = np.zeros(len(models)) # 假设均匀先验 log_posteriors = log_evidences + log_priors posterior_probs = np.exp(log_posteriors - log_posteriors.max()) posterior_probs /= posterior_probs.sum() return posterior_probs ``` --- ## 七、贝叶斯神经网络 ### 7.1 基本思想 将神经网络权重视为**随机变量**:

\theta \sim p(\theta | \mathcal{D})

p(y^* | x^, \mathcal{D}) = \int p(y^ | x^*, \theta) p(\theta | \mathcal{D}) d\theta

优势: - **自然的不确定性量化**(参数不确定性 → 预测不确定性) - **校准的概率预测** - **抗过拟合**(参数后验平均) ### 7.2 MC Dropout **核心思想**(Gal & Ghahramani 2016): - 训练时启用 dropout - 测试时**也启用** dropout - 多次前向传播得到**后验样本** ```python class MCDropout(nn.Module): """MC Dropout:测试时的不确定性量化""" def __init__(self, d_in, d_hidden, d_out, p=0.5): super().__init__() self.fc1 = nn.Linear(d_in, d_hidden) self.fc2 = nn.Linear(d_hidden, d_hidden) self.fc3 = nn.Linear(d_hidden, d_out) self.dropout = nn.Dropout(p) def forward(self, x): # 训练和测试都启用 dropout h = F.relu(self.fc1(x)) h = self.dropout(h) h = F.relu(self.fc2(h)) h = self.dropout(h) return self.fc3(h) def predict_with_uncertainty(self, x, n_samples=100): """多次前向传播,得到预测分布""" self.train() # 保持 dropout 启用 predictions = [] for _ in range(n_samples): with torch.no_grad(): pred = self.forward(x) predictions.append(pred) predictions = torch.stack(predictions) # (n_samples, batch, d_out) mean = predictions.mean(dim=0) std = predictions.std(dim=0) return mean, std ``` ### 7.3 Deep Ensembles **核心思想**:训练多个独立网络,集成预测。 **后验机制**:每个网络是后验的一个样本,集成 = 后验求平均。 ```python def deep_ensembles(X_train, y_train, X_test, n_models=5): """Deep Ensembles 实现""" predictions = [] for i in range(n_models): model = SimpleNN(d_in=X_train.shape[1], d_hidden=64, d_out=1) optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) for epoch in range(100): pred = model(X_train) loss = F.mse_loss(pred, y_train) optimizer.zero_grad() loss.backward() optimizer.step() with torch.no_grad(): pred = model(X_test) predictions.append(pred) predictions = torch.stack(predictions) mean = predictions.mean(dim=0) std = predictions.std(dim=0) return mean, std ``` ### 7.4 拉普拉斯近似(BNN) **Daxberger et al. NeurIPS 2021** 提出 **LAFLA (Last-layer Laplace Approximation)**: 只对**最后一层**做 Laplace 近似,效率高。 **FSP-Laplace (NeurIPS 2024)** 提出**函数空间先验**:[^2] 在函数空间定义先验 $p(f) = \mathcal{GP}(\mu, k)$,再映射回权重:

\Sigma_W = (J^\top J)^{-1} J^\top \Sigma_f J (J^\top J)^{-1}

避免权重空间 Laplace 的尺度病态。 ```python class FSPLaplace(nn.Module): """函数空间先验的 Laplace 近似""" def __init__(self, base_model, kernel_fn): super().__init__() self.base_model = base_model self.kernel_fn = kernel_fn # 函数空间核 def fit(self, X_train, y_train): # 1. 训练 MAP 估计 self._train_map(X_train, y_train) # 2. 在函数空间定义先验 K = self.kernel_fn(X_train) # (n, n) # 3. 计算 Jacobian J = self._compute_jacobian(X_train) # (n, p) # 4. 权重空间协方差 JTJ_inv = torch.linalg.inv(J.T @ J + 1e-6 * torch.eye(J.shape[1])) Sigma_W = JTJ_inv @ J.T @ K @ J @ JTJ_inv self.Sigma_W = Sigma_W def predict_with_uncertainty(self, X_test, n_samples=100): mean = self.base_model(X_test) std = self._compute_predictive_std(X_test) return mean, std ``` ### 7.5 变分推断(BNN) 用变分分布 $q_\phi(\theta)$ 近似后验 $p(\theta | \mathcal{D})$: **ELBO**:

\mathcal{L}(\phi) = \mathbb{E}{q\phi(\theta)}[\log p(\mathcal{D} | \theta)] - D_{\text{KL}}(q_\phi(\theta) | p(\theta))

\theta = \mu_\phi + \sigma_\phi \odot \epsilon, \quad \epsilon \sim \mathcal{N}(0, \mathbf{I})

```python class VariationalBNN(nn.Module): """变分贝叶斯神经网络""" def __init__(self, d_in, d_hidden, d_out): super().__init__() # 变分参数 self.fc1_mu = nn.Linear(d_in, d_hidden) self.fc1_logvar = nn.Linear(d_in, d_hidden) self.fc2_mu = nn.Linear(d_hidden, d_out) self.fc2_logvar = nn.Linear(d_hidden, d_out) def reparameterize(self, mu, logvar): std = torch.exp(0.5 * logvar) eps = torch.randn_like(std) return mu + eps * std def forward(self, x): # 第一层 mu1, logvar1 = self.fc1_mu(x), self.fc1_logvar(x) w1 = self.reparameterize(mu1, logvar1) h = F.relu(w1) # 第二层 mu2, logvar2 = self.fc2_mu(h), self.fc2_logvar(h) w2 = self.reparameterize(mu2, logvar2) return w2 def kl_loss(self): """KL 散度(高斯先验)""" kl = 0 for mu, logvar in [(self.fc1_mu.weight, self.fc1_logvar.weight), (self.fc2_mu.weight, self.fc2_logvar.weight)]: kl += -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp()) return kl ``` ### 7.6 BNN 真的"贝叶斯"吗? **Pituk et al. ICML 2025** 提出关键质疑:[^3] > MC Dropout、Deep Ensembles、VI 等近似是否**真正遵循贝叶斯后验更新**?实证检验发现**显著偏差**。 **贝叶斯一致性检验**:

D_{\text{KL}}(q(\theta | \mathcal{D}) | p(\theta | \mathcal{D})) \stackrel{?}{=} 0

该论文发现: - 训练损失相同的两个网络,预测的校准不同 - Deep Ensembles 的"集成"并不等价于后验求平均 - MC Dropout 倾向于**过度自信** **实践建议**: - 不能盲目相信 BNN 的不确定性量化 - 校准验证(reliability diagrams)必不可少 --- ## 八、贝叶斯推断新方法(2024-2026) ### 8.1 DDVI:扩散变分推断 **Piriyakulkij et al. AAAI 2025** 用扩散模型作为变分后验:[^4]

q(\mathbf{z}0 | \mathbf{x}) = \int q(\mathbf{z}T) \prod{t=1}^{T} q(\mathbf{z}{t-1} | \mathbf{z}t, \mathbf{x}) d\mathbf{z}{1:T}

**优势**: - 支持**任意拓扑后验**(多模态、奇异分布) - 突破流模型的可逆约束 ### 8.2 SVGD 加速 **Carrillo & Skrzeczkowski (2024)** 证明**连续 SVGD 流的指数收敛**。 **加速 SVGD (V. Stein & W. Li 2025)**:引入动量,类比 Nesterov 加速。 ### 8.3 函数空间先验 **FSP-Laplace (NeurIPS 2024)**:用函数空间 GP 先验,避免权重空间 Laplace 的病态。 ### 8.4 摊销贝叶斯推断 **Habermann et al. (2024)** 提出**摊销贝叶斯多层模型**: 用神经网络学习**共享的推断网络** $f_\theta(\mathcal{D}, \text{context}) \to q(\theta | \mathcal{D})$,替代每数据集重跑 MCMC。 ### 8.5 贝叶斯深度学习的现代应用 - **LLM 校准**:ICML 2024 立场论文论证 BDL 在大模型时代的必要性 - **RLHF 不确定性**:贝叶斯方法量化奖励模型的不确定性 - **主动学习**:贝叶斯不确定性指导数据选择 - **科学发现**:SBI(模拟推断)用于难以写似然的科学问题 --- ## 九、关键洞察总结 ### 9.1 三大数学对象 1. **先验** $p(\theta)$:编码先验信念 2. **似然** $p(\mathcal{D} | \theta)$:数据与参数的连接 3. **后验** $p(\theta | \mathcal{D})$:更新后的信念 ### 9.2 三大估计策略 1. **MAP**:最简单(优化),但忽略后验形状 2. **后验均值**:最优(最小 MSE),但需要积分 3. **拉普拉斯/VI/MCMC**:各种近似方法 ### 9.3 三大现代挑战 1. **高维后验**:神经网络有百万参数,后验分布极其复杂 2. **BNN 校准**:流行方法不一定真正"贝叶斯" 3. **计算成本**:MCMC 难扩展,VI 有 mode-seeking 问题 --- ## 十、与其他专题的连接 - **变分推断**:VAE = 现代变分推断实现 - **MCMC**:扩散模型 = 连续 MCMC - **GNN**:消息传递 = 信念传播 - **扩散模型理论**:扩散 = SDE 的离散化 - **不确定性量化**:BNN 自然的不确定性输出 --- ## 参考资料 [^1]: Bishop, C.M. (2006). Pattern Recognition and Machine Learning. Springer. Gelman, A. et al. (2013). Bayesian Data Analysis. Chapman & Hall/CRC. [^2]: Cinquin, V. et al. (2024). FSP-Laplace: Function-Space Priors for Laplace Approximation. NeurIPS 2024. [^3]: Pituk, C. et al. (2025). Do Bayesian Neural Networks Actually Behave Like Bayesian Models? ICML 2025. [PMLR 267:49420-49458](https://proceedings.mlr.press/v267/) [^4]: Piriyakulkij, M. et al. (2024). Denoising Diffusion Variational Inference. AAAI 2025. [arXiv:2401.02739](https://arxiv.org/abs/2401.02739) #### 2024-2026 关键论文 - Papamarkou, T. et al. (2024). Bayesian Deep Learning is Needed in the Age of Large-Scale AI. ICML 2024 Position Paper. [arXiv:2402.00809](https://arxiv.org/abs/2402.00809) - Winter, S. et al. (2024). Emerging Directions in Bayesian Computation. *Statistical Science* 39(1):62-89. [DOI](https://doi.org/10.1214/23-STS919) - Fearnhead, P. et al. (2024). Scalable Monte Carlo for Bayesian Learning. Cambridge Univ. Press. [arXiv:2407.12751](https://arxiv.org/abs/2407.12751) - Deistler, M. et al. (2025). Simulation-Based Inference: A Practical Guide. [arXiv:2508.12939](https://arxiv.org/abs/2508.12939) - Banerjee, I. et al. (2024-2025). Improved Finite-Particle Convergence Rates for SVGD. [arXiv:2409.08469](https://arxiv.org/abs/2409.08469) - Carrillo, J.A. & Skrzeczkowski, J. (2024). The Stein-log-Sobolev Inequality and Exponential Convergence of Continuous SVGD. [arXiv:2412.10295](https://arxiv.org/abs/2412.10295) - Jordahn, H. et al. (2025). On Local Posterior Structure in Deep Ensembles. AISTATS 2025. - Habermann, D. et al. (2024). Amortized Bayesian Multilevel Models. [arXiv:2408.13230](https://arxiv.org/abs/2408.13230) - Faller, P.M. & Martin, J. (2025). Optimal Subspace Inference for the Laplace Approximation of BNN. [arXiv:2502.02345](https://arxiv.org/abs/2502.02345) - Gal, Y. & Ghahramani, Z. (2016). Dropout as a Bayesian Approximation. ICML 2016. *最后更新:2026-06-22*