缘由
艺多不压身
碎碎念
我们继续飞行在云层和雾气之间,飞行在一个无光无影的空洞世界中。 ——《风沙星辰》
Ref
Bootstrap resampling and tidy regression models – tidymodels
代码
利用boostrap估计回归方程的参数
library(ggplot2)
library(tidymodels)
#️⃣ Step 1 建立非线性回归模型
# 目的:探索重量与油耗的非线性关系
# 优点:更贴合实际,避免线性假设偏差
nlsfit <- nls(mpg ~ k / wt + b, mtcars, start = list(k = 1, b = 0))
summary(nlsfit)
ggplot(mtcars, aes(wt, mpg)) +
geom_point() +
geom_line(aes(y = predict(nlsfit)))
#️⃣ Step 2 自助法重采样数据
# 目的:重复抽样 2000 次模拟数据波动
# 优点:估计结果更稳健,不依赖单次样本
set.seed(27)
boots <- bootstraps(mtcars, times = 2000, apparent = T)
boots
#️⃣ Step 3 定义拟合函数
# 目的:在每个重采样数据上拟合模型
# 优点:保证建模流程自动化、可重复
fit_nls_on_bootstrap <- function(split) {
nls(mpg ~ k / wt + b, analysis(split), start = list(k = 1, b = 0))
}
#️⃣ Step 4 批量建模与提取参数
# 目的:对所有子样本批量拟合并提取参数
# 优点:获得参数分布,而非单点估计
boot_models <-
boots %>%
mutate(model = map(splits, ~ fit_nls_on_bootstrap(.x)),
coef_info = map(model, tidy))
boot_coefs <- boot_models %>% unnest(coef_info)
#️⃣ Step 5 计算参数置信区间
# 目的:基于参数分布估计区间范围
# 优点:更直观体现不确定性,结论可靠
percentile_intervals <- int_pctl(boot_models, coef_info)
percentile_intervals
#️⃣ Step 6 可视化参数分布
# 目的:直观展示参数估计与置信区间
# 优点:避免依赖单点,增强解释力
ggplot(boot_coefs, aes(estimate)) +
geom_histogram(bins = 30) +
facet_wrap(~ term, scales = "free") +
geom_vline(aes(xintercept = .lower), data = percentile_intervals, col = "blue") +
geom_vline(aes(xintercept = .upper), data = percentile_intervals, col = "blue")
#️⃣ Step 7 可视化拟合曲线稳定性
# 目的:叠加展示不同自助样本的拟合曲线
# 优点:直观看出模型波动与稳定性
boot_aug <-
boot_models %>%
sample_n(200) %>%
mutate(augmented = map(model, augment)) %>%
unnest(augmented)
ggplot(boot_aug, aes(wt, mpg)) +
geom_line(aes(y = .fitted, group = id), alpha = .2, col = "blue") +
geom_point()