Hyperparameter Tuning in Python
Alex Scriven
Data Scientist
Vaše předchozí práce:
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)
Výsledky jsme pak shromáždili v datovém rámci pro analýzu.
Co testování hodnot 2 hyperparametrů?
Použijeme algoritmus GBM:
learn_rate [0.001, 0.01, 0.05]max_depth [4,6,8,10]Můžeme použít (vnořenou) smyčku for!
Nejprve funkce pro vytvoření modelu:
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)])
Nyní procházíme seznamy hyperparametrů a voláme funkci:
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))
Výsledky můžeme také vložit do DataFrame a vypsat:
results_df = pd.DataFrame(results_list, columns=['learning_rate', 'max_depth', 'accuracy'])
print(results_df)

Přidáním více hyperparametrů a hodnot vzniká mnohem více modelů.
Co křížová validace?
Co přidat více hyperparametrů?
Můžeme vnořit smyčky!
# Adjust the list of values to test
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']
Upravíme funkci:
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)])
Úprava smyčky (vnoření):
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)
Kolik modelů teď?
Vnořovat donekonečna nelze!
A co kdybychom chtěli:
Vytvoříme mřížku:

Procházíme každou buňku mřížky:

(4, 0.001) odpovídá vytvoření estimátoru takto:
GradientBoostingClassifier(max_depth=4, learning_rate=0.001)
Některé výhody tohoto přístupu:
Výhody:
Některé nevýhody tohoto přístupu:
„Informované" metody probereme později!
Hyperparameter Tuning in Python