執行一個簡單的 bootstrap
歡迎來到 bootstrapping 小節的第一個練習。我們會透過一個例子學會如何執行簡單的 bootstrap。就像在影片裡看到的,bootstrapping 的核心概念是「有放回的抽樣」。
假設你擁有一家生產扳手的工廠。你想描述扳手的平均長度,並確認它們符合規格。工廠每天生產上千把扳手,但要量每一把的長度並不可行。不過,你手邊有 100 把扳手的具代表性樣本。讓我們用 bootstrapping 來取得平均長度的 95% 信賴區間(CI)。
在指令列中查看清單 wrench_lengths,其中包含 100 個觀察到的扳手長度。
本練習屬於課程
Python 的統計模擬
練習說明
- 從
wrench_lengths進行有放回的隨機抽樣,並將結果存成temp_sample。設定size = len(wrench_lengths)。 - 計算每個樣本的平均長度,指派給
sample_mean,然後將它加入mean_lengths。 - 使用
np.percentile()計算 bootstrap 的平均值(boot_mean)以及 bootstrap 的 95% 信賴區間(boot_95_ci)。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Draw some random sample with replacement and append mean to mean_lengths.
mean_lengths, sims = [], 1000
for i in range(sims):
temp_sample = ____(____, replace=____, size=____)
sample_mean = ____
mean_lengths.append(sample_mean)
# Calculate bootstrapped mean and 95% confidence interval.
boot_mean = np.mean(____)
boot_95_ci = ____(mean_lengths, [2.5, 97.5])
print("Bootstrapped Mean Length = {}, 95% CI = {}".format(boot_mean, boot_95_ci))