開始使用免費開始

以自助法建立信賴區間

評估資料變異性的一項好工具是自助法(bootstrap)。在這個練習中,你將撰寫自己的自助抽樣函式,用來回傳自助法的信賴區間。

這個函式需要三個參數:數值的 2 維陣列(data)、要計算的百分位數清單(percentiles),以及要進行的自助抽樣次數(n_boots)。它會使用 resample 函式產生一個自助樣本,並重複多次以計算信賴區間。

本練習屬於課程

Python 的時間序列資料機器學習

檢視課程

練習說明

  • 這個函式應該針對自助抽樣次數(參數 n_boots)進行迴圈,並且:
    • 以可重複抽樣的方式,從資料中隨機抽樣,並計算此隨機樣本的平均值
    • 計算 bootstrap_means 的百分位數並回傳

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

from sklearn.utils import ____

def bootstrap_interval(data, percentiles=(2.5, 97.5), n_boots=100):
    """Bootstrap a confidence interval for the mean of columns of a 2-D dataset."""
    # Create our empty array to fill the results
    bootstrap_means = np.zeros([n_boots, data.shape[-1]])
    for ii in range(____):
        # Generate random indices for our data *with* replacement, then take the sample mean
        random_sample = ____
        bootstrap_means[ii] = random_sample.mean(axis=0)
        
    # Compute the percentiles of choice for the bootstrapped means
    percentiles = ____(bootstrap_means, percentiles, axis=0)
    return percentiles
編輯並執行程式碼