調整視窗大小
你想親自驗證在心律不整資料集上,最佳的視窗大小為 50。你已收到一個名為 arrh 的 pandas 資料框,並想使用時間到 t_now 為止的資料子集。測試資料為 X_test、y_test。你會嘗試多個視窗大小,範圍從 10 到 100,對每個視窗訓練一個 naive Bayes 分類器,在測試資料上評估其 F1 分數,然後挑選表現最佳的視窗大小。你也可以使用 numpy(別名 np),而函式 f1_score() 已經匯入。最後,已為你初始化一個名為 accuracies 的空清單,用來儲存各視窗的準確度。
本練習屬於課程
在 Python 設計機器學習工作流程
練習說明
- 使用
.loc()方法,定義一個在t_now停止、大小為w_size的滑動視窗索引。 - 從該滑動視窗建立
X,方法是移除class欄,並將該欄存為y。 - 對
X與y擬合一個 naive Bayes 分類器,並用它來預測測試資料X_test的標籤。 - 計算每個視窗大小下的預測 F1 分數,並找出表現最好的視窗大小。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Loop over window sizes
for w_size in wrange:
# Define sliding window
sliding = arrh.____[____:t_now]
# Extract X and y from the sliding window
X, y = sliding.____('class', ____), sliding[____]
# Fit the classifier and store the F1 score
preds = GaussianNB().fit(____, ____).____(X_test)
accuracies.append(____(____, ____))
# Estimate the best performing window size
optimal_window = ____[np.____(accuracies)]