Ajustement des hyperparamètres en Python
Alex Scriven
Data Scientist
Présentation d'un objet 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')
Étapes d'une recherche par grille :
Les entrées importantes :
estimatorparam_gridcvscoringrefitn_jobsreturn_train_score
L'entrée estimator :
À retenir :
L'entrée param_grid :
Plutôt qu'une liste :
max_depth_list = [2, 4, 6, 8]
min_samples_leaf_list = [1, 2, 4, 6]
Ce serait :
param_grid = {'max_depth': [2, 4, 6, 8],
'min_samples_leaf': [1, 2, 4, 6]}
L'entrée param_grid :
Rappel : les clés de votre dictionnaire param_grid doivent être des hyperparamètres valides.
Par exemple, pour un estimateur Logistic regression :
# Incorrect
param_grid = {'C': [0.1,0.2,0.5],
'best_choice': [10,20,50]}
ValueError: Invalid parameter best_choice for estimator LogisticRegression
L'entrée cv :

L'entrée scoring :
metrics de Scikit LearnPour voir toutes les fonctions de score intégrées :
from sklearn import metrics
sorted(metrics.SCORERS.keys())
L'entrée refit :
GridSearchCV comme estimateur (pour la prédiction)L'entrée n_jobs :
Code pratique :
import os
print(os.cpu_count())
Attention à ne pas utiliser tous vos cœurs si vous faites autre chose en même temps !
L'entrée return_train_score :
Créer notre propre objet 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')
Assembler les éléments :
grid_rf_class = GridSearchCV(
estimator = rf_class,
param_grid = parameter_grid,
scoring='accuracy',
n_jobs=4,
cv = 10,
refit=True,
return_train_score=True)
Comme refit est à True, vous pouvez utiliser l'objet directement :
#Fit the object to our data
grid_rf_class.fit(X_train, y_train)
# Make predictions
grid_rf_class.predict(X_test)
Ajustement des hyperparamètres en Python