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_.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • 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

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.

From baking tests to code
param_grid🗂️ The temperatures and times to try
cv=5🍰 Taste each cake 5 times
best_params_🏆 The winning combination
search.score(X_test, y_test)🍽️ Serve it to the guests
Every cell of the grid is tried with cross-validation.
In one sentence

GridSearchCV 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

  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.

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

Open in editor →
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}")
Get a Run button for this example

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.

  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.
Run in the Python compiler →

Common mistakes

Tuning on the test set

Choosing settings by the test score makes that score too optimistic; search on the training set only.

Problem
search.fit(X, y)  # before splitting
Fix
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