Python 超參數調校
Alex Scriven
Data Scientist
介紹一個 GridSearchCV 物件:
sklearn.model_selection.GridSearchCV(
estimator,
param_grid, scoring=None, fit_params=None,
n_jobs=None, refit=True, cv='warn',
verbose=0, pre_dispatch='2*n_jobs',
error_score='raise-deprecating',
return_train_score='warn')
Grid Search 的步驟:
重要的輸入參數有:
estimatorparam_gridcvscoringrefitn_jobsreturn_train_score
estimator 參數:
提醒:
param_grid 參數:
與其用清單:
max_depth_list = [2, 4, 6, 8]
min_samples_leaf_list = [1, 2, 4, 6]
可以改為:
param_grid = {'max_depth': [2, 4, 6, 8],
'min_samples_leaf': [1, 2, 4, 6]}
param_grid 參數:
提醒:param_grid 字典中的鍵必須是有效的超參數名稱。
例如,對 Logistic regression 的 estimator:
# Incorrect
param_grid = {'C': [0.1,0.2,0.5],
'best_choice': [10,20,50]}
ValueError: Invalid parameter best_choice for estimator LogisticRegression
cv 參數:

scoring 參數:
metrics 模組你可以這樣查看所有內建評分函式:
from sklearn import metrics
sorted(metrics.SCORERS.keys())
refit 參數:
GridSearchCV 物件可直接當成 estimator(用於預測)n_jobs 參數:
實用程式碼:
import os
print(os.cpu_count())
若還要做其他工作,別把所有核心都拿去訓練模型!
return_train_score 參數:
建立自己的 GridSearchCV 物件:
# Create the grid param_grid = {'max_depth': [2, 4, 6, 8], 'min_samples_leaf': [1, 2, 4, 6]}#Get a base classifier with some set parameters. rf_class = RandomForestClassifier(criterion='entropy', max_features='auto')
把元件組合起來:
grid_rf_class = GridSearchCV(
estimator = rf_class,
param_grid = parameter_grid,
scoring='accuracy',
n_jobs=4,
cv = 10,
refit=True,
return_train_score=True)
因為我們將 refit 設為 True,可以直接使用該物件:
#Fit the object to our data
grid_rf_class.fit(X_train, y_train)
# Make predictions
grid_rf_class.predict(X_test)
Python 超參數調校