Sub topic 9
Random search
Random search tunes hyperparameters by drawing settings at random from a search space you define, scoring each draw with cross-validation, and keeping the best. This chapter assumes you can use scikit-learn pipelines and cross_val_score, and that you know what a search space and grid search are from the earlier chapters.
Why random sampling works
Grid search tests every combination of a fixed list of values. The cost multiplies with each hyperparameter you add. Three values for each of five hyperparameters is already 243 fits per cross-validation fold.
Grid search also wastes trials on hyperparameters that barely matter. Suppose only C affects the score and gamma is irrelevant. A 3 by 3 grid tests only three distinct values of C, each repeated three times. Nine random draws give nine distinct values of C, so you explore the important dimension more finely for the same cost.
This is the main argument for random search. In most problems a few hyperparameters dominate the score, and you don't know which ones in advance. Random sampling covers every dimension densely whichever ones turn out to matter.
Budget and the chance of a good result
You choose the number of trials, n_iter, directly. This makes planning easy. Say the best 5% of the space contains settings you'd be happy with. Each independent draw lands there with probability 0.05. After n draws, the chance that at least one does is 1 - 0.95^n.
| Trials (n) | Chance of at least one draw in the top 5% |
|---|---|
| 10 | about 40% |
| 30 | about 78% |
| 60 | about 95% |
| 100 | about 99.4% |
This holds whatever the number of hyperparameters. Grid search has no equivalent guarantee, because its cost grows with every dimension. The table does not say the top 5% is good enough. It only says you'll probably find something at least that good in the space you defined. If the space is badly chosen, 60 trials won't rescue it.
Running it with scikit-learn
RandomizedSearchCV takes a dictionary that maps each hyperparameter name to a distribution or a list. The pipeline prefixes (svc__C) are the same as in grid search.
from scipy.stats import loguniform
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, RandomizedSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0, stratify=y
)
pipe = make_pipeline(StandardScaler(), SVC())
param_distributions = {
"svc__C": loguniform(1e-2, 1e2),
"svc__gamma": loguniform(1e-4, 1e0),
}
search = RandomizedSearchCV(
pipe, param_distributions, n_iter=30, cv=5, random_state=0, n_jobs=-1
)
search.fit(X_train, y_train)
print(search.best_params_, search.best_score_)The search draws 30 settings, runs 5-fold cross-validation for each (150 fits), then refits the best setting on the whole training set. best_score_ is the mean cross-validated score of that setting. Because it was chosen as the maximum over 30 noisy estimates, it is slightly optimistic. Report the held-out test score, computed once with search.score(X_test, y_test), as your performance estimate.
Choosing distributions
Sampling is only as good as the distributions you give it. Each value in param_distributions can be one of three things.
- A list. Scikit-learn picks one element uniformly. Use it for categorical choices such as
["linear", "rbf"]. - A frozen
scipy.statsdistribution. Any object with anrvsmethod works. Useloguniformfor scale parameters,uniformfor bounded floats, andrandintfor integers. - A list of dictionaries. Use it for conditional spaces, where some hyperparameters only apply to certain choices. For example,
gammais meaningless for a linear kernel.
Match the scale to how the hyperparameter behaves. C and gamma change the model by factors, so the gap between 0.01 and 0.1 matters as much as the gap between 10 and 100. A uniform draw over 0.01 to 100 would put 90% of samples above 10. A log-uniform draw gives each decade the same share.
Two gotchas catch people regularly:
scipy.stats.uniform(loc, scale)coversloctoloc + scale, notloctoscale.uniform(0.5, 0.5)samples between 0.5 and 1.0.randint(low, high)excludeshigh.randint(2, 17)gives integers 2 to 16.
Reading the trials
The summary attributes show the winner. The full table shows how sensitive the score is to each setting, which tells you whether to widen or narrow the space. This example builds on the search above.
import numpy as np
results = search.cv_results_
order = np.argsort(results["rank_test_score"])[:5]
for i in order:
print(
f"rank {results['rank_test_score'][i]:>2} "
f"mean={results['mean_test_score'][i]:.4f} "
f"std={results['std_test_score'][i]:.4f} "
f"{results['params'][i]}"
)Look at two things. First, whether the top trials are close in score. If the top five differ by less than the fold-to-fold standard deviation, they are statistically indistinguishable, and you can pick the simpler or cheaper one. Second, whether the best values sit at the edge of your ranges. A best C near 100 when your upper bound is 100 means the true optimum may lie outside the space.
Making the run reproducible
random_state on RandomizedSearchCV fixes which settings are drawn. The same seed with the same ranges gives the same 30 candidates. It does not fix randomness inside the model. For estimators such as random forests, set their own random_state inside the pipeline. The cross-validation splitter is deterministic when cv is an integer and the estimator is a classifier, since scikit-learn uses unshuffled stratified folds. If you pass a shuffling splitter, seed that too.
Record the seed, n_iter, the distributions, the scoring metric, and the library versions with your results.
Refining a search
A common workflow uses two rounds. The first is a wide, coarse random search with perhaps 50 to 100 trials. You then inspect cv_results_, shrink each range around the promising region, and run a second, narrower search. This costs far less than a fine grid over the whole space. Later chapters cover methods that automate this idea by letting earlier trials guide later ones.
When to prefer random search
Random search is usually the better default when you have three or more hyperparameters, when some are continuous, or when you have a fixed time budget. Grid search is reasonable for one or two hyperparameters with a few meaningful discrete values, where you want to see the whole surface. Random search has one real weakness. It ignores what earlier trials learned, so it can keep sampling regions that have already proven poor.
Exercise
A colleague tunes learning_rate with uniform(0.0001, 0.1) in RandomizedSearchCV, runs 40 trials, and finds that nearly all sampled values are above 0.01. What is the problem, what distribution would you use instead, and what range does the original call actually cover?
Show answer
uniform(loc, scale) samples from loc to loc + scale, so the original call covers 0.0001 to 0.1001. On a linear scale, about 90% of draws exceed 0.01, so the small learning rates that often work best are barely explored. Use loguniform(1e-4, 1e-1), which gives each decade (1e-4 to 1e-3, 1e-3 to 1e-2, 1e-2 to 1e-1) an equal share of draws.
Exercise
Using 1 - (1 - p)^n, about how many random trials do you need for a 90% chance of at least one draw in the best 2% of the space?
Show answer
Solve 1 - 0.98^n >= 0.90, so 0.98^n <= 0.10. Then n >= ln(0.10) / ln(0.98), which is about 114 trials.