開始使用免費開始

使用 RandomizedSearchCV 進行超參數調校

如你所見,GridSearchCV 的計算成本可能相當高,特別是當你要搜尋的超參數空間很大時。此時可以改用 RandomizedSearchCV,它會從指定的機率分佈中抽樣,測試固定數量的超參數組合。

diabetes_df 的訓練集與測試集已為你預先載入為 X_trainX_testy_trainy_test,其中目標變數是 "diabetes"。一個羅吉斯迴歸模型已建立並存成 logreg,同時也有一個 KFold 物件存成 kf

你將定義一組超參數範圍,並使用已從 sklearn.model_selection 匯入的 RandomizedSearchCV,從這些選項中尋找最佳的超參數。

本練習屬於課程

使用 scikit-learn 進行監督式學習

檢視課程

練習說明

  • 建立 params:在 penalty 加入 "l1""l2",將 C 設為 0.11.0 之間的 50 個浮點數,class_weight 設為 "balanced" 或字典 {0:0.8, 1:0.2}
  • 建立 Randomized Search CV 物件,傳入模型與參數,並將 cv 設為 kf
  • logreg_cv 擬合到訓練資料。
  • 列印模型的最佳參數與正確率分數。

動手互動練習

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

# Create the parameter space
params = {"penalty": ["____", "____"],
         "tol": np.linspace(0.0001, 1.0, 50),
         "C": np.linspace(____, ____, ____),
         "class_weight": ["____", {0:____, 1:____}]}

# Instantiate the RandomizedSearchCV object
logreg_cv = ____(____, ____, cv=____)

# Fit the data to the model
logreg_cv.____(____, ____)

# Print the tuned parameters and score
print("Tuned Logistic Regression Parameters: {}".format(____.____))
print("Tuned Logistic Regression Best Accuracy Score: {}".format(____.____))
編輯並執行程式碼