Concepts / Cross-Validation Score

Cross-Validation Score

GridSearchCV tries combinations of hyperparameters with cross-validation and reports the best parameters, the best cross-validation score, and a score on held-out data.

  • Programming
Interactive lab

Try it: K-Fold Cross-Validation and Model Selection

How hold-out and k-fold cross-validation choose among candidate models: each fold takes a turn as the validation set, the fold errors are averaged, the lowest average picks the model, and only then is the untouched test set used once — while tuning on the test set would report an optimistic number.

How it works

  1. Set 10 test points aside; they take no part in any choice.
  2. Optionally shuffle the 20 development points (seeded), then cut them into k folds (hold-out: one chunk validates, the rest trains).
  3. For every round, train each candidate polynomial on the other folds and measure its validation MSE on the held-out fold.
  4. Average each candidate's fold errors (with repeated shuffling: average the p run scores; p × k fits per candidate).
  5. Select the candidate with the lowest average, retrain it on all development points, and evaluate it once on the test set.
  6. For contrast, show which candidate the test set itself would have picked — that figure is leaked and optimistic.

Default run (12 steps): 20 development points (sorted by x as they arrived) and 10 test points set aside. Candidates: polynomial degree 0, 1, 2, 3, 4, 5, 6. Plan: 5-fold cross-validation, shuffled with seed 1 → 5 fits per candidate (p × k = 1 × 5), 35 in total. … 5-fold cross-validation picks degree 3 (score 0.0768); its honest test MSE is 0.0889. Picking by test error would report degree 4 at 0.0868 — a leaked, optimistic figure.

Simplified: One fixed toy dataset (20 development + 10 test points from sin(2πx) with noise) and polynomial least squares of degree 0–6 as the candidate models. Shuffling uses a seeded mulberry32 Fisher–Yates; folds are contiguous chunks like scikit-learn's KFold. Hold-out uses the first of k chunks as the validation set.

Educational simulation

Loading the simulation…

Reading a Finished Search Run

Before you can judge a model, you have to know which version of it to judge. A grid search answers that question by trying several hyperparameter settings and keeping the one that scores best. In this article you will start from a finished search and work backward from its printed output. The search is fitted on the training portion of a breast cancer dataset, and then three numbers are reported. Each of those numbers comes from a different place, and knowing where each one comes from is the core skill this article builds.

The setup assumes that a pipeline object and a parameter grid already exist, and that the cancer dataset has been loaded. What matters for evaluation is the flow of data: the search is fitted on the training split, and the test split is kept back until the last step. Before reading further, decide for yourself which of the reported scores should be higher, and why. Think about which score comes from data the search used while choosing its settings, and which comes from data it never touched.

Three Numbers and Their Data Sources

A GridSearchCV run reports three things: the best parameters, the best cross-validation score, and a score on held-out data. The best cross-validation score is the attribute best_score_. It reports the average score of the winning combination across the folds that were used to select it. This is the number the search itself optimized, so it describes how the chosen settings performed on the data used to pick them.

The held-out score comes from a different call. The call grid.score(X_test, y_test) uses the test split, which was never passed to fit. No part of the search adjusted itself to that data. This is why the test-set score is the number that speaks to how the model is expected to behave on new data. In the run described by the source, the two values are close: 0.99 from cross-validation and 0.98 on the test set.

Training splitFive foldsFit on four, score ononeAveraged CV scorebest_score_Test splitheld back until the endbest_params_grid.score on X_testspliteach combinationaveragewinnerwinnerscored once
For one candidate setting, which rows of the data are used for fitting, which for validation, and which are kept aside for the final test score?

The diagram shows the direction of the flow. The training split feeds the search, the folds produce both the best settings and the cross-validation score, and the test split enters only at the very end. Keeping that direction in mind helps you locate the source of any surprising number.

Tracing How a Search Reaches Its Best Score

GridSearchCV performs cross-validation for every combination in the grid. For each combination, the training data is split into five folds. The model is trained on four of them and scored on the fifth, and the scores are averaged. This happens for every combination, and the combination with the highest average is the winner. The steps below follow that sequence in order, from one candidate setting to the final test score.

  1. 1
    Take one candidate setting from the parameter grid.
  2. 2
    Split the training data into five folds.
  3. 3
    Train on four folds and score on the fifth, repeating so each fold is the validation fold once.
  4. 4
    Average the five validation scores for that setting.
  5. 5
    Repeat for every setting in the grid and select the setting with the highest average.
  6. 6
    Report the winning average as best_score_ and its settings as best_params_.
  7. 7
    Score the fitted search on X_test and y_test to get the held-out score.

The best parameters are a dictionary, and the source describes its contents for one run. The chosen classifier is an SVC with kernel='rbf', and the chosen preprocessing step is StandardScaler. The two remaining entries are the hyperparameters the grid varied, C=10 and gamma=0.01. Each of these values is the outcome of the averaged fold scores described above, not of the test split.

Decoding Pipeline Parameter Names

The keys in best_params_ use a naming pattern that you will see often when a pipeline is involved. Two keys, classifier and preprocessing, hold the objects chosen for the pipeline steps. The other two keys, classifier__C and classifier__gamma, are the hyperparameters that the grid varied. A pipeline addresses a parameter inside one of its named steps by joining the step name and the parameter name with a double underscore.

classifiername of the pipeline step__separator into the stepgammahyperparameter of that stepstepparameter
In the name classifier__gamma, what does each part refer to, and which pipeline step does it configure?

Tracing an Unexpected Result

Suppose a colleague reports that a search gave a test-set score far below its cross-validation score. The useful question is not whether the search is broken, but at which step the numbers stopped agreeing. The checklist below follows the data flow in order, so each check narrows the problem to one step.

Worked example

Locating the source of a score gap

A search reports best_score_ of 0.99, but grid.score on the test split returns 0.70. Using the trace-the-flow checklist, find where the numbers may have stopped agreeing. These values are generated for illustration and are not from a real run.

  1. 1
    Check the split first

    Confirm that the test split was created before the search and was never passed into fit. If the test rows leaked into training, the held-out score would no longer be a fair test.

  2. 2
    Check the parameters

    Confirm that the settings being read come from best_params_ and not from the grid that was defined. The grid lists everything that was tried, while best_params_ holds the single winner.

  3. 3
    Check the scoring call

    Confirm that the score method was called with X_test and y_test. Calling it with training rows would inflate the number and hide the gap.

  4. 4
    Interpret the result

    If all three checks pass, the gap is a real finding about generalization rather than a bookkeeping error. The model did well on folds used for selection and less well on new data.

Result

The checklist moves from the split, to the parameters, to the scoring call. The step where the numbers stopped agreeing is the one that fails its check.

Heat Maps of Two-Parameter Grids

A grid search stores one row of results for each parameter setting it tried. Each row records the score from every cross-validation split, along with the mean and standard deviation across those splits. When the search covers two parameters, the natural picture is a heat map. One axis holds one parameter, the other axis holds the second parameter, and each cell is colored by its mean validation score. To draw it, you pull out the mean scores and reshape them into a rectangle whose rows and columns follow the two parameters.

The reshape step only works when the number of stored scores equals the number of cells in the grid. A 6 by 6 grid has 36 cells, so the flat list must contain exactly 36 values. Here is a small generated example with made-up numbers, not real model scores, that shows how a flat list becomes rows.

python
Output (expected)
[[1 2 3]
 [4 5 6]]
Notes on the code
  • reshape(2, 3) requires exactly 2 times 3 equals 6 values
  • Each row of the output corresponds to one value of the first parameter
  • Each column corresponds to one value of the second parameter
low gamma, low Cpoormid gamma, low Cfairhigh gamma, low Cpoorlow gamma, mid Cfairmid gamma, mid Cbesthigh gamma, mid Cfairlow gamma, high Cpoormid gamma, high Cfairhigh gamma, high Cpoor
Where on the two-parameter grid do the best and worst settings appear, and how do the rows and columns map to the parameter values?

The schematic above is generated for illustration. Each cell stands for one parameter setting, and its color stands for accuracy. Light cells mark high accuracy and dark cells mark low accuracy. Reading the picture means asking where the light cells are, where the dark cells are, and how those regions line up with the two axes. In the diagram, the best cell sits in the interior of the grid rather than on an edge.

What the Heat Map Shows About Parameter Strength

The source uses an SVC model to show how dramatic a heat map can be when parameters matter. In that plot, many settings of C and gamma produce accuracy around 40 percent, which is poor, while other settings reach around 96 percent. Moving between settings changes the result from very bad to very good. The message is that the two parameters strongly control performance.

The same plot supports two checks you should make on any heat map. First, do the ranges you chose actually change the outcome? Second, does the best region sit inside the grid, or does it touch an edge? The source notes that the optimum values in its plot were not on the edges, which suggests the search ranges were wide enough to capture the peak.

Flat Heat Maps: Narrow Ranges or Unimportant Parameters

A uniform heat map is the hardest picture to read, and the first reaction is often to throw the run away and start over with a different model. That reaction is usually premature. A uniform picture is a clue, and it points to a small set of specific causes that you can check one at a time. The source describes three heat maps produced from deliberately misspecified grids, each with a different color arrangement, and each arrangement points to a different diagnosis.

Colors nearlyuniformchange on both axes issmallWiden or rescale therangefirst checkColor constantalong one axisstripes or bandsOther parameterdrives changethe varying axis matterssuggestssuggests
How does a flat heat map look different when the search range is too narrow compared with when one parameter has little effect?

The two causes look different on the page. When the range is too narrow, the whole map tends to look similar, so the search has not explored a region where the score changes. When one parameter has little effect, the color varies along the other axis but stays constant along the axis holding the unimportant parameter. Naming the pattern is the first step toward deciding what to change. The source's comparison also reminds you that a uniform heat map is a prompt to investigate, not proof that the model has failed.

python
Notes on the code
  • The source's three panels loop over three different grids in this way
  • Only the spacing of the values differs between the grids, while the model and data stay the same
  • The mean scores are drawn on a shared color scale so the panels can be compared

Adjusting the Grid Without the Test Set

Adjusting the parameter grid after looking at cross-validation results is a legitimate and useful habit. The heat map guides those adjustments: it shows where accuracy changes, where it does not, and where the best region presses against the edge of the search. The adjustments should be made using cross-validation scores on the training data, which is where the heat map comes from. The test split stays untouched until the final score is computed.

Best region at anedge?Widen the range onthat sideCheck ranges,scaling, parameterimportanceMap flat overall?Refine the gridaround the peakyesnoyesno
Given what the heat map shows, such as a best region at a grid edge, a flat region, or a clear peak, what is the next step in refining the grid?

Common Mistakes When Reading Search Results

  • Common mistake

    Treating best_score_ as an unbiased estimate of new-data performance

    Why it fails

    best_score_ comes from the folds the search used to choose the winner, so it describes the selection data rather than data the search never touched.

    Do this instead

    Use the score from grid.score on X_test and y_test as the number that speaks to expected behavior on new data.

  • Common mistake

    Reading the parameters from the grid you defined rather than from best_params_

    Why it fails

    The grid lists every combination that was tried, while best_params_ holds only the single winner.

    Do this instead

    Read the chosen settings from best_params_ after the search has finished.

  • Common mistake

    Using a shortened name such as C for a pipeline parameter

    What it looks like

    Writing C instead of classifier__C

    Why it fails

    The pipeline addresses parameters through their full step-qualified names.

    Do this instead

    Use the full key, such as classifier__C, to refer to the C parameter of the classifier step.

  • Common mistake

    Discarding a flat heat map as proof that the model failed

    Why it fails

    A uniform picture can come from ranges that are too narrow or from a parameter with little effect.

    Do this instead

    Check the range and the scaling first, then look for whether one parameter drives the change.

  • Common mistake

    Adjusting the grid by looking at the test score

    Why it fails

    Using the final test set to choose settings lets the test data influence the search, so it no longer measures generalization.

    Do this instead

    Make grid adjustments from cross-validation scores on the training data only.

Practice Reading a Search Report

MEDIUM

A search report lists best_params_ with the keys classifier, preprocessing, classifier__C, and classifier__gamma. It also reports best_score_ and a test-set score from grid.score. Identify which key refers to a pipeline step, which two keys refer to hyperparameters, which score came from the folds used for selection, and which score came from data the search never touched. Then describe which step of the search would be the first place to check if the test score were far below best_score_.

Hints
  • Keys that contain a double underscore point into a named pipeline step.
  • best_score_ is computed from the averaged validation folds used during selection.
  • grid.score uses X_test and y_test, which were never passed to fit.
  • Follow the checklist in order: split first, then parameters, then the scoring call.

Key Takeaways

  • GridSearchCV tries combinations of hyperparameters with cross-validation and reports the best parameters, the best cross-validation score (best_score_), and a score on held-out test data.
  • best_score_ comes from the training folds used during the search, while grid.score on X_test measures performance on data the search never touched, so the test score is the one that speaks to new data.
  • Keys such as classifier__C and classifier__gamma refer to a hyperparameter inside a named pipeline step and must be read and set with their full names.
  • A two-parameter heat map of mean cross-validation scores shows where settings are best and worst; a flat map can come from narrow ranges or an unimportant parameter, and it is a prompt to investigate.
  • Adjust the grid using cross-validation results on the training data, widening ranges when the best region touches an edge, and keep the test split untouched until the final score.

Related concepts

More concepts starting with C