Home/ Machine Learning/ GridSearchCV Explained: Hyperparameter Tuning in scikit-learn (With Examples)
Machine Learning

GridSearchCV Explained: Hyperparameter Tuning in scikit-learn (With Examples)

Learn GridSearchCV step by step: a full Python scikit-learn Pipeline example, the cost formula, how to read cv_results_, and how to avoid the test-set trap.

GridSearchCV is scikit-learn’s tool for hyperparameter tuning. You give it a model and a list of candidate settings. It tries every combination, scores each one with cross-validation, and hands back the best. This guide runs one dataset from start to finish, so every number you see is reproducible. It also works out the cost of a grid before you run it, and shows how to keep your test set honest.

What hyperparameter tuning is, and where GridSearchCV fits

A model has two kinds of numbers. Parameters are learned from data during training. Hyperparameters are chosen by you before training starts, and they control how the model learns.

Parameters Hyperparameters
Set by The training algorithm You (or a search procedure)
Examples Linear regression coefficients, tree split thresholds SVM C and gamma, forest max_depth, learning rate
Learned from Training data Validation performance
Changed during fit() Yes No

Hyperparameter tuning is the search for the hyperparameter values that give the best performance on data the model has not seen. GridSearchCV is the simplest systematic way to do that in scikit-learn: exhaustive search over a grid you define, with cross-validation for scoring.

How grid search works

Grid search has four moving parts.

  1. The grid. A dictionary mapping each hyperparameter name to a list of values to try.
  2. The combinations. Every possible pairing of those values. Two hyperparameters with 4 values each give 4 × 4 = 16 combinations.
  3. Cross-validation. For each combination, the training data is split into cv folds. The model trains on cv − 1 folds and is scored on the remaining one. This repeats so each fold is held out once, and the scores are averaged.
  4. Refit. By default (refit=True), GridSearchCV retrains the best combination on the whole training set. That final model is available as best_estimator_.

For classifiers with an integer cv, scikit-learn uses stratified folds, so class proportions are preserved in each fold.

Three-step diagram: a 4-by-4 grid of C and gamma combinations, a five-fold cross-validation strip with one blue test block per row, and a block of 80 small squares, ending in 16 combinations times 5 folds equals 80 model fits.
Sixteen combinations, each fitted once per fold: 16 × 5 = 80 fits before a single best parameter is chosen, plus one refit of the winner.

First complete example, step by step

Setup. The dataset is the Breast Cancer Wisconsin dataset, bundled with scikit-learn (load_breast_cancer): 569 samples, 30 numeric features, two classes (212 malignant, 357 benign). The model is a support vector classifier with an RBF kernel, and we tune C and gamma. We hold out 20% as a test set (455 train, 114 test) with random_state=42.

import time
import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

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

# The scaler lives INSIDE the pipeline, so it is re-fitted on each CV training fold
pipe = Pipeline([
    ("scaler", StandardScaler()),
    ("svc", SVC(kernel="rbf")),
])

# Pipeline step name + double underscore + parameter name
param_grid = {
    "svc__C": [0.1, 1, 10, 100],
    "svc__gamma": [0.001, 0.01, 0.1, 1],
}

grid = GridSearchCV(pipe, param_grid, cv=5, scoring="accuracy", n_jobs=1)

start = time.perf_counter()
grid.fit(X_train, y_train)          # the test set is not used here
elapsed = time.perf_counter() - start

print(f"Combinations: {len(grid.cv_results_['params'])}")
print(f"Wall-clock time: {elapsed:.2f}s")
print("Best parameters:", grid.best_params_)
print(f"Best CV accuracy: {grid.best_score_:.4f}")

results = pd.DataFrame(grid.cv_results_)
cols = ["param_svc__C", "param_svc__gamma", "mean_test_score",
        "std_test_score", "rank_test_score"]
print(results[cols].sort_values("rank_test_score").to_string(index=False))

What this run produced (scikit-learn 1.9.1, NumPy 2.5.4, pandas 3.0.6, Python 3.12.3):

Combinations: 16
Wall-clock time: 0.93s
Best parameters: {'svc__C': 10, 'svc__gamma': 0.01}
Best CV accuracy: 0.9802

The top of the sorted results table:

C gamma mean CV accuracy std rank
10 0.01 0.9802 0.0162 1
100 0.001 0.9780 0.0155 2
10 0.001 0.9736 0.0149 3
1 0.01 0.9692 0.0235 4
100 0.01 0.9692 0.0162 4

Timings depend on your machine. Parameters and scores should match yours exactly if your library versions are the same.

Reading the results: cv_results_, best_params_, best_score_

  • best_params_ is the combination with the highest mean cross-validated score: here C=10, gamma=0.01. Note the svc__ prefix: it names the pipeline step.
  • best_score_ is that combination’s mean validation score across the 5 folds (0.9802). It is not a test score. It was also used to pick the winner, so it is slightly optimistic as an estimate of future performance.
  • cv_results_ is a dictionary holding the full record: one row per combination, with mean_test_score, std_test_score, rank_test_score, mean_fit_time and the parameters tried. Wrap it in pd.DataFrame to read it.

Three habits make the results more useful than a single “best” line:

  1. Look at std_test_score. The winner’s standard deviation is 0.016, and the runner-up scores 0.9780. That gap is far smaller than the fold-to-fold spread, so the top few rows are effectively tied.
  2. Look at the shape, not just the winner. Here is the full grid of mean CV accuracy:
C \ gamma 0.001 0.01 0.1 1
0.1 0.7363 0.9429 0.9451 0.6264
1 0.9473 0.9692 0.9604 0.6308
10 0.9736 0.9802 0.9516 0.6352
100 0.9780 0.9692 0.9473 0.6352

Accuracy collapses at gamma=1 for every C (the RBF kernel becomes too narrow and the model overfits). The good region is a diagonal band where a larger C pairs with a smaller gamma. That tells you where to zoom in next.

Heatmap of mean cross-validation accuracy with C on the x-axis (0.1, 1, 10, 100) and gamma on the y-axis (0.001, 0.01, 0.1, 1), darker cells scoring higher, with the best combination C=10 and gamma=0.01 outlined and starred at 0.9802.
The cv_results_ surface: the outlined cell is best_params_ (C = 10, gamma = 0.01), but the plateau around it is what makes the choice robust.
  1. Check that the winner is not on the grid’s edge. If the best value sits at the boundary of a list, the true optimum may lie outside your grid.

The cost maths: plan before you run

Grid search cost is predictable, so calculate it first.

Total fits = combinations × folds (+ 1 refit)
Estimated time ≈ total fits × seconds per fit ÷ parallel workers

This article’s grid. Combinations = 4 (C) × 4 (gamma) = 16. With cv=5, that is 16 × 5 = 80 fits, plus 1 refit of the winner = 81. A single fit of this pipeline took about 0.005 s here, so the cost is trivial and the whole search took 0.93 s.

Why it matters. Combinations multiply, so every extra hyperparameter multiplies the cost. Take an illustrative case with made-up round numbers: a forest where each fit takes 30 seconds, and a grid of 5 × 5 × 4 = 100 combinations with cv=5. That is 500 fits × 30 s = 15,000 s, about 4.2 hours on one core. Adding one more hyperparameter with 4 values would quadruple it. The rule: estimate one fit, multiply, then decide whether the grid is affordable. Time a single fit() and use n_jobs=-1 to spread work across cores.

The test-set trap and the fix

The trap: you try many settings, look at the test score each time, and keep what scores best. The test set has now guided your choices, so its score is no longer an honest estimate. A second, quieter version of the same trap is leakage through preprocessing. (For the basics of why the split matters, see training and testing data.)

The fix is a workflow with three rules:

  1. Split once, early. Set the test set aside before any tuning.
  2. Put every learned preprocessing step inside a Pipeline. GridSearchCV then refits the scaler on each fold’s training portion only, so the held-out fold never influences it.
  3. Touch the test set once, at the very end, with the final chosen model.
# Final, single evaluation after ALL tuning is finished
final_model = grid.best_estimator_      # already refit on the full training set
print(f"Test accuracy: {final_model.score(X_test, y_test):.4f}")

On this run the test accuracy was 0.9825 (112 of 114 correct). With only 114 test samples, one sample is about 0.9 percentage points, so small differences between settings are not meaningful.

Common mistakes

Preprocessing outside the Pipeline. This is the leak:

# WRONG: the scaler sees every row, including the folds used for validation
X_scaled = StandardScaler().fit_transform(X_train)
GridSearchCV(SVC(), param_grid, cv=5).fit(X_scaled, y_train)

Each validation fold’s statistics have already shaped the scaling. The Pipeline version above avoids this.

Scoring choice. Without scoring, GridSearchCV uses the estimator’s default (accuracy for classifiers). Accuracy is fine for this lightly imbalanced dataset. If one class is rare or errors have unequal costs, choose deliberately: "f1", "roc_auc", "recall", or others from scikit-learn’s scoring list.

Too-coarse, then too-fine, grids. Grids spaced in powers of ten find the right region but not the best point. Going straight to a fine grid over a wide range wastes fits. Search coarse first, then zoom in. Here is that second step, narrowed around the first winner (C=10, gamma=0.01):

fine_grid = {
    "svc__C": [3, 5, 10, 20, 30],
    "svc__gamma": [0.005, 0.01, 0.02, 0.03, 0.05],
}
fine = GridSearchCV(pipe, fine_grid, cv=5, scoring="accuracy").fit(X_train, y_train)
print(fine.best_params_, round(fine.best_score_, 4))

This is 25 combinations × 5 folds = 125 fits (0.98 s in this run). The result: the same winner, C=10, gamma=0.01, with the same CV accuracy of 0.9802. Neighbours scored 0.9780 (C=5, C=30 and gamma=0.005 at the other parameter’s winning value). That is useful information: the coarse grid already found a plateau, and further zooming would be tuning noise. If the zoom had moved the winner, you would repeat once more around it. Keep the test set out of this loop: evaluate on it once, with the final model.

When grid search is the right tool

Three-row decision list: few parameters and fast fits map to GridSearchCV, more parameters or an unknown space to RandomizedSearchCV, expensive fits on a tight time budget to Optuna TPE.
Start with the cheapest search that fits the problem; the full tree with dataset size, fit cost and pruning is in the Optuna comparison.

Grid search fits when:

  • you have two or three hyperparameters with a handful of sensible values each;
  • fits are cheap, as here, or you have the compute to spare;
  • you want a complete, reproducible map of the search space, like the table above.

Move on when the grid explodes. RandomizedSearchCV samples a fixed number of combinations from ranges or distributions, so your budget no longer grows with every parameter you add. For larger spaces, expensive fits, or a fixed time budget, a smarter sequential search such as Optuna usually finds good settings in fewer trials. We time all three on the same dataset in Optuna vs GridSearchCV, and an Optuna tutorial walks through the library step by step.

How many hyperparameters? ── 1-3, cheap fits ──────────► GridSearchCV
        │
        ├─ 4+ or wide ranges ──────────────────────────► RandomizedSearchCV
        │
        └─ expensive fits / strict time budget ─────────► Optuna

GridSearchCV remains the best place to start, because the results table makes the search space easy to understand. Once you have that understanding, the alternatives are easier to choose between.

FAQ

What does cv=5 mean in GridSearchCV?

The training data is split into 5 folds. The model trains on 4 and is scored on the 5th, five times over, and the 5 scores are averaged. This multiplies your fit count by 5.

Does GridSearchCV use the test set?

No. It only sees the data you pass to fit(). Pass it your training split and keep the test set for one final evaluation.

What is refit=True for?

After the search, GridSearchCV retrains the best combination on the whole training set and exposes it as best_estimator_, so you can call predict() on the search object directly.

Why do I need a Pipeline?

So preprocessing like scaling is fitted only on each fold’s training portion. Scaling the data before the search leaks information from the validation folds into training.

How do I reduce GridSearchCV’s runtime?

Shrink the grid, lower cv (for example 3), use n_jobs=-1, or switch to RandomizedSearchCV. Estimate with combinations × folds × seconds per fit before launching.

Is best_score_ my model’s real accuracy?

No. It is the mean validation score of the winning combination, which was selected because it scored highest. Use the untouched test set for the honest estimate.

Scroll to Top