為實作模型建立過程與調參過程的分離,将模型的超參數寫如配置檔案中,以實作自動化調參
以随機森林為例:
超參數寫入variables.ini配置檔案中,每一個section可以作為一個調參的方案,并且在進行調參時,不需要對程式作出修改,簡便了調參的過程
[RandomForest0]
n_estimators = [10,18,2]
criterion = ['gini','entropy']
[RandomForest1]
n_estimators = [10,20,4]
max_depth = [6,12,2]
讀取配置檔案
import configparser
config=configparser.ConfigParser()
config.read("variables.ini")
周遊配置檔案中的超參數
#周遊配置檔案中所有的section
for section in config.sections():
#将每一個section中所有的參數儲存在para字典中
para=config.items(section)
clf=RandomForestClassifier(random_state=10)
for key, value in para:
#周遊字典中所有的超參數
value = eval(value)
#判斷參數清單長度如果為3,則采用range(start, end, step)的形式
if len(value)!=3:
param_test={key:value}
else:
start=value[0]
end=value[1]
step=value[2]
param_test={key:list(range(start,end,step))}
print(param_test)
gsearch = GridSearchCV(estimator = clf, param_grid = param_test, cv = 5)
gsearch.fit(X_train,y_train)
print(gsearch.best_score_)
print(gsearch.best_params_)
運作結果如下:
{'n_estimators': [10, 12, 14, 16]}
0.9695155091424357
{'n_estimators': 16}
{'criterion': ['gini', 'entropy']}
0.9688555456345355
{'criterion': 'entropy'}
{'n_estimators': [10, 14, 18]}
0.9697387320936371
{'n_estimators': 18}
{'max_depth': [6, 8, 10]}
0.9622267945184207
{'max_depth': 10}