Hyperparameter Tuning in Python
Alex Scriven
Data Scientist
Objekt 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')
Kroky Grid Search:
Důležité vstupy jsou:
estimatorparam_gridcvscoringrefitn_jobsreturn_train_score
Vstup estimator:
Pozor:
Vstup param_grid:
Místo seznamů:
max_depth_list = [2, 4, 6, 8]
min_samples_leaf_list = [1, 2, 4, 6]
Použijte:
param_grid = {'max_depth': [2, 4, 6, 8],
'min_samples_leaf': [1, 2, 4, 6]}
Vstup param_grid:
Pozor: Klíče ve slovníku param_grid musí být platné hyperparametry.
Například pro estimátor logistické regrese:
# Incorrect
param_grid = {'C': [0.1,0.2,0.5],
'best_choice': [10,20,50]}
ValueError: Invalid parameter best_choice for estimator LogisticRegression
Vstup cv:

Vstup scoring:
metrics ze Scikit-LearnVšechny vestavěné funkce pro hodnocení lze zobrazit takto:
from sklearn import metrics
sorted(metrics.SCORERS.keys())
Vstup refit:
GridSearchCV jako estimátor (pro predikci)Vstup n_jobs:
Užitečný kód:
import os
print(os.cpu_count())
Pozor: pokud potřebujete počítač i pro jinou práci, nevyužívejte všechna jádra pro trénování!
Vstup return_train_score:
Vytvoření vlastního objektu 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')
Složení dílů dohromady:
grid_rf_class = GridSearchCV(
estimator = rf_class,
param_grid = parameter_grid,
scoring='accuracy',
n_jobs=4,
cv = 10,
refit=True,
return_train_score=True)
Protože jsme nastavili refit na True, můžeme objekt přímo použít:
#Fit the object to our data
grid_rf_class.fit(X_train, y_train)
# Make predictions
grid_rf_class.predict(X_test)
Hyperparameter Tuning in Python