開始使用免費開始

使用 GridSearchCV 尋找最佳參數

在這個練習中,你將不再以「隨機」方式微調模型,而是改用 GridSearchCV 幫你完成設定搜尋。

使用 GridSearchCV 時,你可以指定要用哪個效能指標來評分不同的選項。因為詐欺偵測最在意能抓到盡可能多的詐欺案例,你可以將模型設定最佳化為 Recall 分數。如果你同時在意降低誤判為詐欺(false positives)的數量,也可以最佳化 F1-score,這能帶來不錯的 Precision–Recall 取捨。

GridSearchCV 已從 sklearn.model_selection 匯入,來試試看吧!

本練習屬於課程

Fraud Detection in Python

檢視課程

練習說明

  • 在參數網格中設定要嘗試 1 與 30 棵樹,並嘗試分裂準則 gini 與 entropy。
  • 定義一個簡單的 RandomForestClassifier,並將 random_state 保持為 5,以便比較模型。
  • 設定 scoring 使其針對 recall 進行最佳化。
  • 將模型擬合到訓練資料 X_train 與 y_train,並取得模型的最佳參數。

動手互動練習

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

# Define the parameter sets to test
param_grid = {'n_estimators': [____, ____], 'max_features': ['auto', 'log2'],  'max_depth': [4, 8], 'criterion': ['____', '____']
}

# Define the model to use
model = ____(random_state=5)

# Combine the parameter sets with the defined model
CV_model = GridSearchCV(estimator=model, param_grid=param_grid, cv=5, scoring='____', n_jobs=-1)

# Fit the model to our training data and obtain best parameters
CV_model.fit(____, ____)
CV_model.____
編輯並執行程式碼