Sub topic 9
Random search
This chapter assumes you know how to train a scikit-learn model, how cross-validation works, and how grid search enumerates a fixed list of settings.
The idea
Random search draws each trial's hyperparameter values at random from distributions you define. You fix the number of trials, called the budget, and the search stops when it is spent. Grid search covers every combination of a few chosen values. Random search covers the space with a set of points that are not tied to a lattice.
Why it often beats grid search
Usually only a few hyperparameters strongly affect the score. Suppose a grid has 3 values for each of 2 parameters. That is 9 trials, but only 3 distinct values of each parameter. Nine random draws give 9 distinct values of each. If one parameter matters much more than the other, random search tests it at more levels for the same cost.
Running it in scikit-learn
RandomizedSearchCV takes distributions instead of lists. For values that span several orders of magnitude, such as C and gamma, use loguniform so each order of magnitude is equally likely.
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_)Key arguments:
n_iteris the number of sampled settings. Total fits aren_iter × cv.random_statemakes the sampled settings repeatable.n_jobs=-1runs fits in parallel on all cores.
The search is fit on the training split only. Keep the test set for one final score, for example search.score(X_test, y_test).
Choosing distributions
| Hyperparameter type | Typical distribution |
|---|---|
| Learning rate, `C`, `gamma`, regularization strength | `loguniform` |
| Integer count such as `max_depth` | `randint` |
| Fraction between 0 and 1 | `uniform` |
| Categorical choice | a plain list, sampled uniformly |
A list given to RandomizedSearchCV is sampled uniformly. If every parameter is a list, scikit-learn samples without replacement and caps n_iter at the grid size.
Common errors
- Linear scale for a log-scale parameter.
uniform(0.0001, 100)puts almost all draws above 1. Useloguniform. - Too few trials. With 30 draws, the best setting is probably good but not the optimum. Treat results as a good region, not an exact answer.
- Ranges that are too narrow or too wide. If the best value sits at a range edge, extend that range and rerun.
- Skipping the pipeline. Scaling outside the pipeline leaks validation data into training. Put preprocessing inside the pipeline, as above.
- Trusting
best_score_as a final estimate. It is the maximum over many noisy trials, so it is optimistic. Use the held-out test set or nested cross-validation.
Exercise
A grid search with 4 values for each of 3 hyperparameters and 5-fold cross-validation takes too long. You switch to random search with n_iter=20. How many model fits does each approach run, and why might random search still find a similarly good setting?
Show answer
Grid search runs 4 × 4 × 4 × 5 = 320 fits. Random search runs 20 × 5 = 100 fits. Random search tests 20 distinct values of every hyperparameter instead of 4, so if only one or two parameters matter, it explores them more finely and often reaches a comparable score.