Sub topic 7
Defining a search space: ranges, types, and scales
This chapter assumes you can run GridSearchCV and RandomizedSearchCV and know what cross-validation does. It also assumes you know the common hyperparameters of an SVM, a random forest, and a gradient-boosted model. Here you will learn how to describe the set of values a tuner may try. A poorly defined space can make a search miss good settings however much compute you spend.
What a search space is
A search space is the set of hyperparameter combinations a tuner is allowed to evaluate. It has three parts for each hyperparameter:
- A type: continuous, integer, or categorical.
- A range: the lowest and highest values, or the list of allowed choices.
- A scale: how probability or grid points are spread across the range.
The tuner can only find what the space contains. If the best C is 500 and your range stops at 100, no search method will find it.
Types of hyperparameters
| Type | Examples | scikit-learn / SciPy | Optuna |
|---|---|---|---|
| Continuous | `C`, `gamma`, learning rate, `alpha` | `loguniform(a, b)`, `uniform(loc, scale)` | `suggest_float` |
| Integer | `max_depth`, `n_estimators`, `n_neighbors` | `randint(low, high)` | `suggest_int` |
| Categorical | `kernel`, `penalty`, `criterion` | a list of values | `suggest_categorical` |
| Conditional | `gamma`, which matters only when `kernel="rbf"` | a list of dicts | ordinary `if` in the objective |
Treat a boolean such as bootstrap as categorical with the choices [True, False]. Treat a number that is really a label as categorical too. For example, n_components in {2, 5, 10} is often best listed explicitly.
Choosing the scale
The scale decides where samples land. Many hyperparameters act on a multiplicative basis. Going from C=0.01 to C=0.1 changes the model about as much as going from 1 to 10. For those, use a log scale, which gives each power of ten equal probability.
A linear scale on a range such as 1e-4 to 1 puts 90% of samples between 0.1 and 1. The decades from 1e-4 to 1e-1 together receive 10%. The next script measures this.
import numpy as np
from scipy.stats import loguniform, uniform
samples_log = loguniform(1e-4, 1e0).rvs(size=10000, random_state=0)
samples_lin = uniform(loc=1e-4, scale=1.0 - 1e-4).rvs(size=10000, random_state=0)
for name, s in [("loguniform", samples_log), ("uniform", samples_lin)]:
decades = np.floor(np.log10(s)).astype(int)
counts = {int(d): int((decades == d).sum()) for d in range(-4, 0)}
print(name, counts)The log-uniform sampler puts about 2,500 samples in each decade. The linear sampler puts about 9,000 in the top decade (0.1 to 1) and only about 10 in the bottom one.
Use a log scale for these:
- Learning rates
- Regularization strengths (
C,alpha,lambda) gammafor RBF kernels- Tolerances
Use a linear scale for these:
- Quantities bounded in [0, 1] whose effect is roughly additive, such as
subsample,colsample_bytree, orl1_ratio - Integers spanning a narrow range, such as
max_depthfrom 2 to 16
Use a log scale for integers that span orders of magnitude, such as n_estimators from 10 to 1000. Optuna supports this with log=True on suggest_int. SciPy has no log-uniform integer. You can use loguniform and round, or list values by hand.
Actually the diagram goes below, in the next section's place. First, here is how to pick ranges.
Choosing ranges
Start wide, then narrow. A practical procedure:
- Take the library default as an anchor. Cover at least two orders of magnitude on each side for log-scale values.
- Use domain limits.
subsamplecannot exceed 1.max_depthbelow 1 is meaningless. - Run a cheap first search, such as random search with 30 to 50 trials.
- Look at where the best trials fall. If they cluster at one edge, extend the range in that direction. If they cluster in the middle, narrow the range around them and search again.
A best value on the boundary is a warning sign. It means the true optimum may lie outside your space.
Defining a space in scikit-learn
RandomizedSearchCV accepts either lists or SciPy distributions. Anything with an .rvs() method works as a distribution. GridSearchCV accepts lists only, so it forces you to pick grid points yourself. Spread them evenly in log space, for example np.logspace(-2, 2, 5).
Conditional spaces use a list of dictionaries. The sampler first picks one dictionary, then samples from it. This avoids wasting trials on gamma when the kernel is linear.
from scipy.stats import loguniform
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import RandomizedSearchCV, train_test_split
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__kernel": ["linear"],
"svc__C": loguniform(1e-2, 1e2),
},
{
"svc__kernel": ["rbf"],
"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_)
print(round(search.best_score_, 4))The names use the pipeline prefix svc__, so the scaler is refit inside each fold. The dictionary choice is uniform, so each kernel gets about half the trials.
After the search, check search.best_params_ against your bounds. If svc__C is within a few percent of 0.01 or 100 on a log scale, widen the range.
Defining a space in Optuna
Optuna builds the space inside the objective function. Each suggest_* call declares a type, range, and scale at the moment it runs. This makes conditional spaces natural, because an ordinary if decides which hyperparameters exist for a trial.
import optuna
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
optuna.logging.set_verbosity(optuna.logging.WARNING)
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
)
def objective(trial):
kernel = trial.suggest_categorical("kernel", ["linear", "rbf"])
C = trial.suggest_float("C", 1e-2, 1e2, log=True)
params = {"kernel": kernel, "C": C}
if kernel == "rbf":
params["gamma"] = trial.suggest_float("gamma", 1e-4, 1e0, log=True)
model = make_pipeline(StandardScaler(), SVC(**params))
return cross_val_score(model, X_train, y_train, cv=5).mean()
study = optuna.create_study(
direction="maximize",
sampler=optuna.samplers.TPESampler(seed=0),
)
study.optimize(objective, n_trials=30)
print(study.best_params, round(study.best_value, 4))Optuna fixes each parameter's range after its first use. A parameter name must keep the same range and type across trials of one study, so do not change a range inside the objective based on earlier results.
Common errors
- Linear scale for a log-scale value. Most samples land in the top decade, and small values are almost never tried.
- Grids that are too fine in the wrong place. Ten values of
max_depthbetween 10 and 20 cost ten times as much as one value, and they rarely help. - Ranges that hide the optimum. Check whether the best value sits at an edge.
- Ranges that mix invalid combinations. For example,
penalty="l1"is not valid with everysolverinLogisticRegression. Such trials fail or waste budget. Encode the valid pairs as separate dictionaries. - Too many dimensions. Each extra hyperparameter widens the space. Fix unimportant ones at their defaults and tune the two or three that matter most.
- Narrowing from the test score. Adjust ranges using cross-validation results on the training data only. Using the test set for this leaks information into your choices.
Exercise
You tune a gradient-boosted model with learning_rate = uniform(0.001, 1.0) in RandomizedSearchCV and get a best value of 0.31. A colleague says the search barely explored small learning rates. Explain why, and write the corrected distribution. Also state what the result tells you about your upper bound.
Show answer
uniform(0.001, 1.0) is linear over about 0.001 to 1.001, so roughly 90% of samples exceed 0.1. Values from 0.001 to 0.01 get about 1% of the trials. Learning rates act multiplicatively, so use loguniform(1e-3, 1), which gives each power of ten equal probability. The best value of 0.31 is not at the upper bound of 1.0, so the bound does not look binding. Check the lower decades with the corrected distribution before concluding that 0.31 is near-optimal.