Hey friends! Your pipeline runs. Now comes a tempting question: what happens if you change every setting until the score looks amazing? Before we touch those knobs, let’s give each experiment a fair test. In this GridSearchCV tutorial, you will compare eight configurations, spot a misleading score, and explain your decision before opening the final test set.
This is the next step after our Pipeline and ColumnTransformer guide. You only need basic Python and a train/test split. Open a blank Google Colab notebook and run the four code blocks in order. The example uses a built-in dataset, so no CSV download is needed.
What is GridSearchCV?
GridSearchCV tries every combination in a parameter grid, evaluates each using cross-validation, and can refit the best combination on all the training data. A hyperparameter is a setting you choose before fitting, such as the number of neighbors in a KNN classifier.
Here is the important distinction: cross-validation helps you choose a configuration; the held-out test set evaluates the choice after you have finished choosing. Searching repeatedly against the test set turns it into another validation set.
Step 1: reserve the test set
We will classify three wine cultivars using chemical measurements from scikit-learn’s small Wine dataset. This is a teaching exercise, not evidence that the same approach will work on a production dataset. Each row is treated as an independent observation.
import numpy as np
import pandas as pd
import sklearn
from sklearn.datasets import load_wine
from sklearn.model_selection import (
train_test_split, StratifiedKFold, GridSearchCV,
cross_val_score, ParameterGrid
)
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.dummy import DummyClassifier
print("scikit-learn:", sklearn.__version__)
X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
print("Training rows:", len(X_train)) # 133
print("Reserved test rows:", len(X_test)) # 45
StratifiedKFold approximately preserves class proportions in each fold. In five-fold CV, each candidate is trained five times: four folds for fitting and the remaining fold for validation, rotating which fold is held out. The 45 reserved test rows never enter this loop.
Before running further: write down which you expect to work better: three neighbors or fifteen. Do you expect a smaller neighborhood to react more strongly to individual observations? A prediction gives you something specific to learn from, even when it is wrong.
Step 2: choose a metric and build a baseline
We choose balanced accuracy before searching. It averages recall across the three classes, giving each class equal weight. Ordinary accuracy weights individual examples equally instead. Neither metric is universally correct: choose the one that matches your task, then keep it fixed during this comparison.
baseline_scores = cross_val_score(
DummyClassifier(strategy="most_frequent"),
X_train, y_train, cv=cv, scoring="balanced_accuracy"
)
print("Baseline CV:", baseline_scores.mean())
pipeline = Pipeline([
("scale", StandardScaler()),
("model", KNeighborsClassifier())
])
param_grid = {
"model__n_neighbors": [3, 5, 9, 15],
"model__weights": ["uniform", "distance"]
}
print("Candidates:", len(list(ParameterGrid(param_grid))))
The majority-class baseline should score about 0.333 in balanced accuracy. It predicts one class, so its recalls are 1, 0 and 0. This gives the tuned model a concrete reference point.
Our scaler belongs inside the pipeline. Every CV fit learns scaling statistics using only that fold’s training rows. Scaling all of X_train before running GridSearchCV would let the validation folds influence preprocessing. You would have protected the final test set but still contaminated model selection.
The double underscore in model__n_neighbors means “the n_neighbors parameter of the step named model.” Four neighbor counts multiplied by two weighting schemes produce eight candidates. Uniform weighting gives neighbors equal votes; distance weighting gives closer neighbors greater influence.
Keep a clear learning path
Want a structure for these experiments? Get the free 90-Day Machine Learning Roadmap and use this lab as a model-selection practice session. Finish the exercise below before collecting another tutorial.
Step 3: run the search and inspect the evidence
search = GridSearchCV(
estimator=pipeline,
param_grid=param_grid,
scoring="balanced_accuracy",
cv=cv,
refit=True,
return_train_score=True,
n_jobs=1,
error_score="raise"
)
search.fit(X_train, y_train)
results = pd.DataFrame(search.cv_results_)
columns = [
"param_model__n_neighbors", "param_model__weights",
"mean_train_score", "mean_test_score", "std_test_score",
"rank_test_score"
]
print(results[columns].sort_values("rank_test_score").to_string(index=False))
print("Selected:", search.best_params_)
print("Best CV score:", search.best_score_)
The name mean_test_score in cv_results_ is easy to misread. Here, “test” means the held-out validation fold inside cross-validation. It does not refer to X_test. The value is the mean of five validation scores.
mean_train_score shows performance on the fitting folds. A large gap between training and validation can be a sign of overfitting. std_test_score describes variation across these five folds; it is not automatically a confidence interval, and the folds’ training sets overlap.
With scikit-learn 1.8.0 and the fixed seeds above, this example selected three neighbors with uniform weights and achieved a mean CV balanced accuracy of approximately 0.981. These are reference results from this run, not a score target to chase. Versions and numerical details can affect results.
A tiny lead on a small dataset is weak evidence that one configuration will always beat another. GridSearchCV returns a winner under your scoring and selection rule; it does not prove that winner is uniquely best. If candidates tie, the default selection can depend on their grid order.
Your challenge: unlock the test set
Challenge 1 — count the work. How many model fits does the search need for eight candidates and five folds, including the final refit? Do not include the separate baseline calculation.
Challenge 2 — catch the leak. A friend suggests running StandardScaler().fit_transform(X_train) once and giving the scaled result to GridSearchCV. Explain what information would cross a fold boundary.
Challenge 3 — interpret the result. Is the winning mean_test_score the final test score? Write why it is or is not, then give one reason to be cautious about a small lead.
You may inspect the candidate table and change your predeclared search using training CV only. Decide when the search is finished before opening the test. For this lab, use the winner returned by search and record your reasoning.
# Pause here: complete these before opening the test result.
selection_reason = "" # Explain the CV evidence and one limitation.
fit_budget_answer = None # Count candidate-fold fits, plus refit.
READY_FOR_TEST = False
if READY_FOR_TEST:
assert len(selection_reason.strip()) >= 30, "Write your reasoning first."
assert fit_budget_answer == 41, "Recount the candidates, folds and refit."
test_score = search.score(X_test, y_test)
print(f"Final test balanced accuracy: {test_score:.3f}")
else:
print("Test stays closed. Finish the challenges, then set READY_FOR_TEST=True.")
Step 4: report the final result honestly
After you complete the challenges, write selection_reason, fill in fit_budget_answer, and set READY_FOR_TEST=True. In the tested run, the final test balanced accuracy was approximately 0.963. The test score can be lower than the winning CV score without anything being broken.
The selected configuration was already refitted on all 133 training rows because refit=True. Calling search.score uses that fitted model and the scoring metric specified above. Do not fit again on the test rows before measuring their performance.
If the test result disappoints you, report it. You can investigate and start a new development cycle, but repeated decisions based on this same test set make it less independent. Use a new untouched evaluation set when practical, or design nested cross-validation when you need to evaluate a tuning procedure without a separate fixed holdout.
Common GridSearchCV mistakes
Searching too many combinations. Adding settings multiplies the work. Our eight candidates require 40 CV fits, plus one refit. The baseline adds five more fits separately. Start with a small, reasoned grid; RandomizedSearchCV is useful when a larger search space makes exhaustive enumeration impractical.
Tuning a model outside its preprocessing pipeline. Put learned imputation, scaling and feature selection inside the searched estimator. A pipeline prevents this particular leakage route; it cannot repair a feature that contains future information.
Using random folds for every dataset. Repeated observations from the same person or account require a group-aware design. Forecasting requires chronological evaluation. A random stratified split is appropriate for this demonstration, not a universal template. Read When Cross-Validation Lies to You for more examples.
Treating tuning as a guaranteed improvement. A better grid cannot fix the wrong target, a misleading split or missing signal. Compare with a sensible default model and a baseline. Use learning curves when you need to investigate data quantity and model capacity.
Answers and explanations
1. The search needs 41 fits. Eight configurations × five folds = 40 fits. refit=True then fits the selected configuration once on all training rows. The baseline’s five fits are outside this count.
2. The scaler would see validation-fold statistics. Fitting it once on the full training partition includes the rows later held out for CV validation. Keeping it in the pipeline makes the mean and scale specific to each fold’s training subset.
3. mean_test_score is the mean CV validation score. The reserved X_test has not been used. The winning CV score was also used to select among candidates, so it is not an independent estimate of the search procedure’s performance. Small folds, close results and repeated experimentation are reasons to avoid strong claims.
Example reasoning: “I selected the highest mean balanced accuracy from the training-only search. I checked fold variation and the training/validation gap. The dataset is small, so I will not describe a narrow lead as conclusive.” Write your own explanation using the table you actually observed.
Turn this lab into a useful project
Save your metric, split strategy, grid, package version and reasoning alongside the result. A good project report explains what you tried and why a reader should trust the comparison. It does more than display the highest score.
For more structure, explore the Machine Learning Starter Kit. Or continue with our model evaluation guide to decide what else to measure after tuning.
Technical references
GridSearchCV API · Cross-validation guide. Code tested with scikit-learn 1.8.0.
Subscribe to our awesome newsletter to get the best content on your journey to learn Machine Learning, including some exclusive free goodies!


