最大似然估计与最大后验估计
比较同一组数据下的似然峰值、带先验的后验峰值与预测分布。
学完这一章,你能够
- 比较同一组数据下的似然峰值、带先验的后验峰值与预测分布。
同一表达式可以沿不同变量阅读
先给观测模型 p(D|θ)。固定参数 θ,它描述可能数据的质量或密度。固定已观察数据 D,把它视为参数 θ 的函数,就得到似然。似然用于比较参数,对 θ 无需归一化。密度模型用密度值计算似然。
最大似然选择使似然最大的参数。对正似然,取对数保留排序,使独立观测的概率连乘变成对数求和。遇到零似然可以用 −∞ 表示。示例让一千项很小的因子相乘,直接乘积下溢为零,对数仍能比较候选。
加入先验后的估计
MAP 最大化后验。对固定数据,证据项不随 θ 变,因此可以最大化似然乘先验。均匀先验使其支持集内的似然排序保持一致。若无约束的 MLE 在支持集之外,MAP 可能落在支持边界。固定先验在常见正则模型中会随数据增多而减弱,仍需检查可识别性和支持范围。
以十个工作日销量为例,若独立高斯观测具有共同均值和已知正方差,最大似然均值等于样本均值。实验在 23.8 和邻近两个候选上比较平方残差,23.8 的损失最低。
正态均值的 MAP 可用精度加权。似然精度是 n/σ²,先验精度是 1/τ²。假定样本均值为 5、观测方差为 4、先验 N(0,1),n=4 得 2.5,n=100 得约 4.807692。若 σ² 来自同批样本,这是插入估计。固定种子还需说明生成器。旧 RandomState(42) 的同组参数实测得到 MLE 约 4.792、插入方差的 MAP 约 4.641;新的 default_rng(42) 使用不同随机流。
训练损失、先验尺度与预测
独立的类别观测下,交叉熵可写作真实类的负对数似然。对独立且同方差的高斯残差,固定方差时负对数似然与平方误差只有固定缩放和附加常数。若估计方差,还要保留与方差有关的项。
对负对数似然之和加 λ‖w‖²,独立零均值高斯先验的每维方差是 1/(2λ)。若惩罚写成 λ‖w‖²/2,才对应 1/λ。L1 惩罚 λ‖w‖₁ 对应尺度 1/λ 的独立 Laplace 先验。把数据项取平均时,还需换算正则系数。L1 在某些目标中会给出精确零值。
贝叶斯预测对权重后验积分,实践中可以用采样近似。若预测式 y=xw+ε,权重后验方差和观测噪声都会影响预测散布。例如 x=3、Var(w)=0.25、独立噪声方差 0.04,预测方差为 2.29。网络训练可采用近似后验,模型不确定性还需用保留数据核对。
验证最大似然、精度加权和先验惩罚
"""Compare likelihood maxima, posterior modes, and posterior predictions."""
import argparse
import json
from math import exp,log
import platform
import numpy as np
def gaussian_map(mean,n,variance,prior_mean,prior_variance):
likelihood_precision=n/variance
prior_precision=1/prior_variance
return (likelihood_precision*mean+prior_precision*prior_mean)/(likelihood_precision+prior_precision)
def main():
parser=argparse.ArgumentParser()
parser.add_argument("--torch",action="store_true")
args=parser.parse_args()
cases=[]
versions={"numpy":np.__version__}
def check(name,inputs,expected,actual,operation):
assert expected==actual,(name,expected,actual)
cases.append(dict(name=name,input=inputs,operation=operation,expected=expected,actual=actual,passed=True))
sales=np.array([23,25,22,24,26,23,25,24,22,24],dtype=float)
center=float(sales.mean())
losses=[float(((sales-value)**2).sum()) for value in (center-.5,center,center+.5)]
check("normal_mean_mle",{"sales":sales.tolist(),"profile_losses":losses},[23.8,1],
[center,int(np.argmin(losses))],"compare normal negative log likelihood at and around the sample mean")
fixed=gaussian_map(5,100,4,0,1)
short=gaussian_map(5,4,4,0,1)
check("normal_map_shrinkage",{"mle":5,"known_variance":4,"prior":[0,1],"sample_sizes":[4,100]},
[2.5,4.807692], [round(short,6),round(fixed,6)], "weight prior and likelihood by precision")
rng=np.random.default_rng(42)
data=rng.normal(5.,2.,100)
plugin=float(data.var())
fitted=float(data.mean())
candidates=[gaussian_map(fitted,len(data),variance,0,1) for variance in (4.,plugin)]
check("known_vs_plugin_variance",{"seed":42,"size":100,"sample_mean":fitted,"sample_var":plugin,"map":candidates},
[True,True],[all(0<value<fitted for value in candidates),abs(candidates[0]-candidates[1])>1e-6],
"compare known likelihood variance to a data-estimated plug-in variance")
legacy=np.random.RandomState(42).normal(5.,2.,100)
legacy_fit=float(legacy.mean())
legacy_map=gaussian_map(legacy_fit,100,float(legacy.var()),0,1)
check("legacy_seed_recalculation",{"RandomState_seed":42,"sample_count":100},
[4.792,4.641], [round(legacy_fit,3),round(legacy_map,3)],
"recalculate the old random-seed recipe with a private RandomState instance")
likelihood=np.array([.01,.02])
check("likelihood_product_underflow",{"probabilities":likelihood.tolist(),"n":1000},[[0.,0.],1],
[(likelihood**1000).tolist(),int(np.argmax(1000*np.log(likelihood)))],
"show identical underflowed products but ordered log likelihoods")
grid=np.linspace(-1,4,1001)
nll=(grid-3)**2
valid=(grid>=-1)&(grid<=1)
check("bounded_uniform_prior",{"unrestricted_mode":3,"prior_support":[-1,1]},[3.,1.],
[float(grid[nll.argmin()]),float(grid[valid][nll[valid].argmin()])],
"compare the unconstrained and support-constrained optimum")
target=np.array([.5,2.,-3.])
coefficient=1.
gaussian_mode=target/(1+2*coefficient)
laplace_mode=np.sign(target)*np.maximum(np.abs(target)-coefficient,0)
check("prior_penalty_modes",{"quadratic_target":target.tolist(),"lambda":coefficient},
[[True,True,True],[0,1,-2]],
[np.isclose(gaussian_mode,[1/6,2/3,-1]).tolist(),laplace_mode.tolist()],
"compare the L2 mode with the L1 soft-threshold solution")
weight_samples=rng.normal(2.,.5,30000)
prediction=3*weight_samples+rng.normal(0,.2,weight_samples.shape)
variance=float(prediction.var())
check("posterior_predictive_variance",{"seed":42,"weight_posterior":[2,.25],"x":3,"noise_variance":.04,"variance":variance},
[True,True],[abs(float(prediction.mean())-6)<.05,abs(variance-2.29)<.08],
"sample a one-weight posterior and observational noise for prediction")
if args.torch:
import torch
import torch.nn.functional as functional
versions["torch"]=torch.__version__
logits=torch.tensor([[0.,log(3)]],dtype=torch.float64)
categorical=functional.cross_entropy(logits,torch.tensor([1]))
gaussian=torch.nn.GaussianNLLLoss(full=False, reduction="none")
actual=gaussian(torch.tensor([1.,3.],dtype=torch.float64),torch.tensor([2.,5.],dtype=torch.float64),
torch.tensor([2.,2.],dtype=torch.float64))
expected=.5*np.log(2)+np.array([1,4])/4
check("classification_and_gaussian_likelihood_losses",{"target_class":1,"observations":[2,5],"fixed_variance":2},
[True,True],[abs(float(categorical)+log(.75))<1e-12,bool(np.allclose(actual.tolist(),expected))],
"compare framework losses with their explicit negative log likelihoods")
print(json.dumps(dict(version=platform.python_version(),library_versions=versions,cases=cases)))
if __name__=="__main__":
main()
- 在已知正态观测方差下,MAP 按精度加权后向先验均值收缩。
所需环境:Windows、Python 3.12.14。numpy 2.5.4;torch 2.10.0+cpu。
当前源码 SHA256:6001b095524530ab2f6288ed5f45b891e1c240661dbaf2e4ec6b945a28343300
复跑实验
解压后按 README 运行自编程序。
所需环境:Windows、Python 3.12.14。numpy 2.5.4;torch 2.10.0+cpu。
ZIP SHA256:9358e47f574e8135b011f7e950bc26d6ea22d86ee47ca3c0bdb306ec446a138d
常见错误与边界
- 区分已知方差和插入估计。
- 对比正则公式时同时核对系数和归约。
练习与解答
为什么给同一正态模型增加样本会降低固定先验的相对权重?
展开参考解答
似然精度 n/σ² 增加,先验精度固定。