蓝色天空.知识 · 实践 · 创造
我的收藏
AI 数学基础 教程目录 54章
课程介绍
AI 数学基础 / LEARN BY DOING

中心极限定理的可视化

用均匀分布的重复抽样区分样本均值的波动和标准化极限。

学完这一章,你能够

  • 用均匀分布的重复抽样区分样本均值的波动和标准化极限。

画出统计量的抽样分布

从 U(0,1) 独立抽取 n 个数求一次平均,重复 5000 组。每个组均值产生一条直方图记录。原始值的直方图接近均匀,组均值随 n 增大向 0.5 集中。班级平均身高是某一组的一个数,要观察平均值的分布需构造许多相同抽样设计的组。依赖、重尾和抽样偏差都需要重新检查条件。

对独立同分布、方差有限且非零的 Xᵢ,Zₙ=(X̄ₙ−μ)/(σ/√n) 依分布收敛到标准正态。独立情形下 Var(X̄ₙ)=σ²/n 已是精确关系。均匀 U(0,1) 的中心为 0.5,方差是 1/12,因此标准误是 1/√(12n)。

比较 n=1、2、5、30 的结果

固定随机种子 2,四组的样本均值标准差实测约 0.287707、0.207378、0.128979、0.052517。n=30 的经验偏度约 −0.054832,超峰度约 −0.004316。这些有限样本量是形状诊断。对照图还画出理论标准正态密度,共用横轴尺度。

样本量一、二、五、三十的标准化组均值直方图与同尺度正态曲线。
本站程序实际生成的四组直方图。横坐标统一为标准化组均值。

批归一化按实际均值与方差计算,输入可以偏离正态。Xavier 和 He 初始化各有均匀及正态形式。回归选用高斯误差模型时,应以残差和任务假设验证。程序还展示完全相关的组内数据会破坏标准误缩放。

三个应用与正态假设

场景实际条件与观察
批归一化对每个特征用均值、方差与 ε 归一化,再按配置做仿射变换。偏斜输入仍可计算。
权重初始化库同时提供 Xavier 与 He 的均匀、正态接口,各自按 fan 与非线性选择尺度。
误差建模有限方差独立项叠加可解释某些近似,完全相关的误差就不能沿用独立样本公式。

绘制四组标准化样本均值分布

含完整源码 · 93 行
展开查看收起
python
"""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()

保存 920×580 的四格图。n=30 的均值标准差约为 0.052517。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

复跑实验

解压后按 README 运行自编程序。

下载本章实验包 (mbskycom202612a33.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:AI 数学基础

课程关联工程包(登记关联54章) · 含当前章节或实例 · mbskycom202612a33.zip

下载课程关联工程包:AI 数学基础

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a41.zip

常见错误与边界检查

  • n 指每组样本量,5000 是独立组数。
  • 直方图依赖分箱,经验偏度和峰度近零不足以推出精确正态。

技术规范与官方资料

练习与参考解答

查看参考解答

样本量变为 4 倍,标准差减半。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习