算法手册/ 通用方法/ 两样本KS检验

两样本KS检验

计算公式

符号

符号含义
n1、n2两组有效样本量
F1、F2两组经验分布函数
D两条经验分布函数的最大垂直距离
ne有效样本量,ne = n1n2 ÷ (n1 + n2)
x(i)合并样本排序后的第 i 个观测值

核心公式

公式 (1.1):K-S 统计量 D
\[ D=\sup_x\left|F_1(x)-F_2(x)\right|=\max_{1\le i\le n_1+n_2}\left|F_1\left(x_{(i)}\right)-F_2\left(x_{(i)}\right)\right| \]
公式 (1.2):渐近双侧 p 值
\[ p\approx 2\sum_{k=1}^{\infty}(-1)^{k-1}\exp\left(-2k^2n_eD^2\right) \]
公式 (1.3):精确检验的 p 值
\[ p_{\mathrm{exact}}=\Pr\left(D_{n_1,n_2}\ge D_{\mathrm{obs}}\right) \]

小样本且两组观测没有并列值时,按 Smirnov 精确分布计算 p;样本较大或存在并列值时,改用 (1.2) 的渐近式。

参考文献

  1. Smirnov, N. (1948). Table for estimating the goodness of fit of empirical distributions. Annals of Mathematical Statistics, 19(2), 279–281.
  2. Massey, F. J. (1951). The Kolmogorov-Smirnov test for goodness of fit. Journal of the American Statistical Association, 46(253), 68–78.
  3. Conover, W. J. (1999). Practical Nonparametric Statistics (3rd ed.). Wiley.

算法参数

参数取值默认影响
缺失处理 成对剔除 / 按列表剔除 成对剔除 成对剔除时每个因变量用自己的有效样本;按列表剔除时所有变量共用一批样本。

验证报告

数据与 R 包

数据文件 ks_2samp.csv
样本与变量 N = 80;G 为二分类分组变量(A、B 各 40 例),Y 为定量变量
R 包 stats 4.6.2(R 基础包)

提示词

以 G 为分组变量、Y 为分析变量做两独立样本 Kolmogorov-Smirnov 检验,比较两条经验分布是否相同,结果保留 10 位小数。

R 代码

options(digits = 15)
d <- read.csv("ks_2samp.csv")
x <- d$Y[d$G == "A"]
y <- d$Y[d$G == "B"]
r <- ks.test(x, y, alternative = "two.sided")
print(r, digits = 15)
cat("n", length(x), length(y), "D", r$statistic, "p", r$p.value, "\n")
cat("median", median(x), median(y), "mean", mean(x), mean(y),
    "sd", sd(x), sd(y), "\n")

对比结果

指标SPSSAUR差值
样本量 A40400
样本量 B40400
D 值0.40000000000.40000000000
精确 p 值3.018184e−33.018184e−33.28e−9
中位数 A49.452309000049.45230900000
中位数 B55.766769500055.76676950000
平均值 A47.930058250047.93005825000
平均值 B56.871987150056.87198715000
标准差 A7.62940002727.62940002724.59e−11
标准差 B12.849371069712.84937106972.59e−11

结论:D 值、精确 p 值、两组均值、标准差与中位数均与 R 一致;本数据无结,R 的 ks.test 采用精确分布,与 SPSSAU 口径相同。

操作手册 问题反馈

引用SPSSAU. 两样本KS检验:计算公式与参数[EB/OL]. SPSSAU算法手册, 2026-11-20. https://www.spssau.com/algorithm/general/ks_2samp.html.