Lilliefors正态性检验:拟合过均值方差,KS的p值就要重新校准

10-10 6阅读

Lilliefors正态性检验:拟合过均值方差,KS的p值就要重新校准

配图为AI生成的概念示意图,不是真实软件截图或实验数据。

让AI生成正态性检验代码时,一个很隐蔽的错误是:先用同一批数据计算均值和标准差,再把拟合出的正态分布交给普通KS检验。程序能运行,统计量也算对了,但返回的p值可能回答了另一个问题。审查这类代码,重点要看参数从哪里来。

同一个距离,对应不同的零假设

固定分布检验问的是“数据是否来自预先指定的正态分布”;通常的正态性检验问的是“是否存在某组均值、方差,使数据来自该正态分布”。后者允许估计参数,属于复合零假设。NIST说明,从待检数据估计参数后,普通KS临界区就不能直接沿用。

原因是拟合已经利用了样本信息,让参考曲线更贴近这批数据。若校准时仍把曲线当作事先固定,模拟样本便没有获得同样的拟合机会。结果往往过于保守,p值偏大。Lilliefors检验处理的正是带估计参数的KS校准问题,不需要更换距离定义。

模拟里也要重新拟合

操作顺序是:拟合原样本并计算距离D;从拟合的正态分布生成同样大小的新样本;对每份新样本重新估计均值和标准差,再算各自的D。最后统计有多少模拟距离不小于原始距离。做B次模拟、命中b次时,使用p=(b+1)/(B+1),避免把有限模拟中没有命中写成概率为零。

SciPy的goodness_of_fit文档明确区分known_params和fit_params:样本估出来的参数不能为了提速塞进前者。下面手写重新拟合过程,再与库函数逐项核对;标准差统一使用ddof=1。只需NumPy与SciPy,示例使用SciPy 1.15起支持的rng参数。

完整可运行例子

数据是人工生成的有界均匀样本,仅用于展示校准差异。保存为test.py后运行python test.py,无须下载数据。

"""Lilliefors-style Monte Carlo calibration. Requires SciPy >= 1.15."""
import numpy as np
import scipy
from scipy import stats


def fitted_ks(a):
    """Fit each row separately, then compute its two-sided KS distance."""
    a = np.asarray(a, dtype=float)
    n = a.shape[-1]
    if n < 3 or not np.all(np.isfinite(a)):
        raise ValueError("Need at least 3 finite observations per sample")
    loc = a.mean(axis=-1, keepdims=True)
    scale = a.std(axis=-1, ddof=1, keepdims=True)
    if np.any(scale <= 0):
        raise ValueError("Each sample must have positive variance")
    cdf = stats.norm.cdf((np.sort(a, axis=-1) - loc) / scale)
    right = np.arange(1, n + 1) / n
    left = np.arange(n) / n
    return np.maximum(np.max(right - cdf, axis=-1),
                      np.max(cdf - left, axis=-1))


# Artificial bounded data, not measurements from an AI product.
x = np.random.default_rng(20261010).uniform(-2, 2, size=160)
n, B = x.size, 19999
loc, scale = x.mean(), x.std(ddof=1)
d_obs = float(fitted_ks(x))

# Deliberately wrong calibration: treats fitted parameters as known.
naive = stats.ks_1samp(x, stats.norm(loc, scale).cdf, method="exact")

# Every simulated sample gets its OWN mean and standard deviation.
null_samples = np.random.default_rng(20261011).normal(
    loc=loc, scale=scale, size=(B, n))
d_null = fitted_ks(null_samples)
b = int(np.count_nonzero(d_null >= d_obs))
p_mc = (b + 1) / (B + 1)
mc_se = np.sqrt(p_mc * (1 - p_mc) / B)  # Approximate simulation SE.

# Library implementation: leave fitted parameters OUT of known_params.
ref = stats.goodness_of_fit(
    stats.norm, x, statistic="ks", n_mc_samples=B,
    rng=np.random.default_rng(20261011))

assert np.isclose(d_obs, naive.statistic, rtol=0, atol=1e-12)
assert np.isclose(d_obs, ref.statistic, rtol=0, atol=1e-12)
assert np.isclose(d_obs, fitted_ks(7 + 3 * x), rtol=0, atol=1e-12)
assert np.allclose(d_null, ref.null_distribution, rtol=0, atol=1e-12)
assert p_mc == ref.pvalue
print(f"NumPy={np.__version__}, SciPy={scipy.__version__}")
print(f"n={n}, B={B}, D={d_obs:.8f}")
print(f"naive_fixed_CDF_p={naive.pvalue:.6f}")
print(f"refitted_MC_p={p_mc:.6f}, approximate_MC_SE={mc_se:.6f}")
print(f"SciPy_refitted_p={ref.pvalue:.6f}")
print("Statistic, affine-invariance and simulation checks: PASS")

如何读这次输出

本地NumPy 2.3.5、SciPy 1.17.0实跑结果如下:

NumPy=2.3.5, SciPy=1.17.0
n=160, B=19999, D=0.07909046
naive_fixed_CDF_p=0.255792
refitted_MC_p=0.016700, approximate_MC_SE=0.000906
SciPy_refitted_p=0.016700
Statistic, affine-invariance and simulation checks: PASS

两个方法得到相同的D,但误用固定分布校准时p约为0.256,重新拟合后约为0.0167。在事先选定的5%水平下,后者拒绝正态性零假设。这个例子说明校准会改变判断,不能据此宣称每批数据都会出现同样差距。

模拟结果的边界

这里的p是尾概率的蒙特卡洛近似,模拟标准误约为0.0009;它不是“数据为正态”的概率。增加B能减少模拟波动,不能修复抽样设计。正态位置尺度族在这样的标准化后,D的零分布不依赖真实均值和标准差,但不能把这个性质推广为任意分布参数自助法都具有有限样本精确性。

上述校准针对独立同分布的连续观测。相关时间序列、明显取整数据,以及同一模型拟合后的相关残差,需要另行设计零假设与模拟流程。代码断言通过只验证实现一致;检验未拒绝也不等于证明正态,更不能单凭它判断AI模型可用。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。