Machine Learning with scikit-learn

GridSearchCV in Python with scikit-learn

Try every combination of hyperparameters with cross-validation and keep the best: best_params_, best_score_ and cv_results_.

  • Intermédiaire
  • 2 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • Writing a param_grid
  • best_params_ and best_score_
  • Comparing combinations in cv_results_
Mean CV accuracy (rows = C, columns = linear, rbf)
C=0.1
0.947
0.857
C=1
0.964
0.938
C=10
0.946
0.964

Trying every combination

Découvrez GridSearchCV in Python with scikit-learn avec un exemple pratique modifiable et exécutable en ligne.

Points clés

  1. 3 values of C x 2 kernels = 6 combinations, each scored with 5-fold cross-validation.
  2. best_params_ is C=1 with the linear kernel; best_score_ is 0.964.
  3. C=10 with rbf ties at 0.964; the first combination in the grid wins a tie.
  4. The refitted best model scores 1.000 on the held-back test set.

Quand l’utiliser ?

  • Train and evaluate classic machine learning models on tabular data.
  • Prepare features: split, scale and encode data the way real projects do.
  • Compare models fairly with cross-validation and the right metric.

Code d’exemple

main.py
from sklearn.datasets import load_iris
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.svm import SVC

X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)

# Every combination is tried: 3 values of C x 2 kernels = 6 models, each with 5-fold cross-validation
param_grid = {"C": [0.1, 1, 10], "kernel": ["linear", "rbf"]}
search = GridSearchCV(SVC(), param_grid, cv=5)
search.fit(X_train, y_train)

print("Best parameters:", search.best_params_)
print(f"Best CV accuracy: {search.best_score_:.3f}")
print(f"Test accuracy:    {search.score(X_test, y_test):.3f}")

for params, score in zip(search.cv_results_["params"], search.cv_results_["mean_test_score"]):
    print(params, f"{score:.3f}")
Obtenir un bouton Run pour cet exemple

Résultat de l’exécution

Best parameters: {'C': 1, 'kernel': 'linear'}
Best CV accuracy: 0.964
Test accuracy:    1.000
{'C': 0.1, 'kernel': 'linear'} 0.947
{'C': 0.1, 'kernel': 'rbf'} 0.857
{'C': 1, 'kernel': 'linear'} 0.964
{'C': 1, 'kernel': 'rbf'} 0.938
{'C': 10, 'kernel': 'linear'} 0.946
{'C': 10, 'kernel': 'rbf'} 0.964

Explication du code

Cet exemple montre GridSearchCV in Python with scikit-learn en pratique. Modifiez les valeurs d’entrée et relancez le code pour voir ce qui change.

Modifiez les valeurs et exécutez le programme avec le compilateur Python en ligne CodeUtility, sans installation locale.

Exercices d’approfondissement

Essayez de modifier le code en suivant les pistes ci-dessous. Changer le code et observer le résultat vous fera bien mieux comprendre la leçon que la simple lecture.

  1. Change random_state and see how much the score moves.
  2. Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
  3. Try a different model or hyperparameter and compare the scores.
Exécuter dans le compilateur Python →

Leçon terminée ?

Marquez-la comme apprise pour suivre votre progression.

Outils pour cette leçon