"""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()
本例需在 Windows、Python 3.12.14。numpy 2.5.4;torch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12.14。numpy 2.5.4;torch 2.10.0+cpu。
入口文件:projects/ai-math-mle-map-lab/likelihood-lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
likelihood-lab.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14。numpy 2.5.4;torch 2.10.0+cpu。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联54章) · 含当前章节或实例 · mbskycom202612a33.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a70.zip