撰寫配對 bootstrap 的函式
正如影片所說,配對 bootstrap 會對資料的成對觀測進行重抽樣。每一組成對資料都用直線擬合,本題使用 np.polyfit()。我們會重複這個流程,得到參數值的 bootstrap 重抽樣。為了方便執行配對 bootstrap,你將撰寫一個函式,對一組 x,y 資料進行配對 bootstrap。
本練習屬於課程
Statistical Thinking in Python(第 2 部分)
練習說明
- 定義一個函式,呼叫簽章為
draw_bs_pairs_linreg(x, y, size=1),用來對線性迴歸參數執行配對 bootstrap 估計。- 使用
np.arange()建立從0到len(x)的索引陣列。你會重抽樣這些索引,並用來從x與y陣列取值。 - 使用
np.empty()初始化斜率與截距的重抽樣陣列,大小為size。 - 撰寫一個
for迴圈以:- 重抽樣索引
inds。使用np.random.choice()來完成。 - 使用重抽樣索引
bs_inds建立新的 \(x\) 與 \(y\) 陣列bs_x與bs_y。為此,使用bs_inds對x與y進行切片。 - 在新的 \(x\) 與 \(y\) 陣列上使用
np.polyfit(),並儲存計算得到的斜率與截距。
- 重抽樣索引
- 回傳斜率與截距的配對 bootstrap 重抽樣陣列。
- 使用
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
def draw_bs_pairs_linreg(x, y, size=1):
"""Perform pairs bootstrap for linear regression."""
# Set up array of indices to sample from: inds
inds = ____
# Initialize replicates: bs_slope_reps, bs_intercept_reps
bs_slope_reps = ____
bs_intercept_reps = ____
# Generate replicates
for i in range(size):
bs_inds = np.random.choice(____, size=____)
bs_x, bs_y = x[____], y[____]
bs_slope_reps[i], bs_intercept_reps[i] = ____
return bs_slope_reps, bs_intercept_reps