Grid and random search
Quick answer
Hyperparameters control how a model learns rather than being learned from the training rows. Grid search enumerates a finite list of configurations; randomized search samples a fixed number from a search space. Compare candidates on the same development folds using a fixed scoring rule. Static examples tested locally with Python 3.13.5, scikit-learn 1.8.0 SciPy 1.17.0 and NumPy 2.3.5 where imported. ByteMind package execution is unverified.
Count a conditional grid
from sklearn.model_selection import ParameterGridspace=[{"kernel":["linear"],"C":[1,10]},{"kernel":["rbf"],"C":[1,10],"gamma":[0.1,1]}]n=len(ParameterGrid(space))print(n,3*n+1)Observed local output:
6 19The branches contribute two and four candidates; each is fitted three times.
How it works
A grid with 3 C values and 4 gamma values contains 12 combinations. With 3 folds it requires 36 fits plus one optional refit. A grid is useful when the space is small and meaningful; a random search can spend the same budget exploring more distinct values of influential dimensions. Sample positive scale parameters such as C on a logarithmic scale when orders of magnitude matter. Use conditional spaces (a list of dictionaries) to avoid irrelevant settings: gamma matters for RBF but not linear SVC. RandomizedSearchCV samples without replacement when all values are lists, and with replacement when at least one distribution is supplied. Set random_state, share explicit splits, specify scoring and keep scaling inside a Pipeline. The best validation score is optimistic when many candidates are tried; reserve a final holdout or use nested CV. Equal trial counts control the number of fits, not necessarily wall-clock time, memory or model complexity.
Compare equal candidate counts
import numpy as npfrom sklearn.model_selection import GridSearchCV,RandomizedSearchCV,StratifiedKFoldfrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import StandardScalerfrom sklearn.svm import SVCX=np.arange(24).reshape(-1,1);y=np.array([0]*12+[1]*12)p=make_pipeline(StandardScaler(),SVC(kernel="linear"));folds=list(StratifiedKFold(3,shuffle=True,random_state=7).split(X,y))g=GridSearchCV(p,{"svc__C":[0.1,1,10]},cv=folds).fit(X,y)r=RandomizedSearchCV(p,{"svc__C":[0.01,0.1,1,10,100]},n_iter=3,random_state=7,cv=folds).fit(X,y)print(len(g.cv_results_["params"]),len(r.cv_results_["params"]))Observed local output:
3 3Both searches use nine fold fits; the spaces differ, so this is not a universal method ranking.
Common mistakes
Do not count individual parameter values instead of combinations, search test labels, or compare 100 random candidates against four grid candidates as a fair equal-budget comparison. Record the complete sampled candidates, not only the winner.
Practice and next steps
Construct two conditional spaces for linear and RBF SVC. Count the combinations and three-fold fit budget, including the final refit. Complete the knowledge check and staged exercise. Next: Bayesian search intuition.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Grid and random search — knowledge check
Apply grid and random search to new scenarios.
What does a grid enumerate?
Why use log-scale sampling for C?
Which is a conditional setting?
What does equal trial count guarantee?
Where should scaling be fitted?