Concepts / Grid Search

Grid Search

Grid search is a method for tuning model parameters that tries every combination of the parameter values of interest.

  • Programming

Predicting How Many Settings a Search Will Try

Once you can measure how well a model generalizes to unseen data, the next question is how to make it generalize better. One lever is the model's parameters. Many learning algorithms expose settings that change how the model behaves, and the values you choose for the important ones can decide whether the model performs well or poorly on new data. This article follows one tuning method, grid search, and works through what it does, how its parameter grid is written, and how to find the cause when a search does not behave as expected.

What do you think happens?

Suppose a grid gives six candidate values for svm__C and six candidate values for svm__gamma. How many combinations will grid search evaluate?

  • 6

  • 12

  • 36

  • 64

Reveal answer
Answer:

36

Every value of one parameter is paired with every value of the other, so 6 times 6 gives 36 cells in the grid. Adding a parameter multiplies the count rather than adding to it.

What Grid Search Does and Why It Exists

Definition

Grid search is a method for tuning model parameters that tries every combination of the parameter values of interest.

Finding good parameter values is difficult. You need to know what each parameter controls before adjusting it, and you usually cannot guess the best setting in advance. Still, this kind of search is required for almost every model and dataset, which is why it is treated as a routine task with standard tools. The most widely used of these standard approaches is grid search.

The name comes from the way the search is organized. You pick a set of candidate values for each parameter. Those candidate sets are then combined so that every value of one parameter is paired with every value of the others. The resulting collection of pairings forms a grid, where each cell is one complete parameter setting to be tested. Grid search does not try to be clever about which cells to skip. It visits all of them.

Because the method tests every combination, its cost grows quickly. Each added parameter multiplies the number of settings, so a grid with several parameters and several candidate values per parameter can contain many cells. The method is most useful when you have a small number of parameters that you already believe matter.

Counting the Combinations for Two Parameters

Consider a kernel SVM with an RBF (radial basis function) kernel, the form implemented in the SVC class. This model has two important parameters: the kernel bandwidth, called gamma, and the regularization parameter, called C. Both control how the model fits the training data, so both are candidates for tuning.

Worked example

Counting the grid for C and gamma

Test the values 0.001, 0.01, 0.1, 1, 10, and 100 for C, and the same six values for gamma. How many combinations does the grid contain?

  1. 1
    Count the candidates for each parameter

    C has six candidate values, and gamma has six candidate values.

  2. 2
    Pair every C value with every gamma value

    Each of the six C values is paired with each of the six gamma values, so there is one cell for each pair.

  3. 3
    Multiply the two counts

    $6 \times 6 = 36$ combinations, so grid search evaluates 36 parameter settings.

Result

The grid holds 36 combinations. If gamma runs down the rows and C runs across the columns, the 36 cells form the table of parameter settings that gives the method its name.

The same counting can be done in Python. The itertools.product function produces every pairing of two lists, which is exactly the set of cells in the grid. The sketch below uses two short lists so the output is easy to read. It illustrates the idea and is not a full tuning procedure.

python
Output (expected)
4
[(1, 0.1), (1, 1), (10, 0.1), (10, 1)]
Notes on the code
  • product pairs every item of the first list with every item of the second list
  • Two candidates for C and two for gamma give four cells, matching 2 times 2
C 0.1, gamma 0.01C 1, gamma 0.01C 10, gamma 0.01C 0.1, gamma 0.1C 1, gamma 0.1C 10, gamma 0.1C 0.1, gamma 1C 1, gamma 1C 10, gamma 1C 0.1, gamma 10C 1, gamma 10C 10, gamma 10
If C has 3 candidate values and gamma has 4, each cell pairs one C value with one gamma value, giving 12 cells in total.

Reading a Grid Key Left to Right

Once a model sits inside a pipeline, its parameters are reached through the pipeline, so the grid has to say which step each parameter belongs to. A pipeline is a sequence of named steps, and each step can hold an estimator that has its own parameters. The rule is to write the step name, then two underscore characters, then the parameter name, all inside one string.

Read the key 'svm__C' from left to right. The part before the double underscore names the step, which is svm. The part after it names the parameter, which is C. The double underscore is the boundary between the two. It is a required separator, and a single underscore would not be read the same way.

svmpipeline step name__double underscore separatorCparameter nameboundaryboundary
The key is read left to right: the text before the double underscore names the pipeline step, and the text after it names the parameter inside that step's estimator.

Writing the Grid Dictionary for a Pipeline

The grid is an ordinary Python dictionary. Each key is a pipeline-qualified parameter name, and each value is the list of candidate values the search should try for that parameter. The example below builds a small pipeline with a scaler as its first step and an SVC as its second step, which is named svm. The pipe object and the training and test splits are assumed to exist already in the session.

python
Notes on the code
  • Each key is a step name, a double underscore, and a parameter name
  • Each value is the list of candidate values for that parameter
  • GridSearchCV receives the pipeline as its first argument and the grid as the parameter grid

The call to GridSearchCV looks the same as it would for a single estimator. The pipeline is passed in as the first argument, and the grid is passed as the parameter grid. The only difference lies in how the grid's keys are written. Reusing the same search pattern with a pipeline therefore needs no new function or special class.

Tracing a Key to the Estimator It Reaches

A plain estimator exposes parameters such as C directly. Inside a pipeline the same parameter is reached through the step that holds it. The before and after versions below show the same parameter written two ways. Only the key changes, so the difference is entirely in how the search routes the value.

Before
param_grid = {
    'C': [0.1, 1, 10]
}

The bare key C does not name a step, so the value will not reach the SVC in the svm step.

After
param_grid = {
    'svm__C': [0.1, 1, 10]
}

The key svm__C names the svm step and the parameter C, so each candidate reaches the SVC estimator.

svm__Csvm stepSVC estimatorC parameternames stepholdsreceives value
The key names a step in the pipeline, and the step holds the estimator whose parameter receives the candidate value.

Finding the Cause of a Misbehaving Search

When a grid search does not behave as expected, the most useful first check is the keys of the grid. A key that does not match a step name followed by a double underscore and a real parameter name will not reach the estimator it was meant for. The flowchart below turns that check into a sequence of questions you can follow in order.

Search misbehavesKey has doubleunderscore?Add or fix the doubleunderscoreCorrect the step nameCorrect the parameternameStep name matchespipeline?Parameter exists onthat estimator?Keys look correctstartnoyesnoyesnoyes
Check the keys in order: the separator first, then the step name, then the parameter name. The first failing check identifies the cause.

Mistakes in Grid Keys

  • Common mistake

    Using a single underscore instead of a double underscore

    What it looks like
    'svm_C'
    Why it fails

    The double underscore is the required separator between the step name and the parameter name. A single underscore is not read the same way, so the value does not reach the intended estimator.

    Do this instead
    'svm__C'
  • Common mistake

    Using the bare parameter name without the step name

    What it looks like
    'C'
    Why it fails

    Once the estimator sits inside a pipeline, its parameters are reached through the pipeline, so the key must say which step holds the parameter.

    Do this instead
    'svm__C'
  • Common mistake

    Misspelling the step name

    What it looks like

    'svn__C' when the step is named svm

    Why it fails

    The key must match a step that actually exists in the pipeline. A misspelled step name stops the value from reaching the estimator.

    Do this instead
    'svm__C'
  • Common mistake

    Forgetting that every combination is tried

    What it looks like

    Adding a third parameter with six values and expecting the count to stay at 36

    Why it fails

    Each added parameter multiplies the number of settings. Six values for three parameters give 216 combinations, not 36 plus a few more.

    Do this instead

    Multiply the candidate counts together before running the search

KeyStep name presentDouble underscore presentReaches the SVC?
svm__CYes, svmYesYes
svm_CNo separate stepNoNo
CNoNoNo
svn__CNo, misspelledYesNo
__CNo step nameYesNo

Comparing correct and incorrect keys for a pipeline whose SVC is in the step named svm

Practicing Key Reading and Grid Counting

EASY

A pipeline has a step named rf that holds a random forest. You want to search over two parameters: rf__max_depth with 4 candidate values and rf__min_samples_leaf with 3 candidate values. Write the parameter grid dictionary for this search, identify the step name and parameter name in each key, and state how many combinations grid search will try.

Hints
  • Each key has three pieces: the step name, the double underscore, and the parameter name.
  • Count the candidate values for each key, then multiply the two counts.
  • Check that both keys begin with the step name rf, not a bare parameter name.

Key Takeaways

  • Grid search is a method for tuning model parameters that tries every combination of the candidate values of interest.
  • Inside a pipeline, each grid key has the form step name, double underscore, parameter name, such as 'svm__C'.
  • The number of combinations is the product of the candidate counts, so 6 values for C and 6 for gamma give 36 combinations.
  • When a search misbehaves, check the keys first for a missing double underscore, a bare parameter name, or a misspelled step name.

Related concepts

More concepts starting with G