2D 網格搜尋
分別獨立調整每個超參數的缺點,是不同超參數之間可能互相依賴。更好的方法是嘗試所有可能的超參數組合。不過在這種情況下,網格搜尋的空間會快速擴張。例如,我們有 2 個參數、各有 10 個可能值,最終就會需要執行 100 次實驗。
你的目標是為 Gradient Boosting 模型找出 max_depth 與 subsample 這一對超參數的最佳組合。subsample 是用來訓練各個樹時,所抽取觀測值的比例。
你已經有函式 get_cv_score(),它會接收訓練資料集與模型參數字典作為引數,並回傳 3 折交叉驗證整體的驗證 RMSE 分數。
本練習屬於課程
用 Python 拿下 Kaggle 競賽
練習說明
- 指定
max_depth與subsample的可能數值網格。max_depth:3、5、7。subsample:0.8、0.9、1.0。 - 使用
itertools套件中的product()函式套用在超參數網格上。它會回傳這兩個網格的所有可能組合。 - 將每一組超參數候選值成對傳入模型的
params字典。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
import itertools
# Hyperparameter grids
max_depth_grid = [____]
subsample_grid = [____]
results = {}
# For each couple in the grid
for max_depth_candidate, subsample_candidate in itertools.____(max_depth_grid, subsample_grid):
params = {'max_depth': ____,
'subsample': ____}
validation_score = get_cv_score(train, params)
# Save the results for each couple
results[(max_depth_candidate, subsample_candidate)] = validation_score
print(results)