"""Reproduce sampling means, draw a normalized comparison and check framework applications."""
import argparse
from hashlib import sha256
import json
from pathlib import Path
import platform
import struct
import matplotlib
matplotlib.use("Agg")
from matplotlib import pyplot as plt
import numpy as np
def main():
cli = argparse.ArgumentParser()
cli.add_argument("--torch", action="store_true")
args = cli.parse_args()
cases = []
versions = {"numpy": np.__version__, "matplotlib": matplotlib.__version__}
def record(name, operation, inputs, expected, actual):
assert expected == actual, (name, expected, actual)
cases.append(dict(name=name, operation=operation, inputs=inputs, expected=expected, actual=actual, passed=True))
sizes = (1, 2, 5, 30)
rng = np.random.RandomState(2)
samples = {n: rng.uniform(size=(5000,n)).mean(axis=1) for n in sizes}
theory = 1 / np.sqrt(12 * np.array(sizes))
record("historical_sampling_spread", "generate independent groups with the fixed seed and compare their observed spread",
{"seed": 2, "draws_per_group": sizes, "groups": 5000},
[[.287707,.207378,.128979,.052517],[.288675,.204124,.129099,.052705]],
[[round(float(means.std()),6) for means in samples.values()], np.round(theory,6).tolist()])
means = samples[30]
z = (means-means.mean())/means.std()
record("uniform_sample_moments", "compute the empirical moments of the standardized n=30 groups",
{"size":30}, [-.054832,-.004316], [round(float(np.mean(z**3)),6),round(float(np.mean(z**4)-3),6)])
repeated = np.repeat(samples[1][:,None],30,axis=1).mean(axis=1)
record("repeat_one_draw_breaks_independence", "repeat exactly one draw across every nominal observation",
{"size":30}, [True,True], [bool(np.allclose(repeated,samples[1])),
bool(repeated.std() / means.std() > 5)])
record("exact_standard_error_scaling", "compare sizes 30 and 120 under independent draws",
[30,120],.5,round(float(np.sqrt(30/120)),6))
z1 = (samples[1]-.5)/theory[0]
z30 = (means-.5)/theory[3]
record("standardization_preserves_finite_shape", "use theoretical normalization and inspect the mass beyond two standard errors",
[1,30],[0,True],[int(np.sum(np.abs(z1)>2)),bool(np.mean(np.abs(z30)>2)>.03)])
output = Path(__file__).resolve().parent/"outputs/sample-means.png"
output.parent.mkdir(exist_ok=True)
fig, axes = plt.subplots(2,2,figsize=(9.2,5.8),layout="constrained",sharex=True,sharey=True)
domain=np.linspace(-4,4,300)
density=np.exp(-domain**2/2)/np.sqrt(2*np.pi)
for ax,n,sd in zip(axes.flat,sizes,theory):
ax.hist((samples[n]-.5)/sd,bins=np.linspace(-4,4,33),density=True,color="#45898e",alpha=.76)
ax.plot(domain,density,color="#a24d21",label="Normal reference")
ax.set(title=f"Group size n = {n}",xlim=(-4,4))
ax.grid(alpha=.23)
fig.supxlabel("Standardized sample mean")
fig.supylabel("Density")
axes[-1,-1].legend()
fig.savefig(output,dpi=100)
plt.close(fig)
data=output.read_bytes()
record("mean_histograms_rendered", "draw four distributions and a standard-normal reference using shared axes",
{"panels":4},[[920,580],True],[list(struct.unpack(">II",data[16:24])),data.startswith(b"\x89PNG\r\n\x1a\n")])
cases[-1]["artifact"]=dict(path="outputs/sample-means.png",sha256=sha256(data).hexdigest(),bytes=len(data))
if args.torch:
import torch
from torch import nn
versions["torch"] = torch.__version__
x = torch.tensor([[0.],[0.],[0.],[6.]],dtype=torch.float64)
bn = nn.BatchNorm1d(1,affine=False,track_running_stats=False,dtype=torch.float64)
observed = bn(x).flatten()
expected = (x-x.mean())/(x.var(correction=0)+bn.eps).sqrt()
record("batchnorm_on_skewed_values", "normalize a skewed batch with actual batch statistics",
x.flatten().tolist(),[True,True], [torch.allclose(expected.flatten(), observed),bool(observed[-1]>1)])
torch.manual_seed(4)
forms = (nn.init.xavier_uniform_,nn.init.xavier_normal_,nn.init.kaiming_uniform_,nn.init.kaiming_normal_)
arrays = [init(torch.empty(128,128,dtype=torch.float64)) for init in forms]
record("initialize_uniform_and_normal", "execute all four initializers and compare shape, spread and bounds",
[init.__name__ for init in forms], [True,True,True],
[all(a.shape == (128,128) and torch.isfinite(a).all() for a in arrays),
max(abs(float(a.var()) / var - 1) for a,var in zip(arrays,(1/128,1/128,2/128,2/128))) < .06,
bool(arrays[0].abs().max() < np.sqrt(6/256) and arrays[2].abs().max() < np.sqrt(6/128))])
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;matplotlib 3.11.2;torch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12.14。numpy 2.5.4;matplotlib 3.11.2;torch 2.10.0+cpu。
入口文件:projects/ai-math-clt-lab/sampling-means.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
sampling-means.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14。numpy 2.5.4;matplotlib 3.11.2;torch 2.10.0+cpu。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联54章) · 含当前章节或实例 · mbskycom202612a33.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a41.zip