Python 超參數調校
Alex Scriven
Data Scientist
你先前的作業:
neighbors_list = [3,5,10,20,50,75]
accuracy_list = []
for test_number in neighbors_list:
model = KNeighborsClassifier(n_neighbors=test_number)
predictions = model.fit(X_train, y_train).predict(X_test)
accuracy = accuracy_score(y_test, predictions)
accuracy_list.append(accuracy)
接著我們彙整到一個 dataframe 來分析。
那如果要測試 2 個超參數的取值呢?
以 GBM 演算法為例:
learn_rate [0.001, 0.01, 0.05]max_depth [4,6,8,10]我們可以用(巢狀)for 迴圈!
先寫一個建立模型的函式:
def gbm_grid_search(learn_rate, max_depth): model = GradientBoostingClassifier( learning_rate=learn_rate, max_depth=max_depth)predictions = model.fit(X_train, y_train).predict(X_test)return([learn_rate, max_depth, accuracy_score(y_test, predictions)])
現在可以走訪超參數清單並呼叫函式:
results_list = []
for learn_rate in learn_rate_list:
for max_depth in max_depth_list:
results_list.append(gbm_grid_search(learn_rate,max_depth))
我們也能把結果放進 DataFrame 並印出:
results_df = pd.DataFrame(results_list, columns=['learning_rate', 'max_depth', 'accuracy'])
print(results_df)

如果再加入更多超參數與取值,會產生更多模型。
那交叉驗證呢?
若再加更多超參數呢?
我們可以把迴圈再巢狀下去!
# 調整要測試的取值清單
learn_rate_list = [0.001, 0.01, 0.1, 0.2, 0.3, 0.4, 0.5]
max_depth_list = [4,6,8, 10, 12, 15, 20, 25, 30]
subsample_list = [0.4,0.6, 0.7, 0.8, 0.9]
max_features_list = ['auto', 'sqrt']
調整我們的函式:
def gbm_grid_search(learn_rate, max_depth,subsample,max_features):
model = GradientBoostingClassifier(
learning_rate=learn_rate,
max_depth=max_depth,
subsample=subsample,
max_features=max_features)
predictions = model.fit(X_train, y_train).predict(X_test)
return([learn_rate, max_depth, accuracy_score(y_test, predictions)])
調整 for 迴圈(巢狀):
for learn_rate in learn_rate_list:
for max_depth in max_depth_list:
for subsample in subsample_list:
for max_features in max_features_list:
results_list.append(gbm_grid_search(learn_rate,max_depth,
subsample,max_features))
results_df = pd.DataFrame(results_list, columns=['learning_rate',
'max_depth', 'subsample', 'max_features','accuracy'])
print(results_df)
現在有多少模型?
我們不可能一直巢狀下去!
而且,如果我們想要:
來建立一個網格:
max_depth 的取值learning_rate 的取值
逐一走訪網格中的每個儲存格:

(4,0.001) 等同於建立這樣的估計器:
GradientBoostingClassifier(max_depth=4, learning_rate=0.001)
此方法的幾個優點:
優點:
此方法的幾個缺點:
之後我們會介紹「具引導性」的方法!
Python 超參數調校