回归的自助法(Bootstrapping)
现在来看看自助法如何用于回归。自助法有助于估计非常规估计量的不确定性。考虑回归关联的 \(R^{2}\) 统计量。运行最小二乘回归时,您会得到一个 \(R^{2}\) 值。不过我们希望得到 \(R^2\) 的 95% 置信区间(CI)。
使用 df.head() 查看包含因变量 \(y\) 和两个自变量 $X1$、\(X2\) 的 DataFrame df。我们已经用 statsmodels(sm)拟合了该回归:
reg_fit = sm.OLS(df['y'], df.iloc[:,1:]).fit()
用 reg_fit.summary() 查看结果会发现 $R^{2}=0.3504$。请使用自助法计算 95% CI。
本练习是课程的一部分
Python 中的统计模拟
练习说明
- 使用 pandas DataFrame 的
sample()方法从原始数据集中抽取一个自助样本。行数应与原始 DataFrame 相同。 - 使用
sm.OLS()拟合与reg_fit()类似的回归,并用属性rsquared提取 \(R^{2}\) 统计量。 - 将该 \(R^{2}\) 追加到列表
rsquared_boot中。 - 使用
np.percentile()计算rsquared_boot的 95% CI,命名为r_sq_95_ci。
交互式实操练习
通过完成这段示例代码来试试这个练习。
rsquared_boot, coefs_boot, sims = [], [], 1000
reg_fit = sm.OLS(df['y'], df.iloc[:,1:]).fit()
# Run 1K iterations
for i in range(sims):
# First create a bootstrap sample with replacement with n=df.shape[0]
bootstrap = ____
# Fit the regression and append the r square to rsquared_boot
rsquared_boot.append(____(bootstrap['y'],bootstrap.iloc[:,1:]).fit().rsquared)
# Calculate 95% CI on rsquared_boot
r_sq_95_ci = ____
print("R Squared 95% CI = {}".format(r_sq_95_ci))