選擇下一個最佳變數
前向逐步變數選擇會從空的變數集合開始,逐步加入變數;在每一步都加入下一個最佳變數。為了幫你實作這個流程,我們已經替你準備了兩個方便的函式。
auc 函式會計算給定變數集合 variables 的模型 AUC,該模型使用此變數集合作為解釋變數。next_best 函式會計算在下一步應該把哪一個變數加入到變數清單中。
在本練習中,你會動手試用這些函式,以更清楚理解它們的用途。你將計算指定變數集合的 AUC,找出下一個應該加入的變數,並驗證這樣確實能得到最佳的 AUC。
本練習屬於課程
Python 預測分析入門
練習說明
auc函式已為你實作好。計算以"max_gift"、"mean_gift"和"min_gift"作為解釋變數的模型 AUC。你應該把這些變數用清單傳入,作為auc函式的第一個引數。next_best函式已為你實作好。已知目前模型包含"max_gift"、"mean_gift"和"min_gift",而"age"與"gender_F"為候選的下一個解釋變數。請計算下一步應加入哪個變數。next_best的第一個引數是目前變數的清單,第二個引數是候選解釋變數的清單。- 計算以
"max_gift"、"mean_gift"、"min_gift"和"age"作為解釋變數的模型 AUC。 - 計算以
"max_gift"、"mean_gift"、"min_gift"和"gender_F"作為解釋變數的模型 AUC。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Calculate the AUC of a model that uses "max_gift", "mean_gift" and "min_gift" as predictors
auc_current = ____([____, ____, ____], ["target"], basetable)
print(round(auc_current,4))
# Calculate which variable among "age" and "gender_F" should be added to the variables "max_gift", "mean_gift" and "min_gift"
next_variable = ____([____, ____, ____], [____, ____], ["target"], basetable)
print(next_variable)
# Calculate the AUC of a model that uses "max_gift", "mean_gift", "min_gift" and "age" as predictors
auc_current_age = ____([____, ____, ____, ____], ["target"], basetable)
print(round(auc_current_age,4))
# Calculate the AUC of a model that uses "max_gift", "mean_gift", "min_gift" and "gender_F" as predictors
auc_current_gender_F = ____([____], ["target"], basetable)
print(round(auc_current_gender_F,4))