開始使用免費開始

Scikit Learn 中的 RandomizedSearchCV

來練習使用 Scikit Learn 建立一個 RandomizedSearchCV 物件。

超參數網格應包含 max_depth(5 到 25 之間且包含端點的所有值)與 max_features('auto' 與 'sqrt')。

這個 RandomizedSearchCV 物件需要的設定如下:

  • 使用 n_estimators 為 80 的 RandomForestClassifier 作為估計器。
  • 3 折交叉驗證(cv)。
  • 使用 roc_auc評分模型。
  • 平行處理時使用 4 個核心(n_jobs)。
  • 重新訓練最佳模型並回傳訓練分數。
  • 為了效率只抽樣 5 個組合(n_iter)。

X_trainy_train 資料集已為你載入。

記得,若要擷取被選中的超參數,可在 cv_results_ 中找到;每個超參數會對應到一個欄位。例如,超參數 criterion 的欄位會是 param_criterion

本練習屬於課程

Python 超參數調校

檢視課程

練習說明

  • 依照上方說明建立超參數網格。
  • 依照上方說明建立 RandomizedSearchCV 物件。
  • RandomizedSearchCV 物件擬合到訓練資料。
  • 存取 cv_results_,列印出模型程序為兩個超參數(max_depthmax_features)所選擇的值。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Create the parameter grid
param_grid = {'max_depth': list(range(____,26)), 'max_features': [____ , ____]} 

# Create a random search object
random_rf_class = RandomizedSearchCV(
    estimator = ____(n_estimators=____),
    param_distributions = ____, n_iter = ____,
    scoring=____, n_jobs=____, cv = ____, refit=____, return_train_score = ____ )

# Fit to the training data
____.fit(X_train, y_train)

# Print the values used for both hyperparameters
print(random_rf_class.cv_results_[____])
print(random_rf_class.cv_results_[____])
編輯並執行程式碼