迴歸的自助法(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))