開始使用免費開始

視覺化置換取樣

為了幫助你理解置換取樣如何運作,這個練習要你產生置換樣本,並用圖形來觀察。

我們會再次使用 Sheffield Weather Station 的資料,這次比較 6 月(較乾)與 11 月(較濕)的月降雨量。我們預期兩者的分布可能不同,因此將進行置換取樣,觀察在「若它們分布相同」時 ECDF 會是什麼樣子。

資料已存於 NumPy 陣列 rain_junerain_november 中。

提醒你,permutation_sample() 的函式介面是 permutation_sample(data_1, data_2),回傳值為 permuted_data[:len(data_1)], permuted_data[len(data_1):],其中 permuted_data = np.random.permutation(np.concatenate((data_1, data_2)))

本練習屬於課程

Statistical Thinking in Python(第 2 部分)

檢視課程

練習說明

  • 撰寫一個 for 迴圈,產生 50 個置換樣本、計算其 ECDF,並將其繪圖。
    • 使用你的 permutation_sample() 函式,從 rain_junerain_november 產生一對置換樣本。
    • 使用你的 ecdf() 函式,為這兩個置換樣本各自產生 ECDF 的 xy 值。
    • 將第一個置換樣本(x_1y_1)的 ECDF 以點狀繪出;第二個置換樣本(x_2y_2)也同樣繪出。
  • rain_junerain_november 的資料各自產生 ECDF 的 xy 值,並分別使用關鍵字引數 color='red'color='blue' 繪出這兩條 ECDF。
  • 加上座標軸標籤、設定 2% 邊界,並顯示圖表。這部分已為你完成,按下送出即可查看圖表!

動手互動練習

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

for _ in ____:
    # Generate permutation samples
    perm_sample_1, perm_sample_2 = ____


    # Compute ECDFs
    x_1, y_1 = ____
    x_2, y_2 = ____

    # Plot ECDFs of permutation sample
    _ = plt.plot(____, ____, marker='.', linestyle='none',
                 color='red', alpha=0.02)
    _ = plt.plot(____, ____, marker='.', linestyle='none',
                 color='blue', alpha=0.02)

# Create and plot ECDFs from original data
x_1, y_1 = ____
x_2, y_2 = ____
_ = plt.plot(x_1, y_1, marker='.', linestyle='none', color='red')
_ = plt.plot(x_2, y_2, marker='.', linestyle='none', color='blue')

# Label axes, set margin, and show plot
plt.margins(0.02)
_ = plt.xlabel('monthly rainfall (mm)')
_ = plt.ylabel('ECDF')
plt.show()
編輯並執行程式碼