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_.
- Writing a param_grid
- best_params_ and best_score_
- Comparing combinations in cv_results_
Trying every combination
The problem
Models have settings you choose before training, such as C and the kernel of an SVM. Guessing them by hand is slow, and tuning them on the test set makes the test score meaningless.
Think of it like this
GridSearchCV is like testing a recipe with every combination of oven temperature and baking time on a grid, tasting each cake several times, and writing down the best combination before serving it to guests.
param_grid🗂️ The temperatures and times to trycv=5🍰 Taste each cake 5 timesbest_params_🏆 The winning combinationsearch.score(X_test, y_test)🍽️ Serve it to the guestsGridSearchCV trains and cross-validates a model for every combination of the hyperparameter values you list, then refits the best one on all the training data.
Key points
- 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.
When should you use it?
- Tuning a model's hyperparameters.
- Comparing a handful of settings fairly.
- Tuning a whole pipeline, including preprocessing steps.
When not to use it
- Many parameters with many values: the grid explodes; use RandomizedSearchCV.
- Very slow models: each combination is trained cv times.
Example code
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}")
Result of running the code
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
Code explanation
param_grid lists 3 values of C and 2 kernels, so GridSearchCV trains 6 SVC models, each scored with 5-fold cross-validation on the training set only. best_params_ is C=1 with the linear kernel and best_score_ is its mean accuracy, 0.964. C=10 with rbf scores the same, and GridSearchCV keeps the first combination in the grid when there is a tie. After the search the best model is refitted on all training data, and search.score on the held-back test set gives 1.000. cv_results_ holds the score of every combination.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- 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.
Common mistakes
Tuning on the test set
Choosing settings by the test score makes that score too optimistic; search on the training set only.
search.fit(X, y) # before splitting
search.fit(X_train, y_train); search.score(X_test, y_test)
Finished this lesson?
Mark it as learned to track your progress.
Tools for this lesson
- Jupyter Notebook Online: Run Python Cells in Your BrowserFree online Jupyter notebook: run Python cells with pandas, NumPy and Matplotlib, add Markdown text, open and download .ipynb files. No install, no account.
- pandas Online Compiler: Run pandas and NumPy in Your BrowserRun pandas and NumPy code online with nothing to install. NumPy, pandas, SciPy, Matplotlib and scikit-learn are ready in the free Python editor.
- How to Plot a Graph in Python Online (Matplotlib Examples)Plot a graph in Python online with Matplotlib: lines, functions like sin(x), data from a CSV, bar and pie charts. Run each example in your browser.