Understanding Grid Search
A simple grid search uses nested for loops to try every combination of the candidate parameter values, training and evaluating a classifier for each one.
A Search That Trains Many Models
A classifier such as an SVC has settings that you choose before training begins. Two of them, gamma and C, strongly affect how well the model performs on data it has not seen. Choosing good values for these settings is called parameter tuning. This article looks at one of the simplest ways to do it, called grid search, and at the small program that implements it with nothing more than nested for loops.
What do you think happens?
Suppose the grid has 6 candidate gamma values and 6 candidate C values. How many classifier models does the search train?
Reveal answer
36
Each model uses one gamma value and one C value together, so the number of models is the number of pairs: 6 times 6, which is 36. The search does not train one model per value; it trains one model per pair.
What a Grid Search Is Doing
A simple grid search works in three moves. First, you define a set of candidate values for each parameter. Second, you try every combination of those values. Third, for each combination you train and evaluate a classifier and keep the combination that produces the best score. The search never looks at a combination that was not on the grid, and it never adjusts the grid while it runs.
The idea is easy to state, but it is easy to lose track of what happens during the search. The source notes that the program makes a single pass over the combinations and prints only the winner. It does not print a table of every score. This means that the count of models trained, and the order in which they were trained, are not shown in the output. You have to reason about them from the code structure, which is the skill this article builds.
Following the Two Nested Loops
The outer loop assigns each gamma value in turn. For every gamma, the inner loop walks through every C value. The inner body therefore runs once for each pair, and every pair is complete: each model uses one gamma and one C together. The source writes the loop headers as a grid of two lists, one for gamma and one for C, which is why the search is described as a grid.
Tracing the first iterations
Starting from the first pair, trace which combinations are tried, in what order, for the first two C values and the start of the second gamma value.
- 1Pair with gamma 0.001 and C 0.001
The outer loop has assigned the first gamma value, 0.001. The inner loop assigns the first C value, 0.001. The classifier is built with these two values, trained, and scored.
- 2Pair with gamma 0.001 and C 0.01
The gamma value stays at 0.001. The inner loop moves to the next C value, 0.01, and the same three steps run again with a new classifier.
- 3Remaining C values for gamma 0.001
The inner loop keeps moving through the C values until all six have been tried with gamma 0.001. Only then does control return to the outer loop.
- 4Start of gamma 0.01
The outer loop advances gamma to 0.01. The inner loop starts again from the first C value, 0.001, so the pair is gamma 0.01 and C 0.001.
Each gamma value is paired with every C value before the next gamma is used. The inner loop changes C fastest, so C is the value that varies most often.
The Grid as a Tree of Combinations
It helps to picture the parameter grid as a tree. The root represents the whole search. Each gamma value is a branch leading off the root. Under each gamma branch, every C value becomes a leaf. Each leaf is one complete pair, and each leaf corresponds to one trained model. Counting the leaves gives the total number of models.
Each Combination: Build, Train, Score
Every pass through the inner body does the same three things, and each has a specific job. The SVC constructor takes the current gamma and C, so the classifier is rebuilt for every pair rather than reused from an earlier pair. The fit call trains that classifier on the training data. The score call measures how well the trained classifier does on the test data and returns one number. Then the program compares that number with the best score seen so far. Three steps, one combination.
- The two for lines control iteration: the outer loop picks gamma, the inner loop picks C.
- The SVC line builds a fresh classifier for each pair.
- The fit line trains that classifier on the training data.
- The score line evaluates the trained classifier on the test data and returns one number.
- The if line and the two assignments under it are the bookkeeping that tracks the winner.
Common mistake The line that trains the model is the one that builds the classifier and calls fit, and the score line is what turns a trained model into a single number. The bookkeeping lines do not change how the model is trained or scored.
How best_score and best_parameters Evolve
The search carries its memory in two variables. The variable best_score begins at 0. After each evaluation, the program compares the new score with best_score using a strict greater-than test. Only when the new score is larger does the program overwrite best_score and build the best_parameters dictionary, which records the C and gamma values that produced it. Every other combination leaves both variables untouched.
Reading the Printed Result
The output contains four lines. The first two come from the data split performed before the loops start. The training set has 112 samples and the test set has 38. Those two numbers add up to 150, the number of samples in the iris dataset, which shows that the split is a complete partition of the data with no sample left out. The last two lines come from the search: the best score, printed with two decimal places, and the best parameters, printed as a dictionary with C and gamma as keys.
The printed winner is the final state of best_score and best_parameters after the last combination has been tried. In this run the winning C is the largest value in the grid and the winning gamma is the smallest. The output reports that fact without explaining it. Whether the best setting sits at an edge of the grid cannot be judged from this output, because the scores for the other combinations are never printed.
Mistakes Beginners Make with Grid Search
Common mistake Assuming the program prints a score for every combination
Why it failsThe program makes a single pass and prints only the winner, along with the training and test set sizes.
Do this insteadTo see other scores, you would need to change the program to record them. The output alone does not show how many models were trained.
Common mistake Believing the classifier is reused across pairs
Why it failsThe SVC constructor takes the current gamma and C, so a new classifier is built for each pair.
Do this insteadTrace each inner iteration as building a fresh model, training it, and scoring it.
Common mistake Expecting a tied score to replace the stored best
Why it failsThe comparison is strictly greater-than, so a tie does not overwrite
best_scoreorbest_parameters.Do this insteadThe first pair to reach the top score is the one kept.
Common mistake Counting models as the sum of the list lengths
Why it failsEach model needs one gamma and one C together, so the count is the product of the two list lengths.
Do this insteadWith 6 gamma values and 6 C values, count 6 times 6, which is 36 models.
Trace a Search by Hand
Suppose a grid has 3 gamma values and 4 C values. Without running anything, work out how many models the search trains. Then list the first three pairs in the order the nested loops visit them, and state which variable changes most often.
Hints
- Each model uses one gamma and one C together, so count pairs.
- The inner loop changes C fastest, so the first pairs keep the first gamma value while C advances.
- The count is the product of the two list lengths: 3 times 4.
Key Takeaways
- A simple grid search uses nested for loops to try every combination of the candidate parameter values, training and evaluating a classifier for each one.
- The outer loop picks each gamma value and the inner loop walks every C value, so the number of models is the product of the list lengths: 6 times 6 gives 36.
- Each pass builds a fresh SVC with the current gamma and C, fits it on the training data, and scores it on the test data.
best_scorestarts at 0 and is overwritten only on a strictly greater score, which also setsbest_parameters; ties keep the earlier pair.- When a result looks wrong, check the loop nesting, the position of the comparison, and the initial values of the tracking variables.