缘由
艺多不压身
碎碎念
我们继续飞行在云层和雾气之间,飞行在一个无光无影的空洞世界中。 ——《风沙星辰》
Ref
Hypothesis testing using resampling and tidy data – tidymodels
Chapter 9 Hypothesis Testing | Statistical Inference via Data Science
解读
infer 的四个核心函数
infer 的推断流程很统一,主要分为 4 步:
- specify():指定变量关系,选择研究的统计量(均值、比例、均值差、相关系数等)。
- hypothesize():声明原假设(点假设或独立性假设)。
- generate():在原假设下生成数据(bootstrap 重抽样 / permute 置换 / simulate 模拟)。
- calculate():计算统计量,用于点估计、假设检验或置信区间。
核心思想:基于数据的重抽样和置换,而不是完全依赖书本上的理论分布。
示例 1:单样本均值检验
问题:人们每周平均工作时长是不是 40 小时?
- 原假设 H₀:总体均值 = 40
- 统计量:样本均值
- 传统方法:
t.test(gss$hours, mu = 40)infer 方法:
library(tidymodels)
set.seed(1234)
data(gss)
# 点估计
point_estimate <- gss %>%
specify(response = hours) %>%
calculate(stat = "mean")
# 在原假设下生成 bootstrap 分布
null_dist <- gss %>%
specify(response = hours) %>%
hypothesize(null = "point", mu = 40) %>%
generate(reps = 5000, type = "bootstrap") %>%
calculate(stat = "mean")
# 计算 p 值
null_dist %>%
get_p_value(obs_stat = point_estimate, direction = "two_sided")解读:infer 利用 bootstrap 重抽样直接生成原假设下的均值分布;t 检验依赖正态近似。两者大样本下结果接近,但 infer 更直观、易理解。
示例 2:两组均值差(置换检验)
问题:有大学学位的人和没有学位的人,平均年龄是否不同?
- 原假设 H₀:学历与年龄独立 → 两组均值差 = 0
- 统计量:均值差
- 传统方法:
t.test(age ~ college, data = gss)infer 方法:
# 点估计
point_estimate <- gss %>%
specify(age ~ college) %>%
calculate(stat = "diff in means", order = c("degree", "no degree"))
# 在独立性假设下生成置换分布
perm_dist <- gss %>%
specify(age ~ college) %>%
hypothesize(null = "independence") %>%
generate(reps = 5000, type = "permute") %>%
calculate("diff in means", order = c("degree", "no degree"))
# 计算 p 值
perm_dist %>%
get_p_value(obs_stat = point_estimate, direction = "two_sided")解读:置换检验通过不断打乱分组标签,模拟“独立”的世界,再计算均值差。相比 t 检验,这种方法完全不依赖分布假设,更稳健。
示例 3:Bootstrap 置信区间
问题:每周平均工作时长的 95% 置信区间是多少?
- 原假设 H₀:不需要,关注估计区间
- 统计量:均值
- 传统方法:
t.test(gss$hours)$conf.intinfer 方法:
boot_dist <- gss %>%
specify(response = hours) %>%
generate(reps = 5000, type = "bootstrap") %>%
calculate(stat = "mean")
# bootstrap 百分位法置信区间
boot_dist %>%
get_confidence_interval(level = 0.95, type = "percentile")解读:t 检验基于正态分布和标准误,bootstrap 百分位法直接取重抽样分布分位点,更稳健,尤其适用于偏斜或非对称分布。