最佳化閾值
你聽說理論上預設值 0.5 能使 accuracy 最大化,但你想實際測試看看。於是你嘗試多個不同的閾值,觀察各自得到的 accuracy,進而找出表現最好的閾值。接著你也對 F1 分數重複同樣的實驗。0.5 真的是最佳閾值嗎?accuracy 與 F1 的最佳閾值會一樣嗎?動手找出答案吧!你手上有以測試資料評分得到的 scores 矩陣。測試資料的真實標籤 y_test 也可取得。最後,已預先載入兩個 numpy 函式 argmin() 與 argmax()(分別用來取得陣列最小值與最大值的索引),以及評估指標 accuracy_score() 與 f1_score()。
本練習屬於課程
在 Python 設計機器學習工作流程
練習說明
- 建立一組包含 0.0、0.25、0.5、0.75、1.0 的閾值範圍。
- 透過雙層串列推導式,將上述每個閾值的預測結果存起來。回想一下,對於分數矩陣,使用閾值
thr取得標籤可寫為[s[1] > thr for s in scores]。 - 走訪該預測列表並計算每個閾值的 accuracy。對 F1 分數重複一次。
- 使用
argmin()或argmax(),找出 accuracy 與 F1 各自的最佳閾值。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create a range of equally spaced threshold values
t_range = ____
# Store the predicted labels for each value of the threshold
preds = [[____ > thr for s in scores] for ____ in ____]
# Compute the accuracy for each threshold
accuracies = [____(____, ____) for p in preds]
# Compute the F1 score for each threshold
f1_scores = [____(____, ____) for p in preds]
# Report the optimal threshold for accuracy, and for F1
print(t_range[____(accuracies)], t_range[____(f1_scores)])