RandomizedSearchCV

Python 的模型驗證

Kasey Jones

Data Scientist

網格式搜尋超參數

當從多個超參數中選值時,所有可能組合會形成一個網格。這個網格稱為超參數空間。

Python 的模型驗證

網格式搜尋續談

優點:

  • 測試所有可能組合

缺點:

  • 超參數一增加,訓練時間呈指數成長
Python 的模型驗證

更好的方法

Python 的模型驗證

隨機搜尋

from sklearn.model_selection import RandomizedSearchCV

random_search = RandomizedSearchCV()

參數分佈:

param_dist = {"max_depth": [4, 6, 8, None],
              "max_features": range(2, 11),
              "min_samples_split": range(2, 11)}
Python 的模型驗證

隨機搜尋的參數

參數:

  • estimator:要使用的模型
  • param_distributions:包含超參數與可能值的字典
  • n_iter:迭代次數
  • scoring:評分方法
Python 的模型驗證

設定 RandomizedSearchCV 參數

param_dist = {"max_depth": [4, 6, 8, None],
              "max_features": range(2, 11),
              "min_samples_split": range(2, 11)}
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import make_scorer, mean_absolute_error

rfr = RandomForestRegressor(n_estimators=20, random_state=1111)
scorer = make_scorer(mean_absolute_error)
Python 的模型驗證

實作 RandomizedSearchCV

建立隨機搜尋:

random_search =\
    RandomizedSearchCV(estimator=rfr,
                       param_distributions=param_dist,
                       n_iter=40,
                       cv=5)
  • 若不理解模型驗證,就無法進行超參數調校
  • 模型驗證能比較多個模型與參數組合
Python 的模型驗證

實作 RandomizedSearchCV

建立隨機搜尋:

random_search =\
    RandomizedSearchCV(estimator=rfr,
                       param_distributions=param_dist,
                       n_iter=40,
                       cv=5)

完成隨機搜尋:

random_search.fit(X, y)
Python 的模型驗證

一起來探索一些例子吧!

Python 的模型驗證

Preparing Video For Download...