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_.
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
- 3 values of
Cx 2 kernels = 6 combinations, each scored with 5-fold cross-validation. best_params_is C=1 with the linear kernel;best_score_is 0.964.- C=10 with rbf ties at 0.964; the first combination in the grid wins a tie.
- 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}")
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.
- Change random_state and see how much the score moves.
- Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
- Try a different model or hyperparameter and compare the scores.
Leçon terminée ?
Marquez-la comme apprise pour suivre votre progression.
Votre progression est enregistrée dans ce navigateur Connectez-vous pour la garder sur tous vos appareils.
Outils pour cette leçon
- Jupyter Notebook en ligne : exécuter des cellules Python dans le navigateurJupyter Notebook en ligne gratuit : exécutez des cellules Python avec pandas, NumPy et Matplotlib, ajoutez du texte en Markdown, ouvrez et téléchargez des fichiers .ipynb. Sans installation, sans compte.
- Basthon, Capytale ou CodeUtility : quel outil pour Python en ligne ?Basthon, Capytale et CodeUtility comparés pour écrire du Python en ligne au lycée : à quoi sert chaque outil, compte, débogueur, exercices et classes.
- Exercices Python corrigés : s'entraîner en ligne gratuitementExercices Python corrigés pour débutants et défis vérifiés automatiquement, du plus facile au plus difficile. À faire dans le navigateur, sans installation.