Sub topic 4
Defining the search space with suggest_float, suggest_int and suggest_categorical
This chapter assumes you can write an Optuna objective function that takes a trial and returns a score, and that you know what a hyperparameter is. Here we cover the three suggest_* methods that define the search space, and the mistakes that most often make a search waste its trials.
What a search space is in Optuna
A search space is the set of values each hyperparameter is allowed to take. Optuna has no separate declaration for it. The space is defined by the suggest_* calls your objective makes, which is called define-by-run. Each call does two things:
- It tells the sampler the name, type and range of the parameter.
- It returns the concrete value the sampler chose for this trial.
import optuna
def objective(trial):
x = trial.suggest_float("x", -10, 10)
return (x - 2) ** 2The name ("x") identifies the parameter across all trials in the study. The sampler uses past values and scores recorded under that name to decide where to look next.
The three methods
| Method | Value returned | Useful options | Typical use |
|---|---|---|---|
| `suggest_float(name, low, high)` | `float` in `[low, high]` | `log=True`, `step=...` | learning rate, regularisation strength, dropout |
| `suggest_int(name, low, high)` | `int` in `[low, high]`, both ends included | `log=True`, `step=...` | tree depth, number of layers, units |
| `suggest_categorical(name, choices)` | one element of `choices` | none | model type, activation, optimizer |
Both bounds are inclusive. choices may contain only None, bool, int, float and str values. Passing lists, tuples or model objects is a common error, and the fix is to pass a string name and build the object afterwards.
Choosing a scale: linear or log
By default a float or int is sampled on a linear scale, so every part of the range is equally likely. That is wrong for parameters that matter across orders of magnitude. With a linear range of 1e-5 to 1e-1 for a learning rate, about 90% of the samples fall between 1e-2 and 1e-1, and the small values are almost never tried.
Set log=True to sample uniformly in log space, so each decade gets the same attention.
lr = trial.suggest_float("lr", 1e-5, 1e-1, log=True)Use a log scale when:
- the parameter is a rate, a penalty or a scale (learning rate,
C,alpha, weight decay); - the useful range spans two or more orders of magnitude;
- you would naturally write the bounds as powers of ten.
Use a linear scale for quantities such as dropout probability between 0 and 0.5, or a subsample fraction. A log scale requires low > 0. If low is zero or negative, Optuna raises a ValueError.
Discretising with step
Both numeric methods accept step, which restricts the values to a grid starting at low.
n_estimators = trial.suggest_int("n_estimators", 50, 500, step=50)
dropout = trial.suggest_float("dropout", 0.0, 0.5, step=0.1)The first call yields 50, 100, ..., 500. Use step when only certain values make sense, or when differences smaller than the step cannot change the result. Fewer distinct values makes the space easier for the sampler to cover. step and log=True cannot be combined, and Optuna raises an error if you try.
A complete example
The objective below tunes a random forest with all three methods and scores it with cross-validation. It runs as written.
import optuna
from sklearn.datasets import load_wine
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
X, y = load_wine(return_X_y=True)
def objective(trial):
params = {
"n_estimators": trial.suggest_int("n_estimators", 50, 300, step=50),
"max_depth": trial.suggest_int("max_depth", 2, 16),
"min_samples_leaf": trial.suggest_int("min_samples_leaf", 1, 32, log=True),
"max_features": trial.suggest_categorical("max_features", ["sqrt", "log2", None]),
"max_samples": trial.suggest_float("max_samples", 0.5, 1.0),
}
model = RandomForestClassifier(bootstrap=True, random_state=0, **params)
return cross_val_score(model, X, y, cv=3).mean()
optuna.logging.set_verbosity(optuna.logging.WARNING)
study = optuna.create_study(direction="maximize")
study.optimize(objective, n_trials=25)
print(study.best_params)
print(study.best_value)Note that None is a valid categorical choice, which matches scikit-learn's meaning of "use all features". min_samples_leaf uses log=True because the difference between 1 and 2 matters more than the difference between 31 and 32.
How the sampler sees each parameter
Internally, each call becomes a distribution object: a float distribution, an int distribution or a categorical distribution, with its bounds, log flag and step. The sampler works from these distributions and from the values and scores of finished trials.
Three consequences follow.
- Names are keys. Calling
suggest_float("x", ...)twice in the same trial returns the same value both times. It does not draw a new one. Reusing a name for two different parameters therefore silently merges them. - Types are fixed within a study. If you change a parameter from
suggest_inttosuggest_float, or change thechoicesof a categorical, and then reload a stored study, Optuna raises aValueErrorbecause the new distribution is incompatible with the stored trials. Start a new study when you change the structure of a parameter. - Categorical choices are unordered. The sampler learns nothing about "closeness" between
"relu"and"tanh". If a parameter has a natural order, such as 2, 4, 8, 16 layers, model it as an integer so the sampler can exploit that.
Choosing good bounds
The sampler can only find values inside your bounds, so the bounds are part of the model you are tuning.
- Start wide, then narrow. Run a first study with generous ranges. Look at where the best trials cluster, then run a second study with tighter bounds. Chapter material on visualisation shows how to see this.
- Watch the edges. If the best value sits at a boundary, the true optimum may lie outside. Widen that bound.
- Keep the space small. Every extra parameter multiplies the volume to search. Fix parameters you do not expect to matter, and spend trials on the ones that do.
- Do not search what you can compute. Derive dependent values inside the objective from a single suggested value instead of suggesting both.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `ValueError` about `log` and `low` | `log=True` with `low <= 0` | use a positive lower bound |
| `ValueError` about `step` and `log` | both set on one parameter | choose one |
| Error about choices types | list, tuple or object passed to `suggest_categorical` | pass strings and map them to objects in code |
| Error when loading a stored study | a parameter's type or choices changed | create a new study name |
| Best learning rate always near the upper bound | linear scale on a rate | add `log=True` and widen the range |
| Two parameters behave identically | same name used twice | give each a unique name |
Exercise
You want to tune a weight-decay value that you expect to lie somewhere between 0.00001 and 0.1, a number of hidden units from 16 to 256 in steps of 16, and an activation function from "relu", "tanh" and "gelu". Write the three suggest calls, and explain why the weight decay needs an option that the hidden units do not.
Show answer
weightdecay = trial.suggestfloat("weightdecay", 1e-5, 1e-1, log=True) hidden = trial.suggestint("hiddenunits", 16, 256, step=16) activation = trial.suggestcategorical("activation", ["relu", "tanh", "gelu"]) Weight decay spans four orders of magnitude, so it needs log=True. On a linear scale most samples would land between 0.01 and 0.1 and values near 1e-5 would almost never be tried. The hidden units span a small range where a linear scale is appropriate.
Exercise
A study stored in SQLite used suggestcategorical("optimizer", ["sgd", "adam"]). Later you edit the code to add "rmsprop" to the choices and reload the same study name with loadif_exists=True. What happens, and what should you do?
Show answer
Optuna raises a ValueError because the categorical distribution now differs from the one stored with the earlier trials. Create a new study, for example with a new study_name, so that all its trials share the same search space.