You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何生成y对x线性回归斜率的1000个Bootstrap分布向量?

生成线性回归斜率的Bootstrap分布

下面提供两种实用方法来生成包含1000个线性回归斜率值的Bootstrap分布向量bootdist,结合你给出的数据实现:

方法1:手动实现(基于观测值的有放回抽样)

这是最直观的Bootstrap实现方式,核心逻辑是重复从原始(x,y)观测对中有放回抽取等量样本,每次拟合线性回归并提取斜率:

# 先将x和y组合成数据框
data_df <- data.frame(
  x = c(1, 1.5, 2, 3, 4, 4.5, 5, 5.5, 6, 6.5, 7, 8, 9, 10, 11, 12, 13, 14, 15),
  y = c(21.9, 27.8, 42.8, 48, 52.5, 52, 53.1, 46.1, 42, 39.9, 38.1, 34, 33.8, 30, 26.1, 24, 20, 11.1, 6.3)
)

# 初始化存储斜率的向量,长度设为1000
bootdist <- numeric(1000)

# 循环执行1000次Bootstrap抽样
for (i in 1:1000) {
  # 有放回抽取与原数据行数相同的样本
  boot_sample <- data_df[sample(nrow(data_df), replace = TRUE), ]
  # 拟合线性回归模型
  boot_lm <- lm(y ~ x, data = boot_sample)
  # 提取x的系数(即斜率)并存入向量
  bootdist[i] <- coef(boot_lm)[["x"]]
}

# 查看Bootstrap分布的前5个值
head(bootdist)
# 绘制直方图可视化分布
hist(bootdist, main = "Bootstrap分布:线性回归斜率", xlab = "斜率值")

方法2:使用boot包(更专业的实现)

R的boot包专门用于Bootstrap分析,代码更简洁,还能直接输出置信区间等统计量:

# 首次使用需安装包
# install.packages("boot")
library(boot)

# 定义一个辅助函数:输入数据和抽样索引,返回斜率值
get_slope <- function(data, indices) {
  boot_sample <- data[indices, ]
  lm_fit <- lm(y ~ x, data = boot_sample)
  return(coef(lm_fit)[["x"]])
}

# 执行1000次Bootstrap抽样
boot_result <- boot(data = data_df, statistic = get_slope, R = 1000)

# 提取斜率的Bootstrap分布向量
bootdist <- boot_result$t

# 查看结果详情
head(bootdist)
print(boot_result)
# 绘制Bootstrap分布的诊断图
plot(boot_result)

补充:残差Bootstrap(可选)

如果更关注残差的随机性,也可以基于残差进行抽样生成新的y值,再拟合回归:

# 先拟合原始模型得到残差和预测值
lm.out <- lm(y ~ x, data = data_df)
resids <- residuals(lm.out)
ypred <- fitted(lm.out)

# 初始化残差Bootstrap的斜率向量
bootdist_resid <- numeric(1000)

for (i in 1:1000) {
  # 有放回抽取残差
  boot_resids <- sample(resids, replace = TRUE)
  # 生成新的y值:预测值 + 抽样残差
  y_new <- ypred + boot_resids
  # 拟合回归并提取斜率
  boot_lm <- lm(y_new ~ x, data = data_df)
  bootdist_resid[i] <- coef(boot_lm)[["x"]]
}

# 可视化残差Bootstrap的斜率分布
hist(bootdist_resid, main = "残差Bootstrap:斜率分布", xlab = "斜率值")

内容的提问来源于stack exchange,提问作者Charlie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 08:01:02