Sub topic 5
Conditional search spaces with define-by-run
This chapter assumes you can write a basic Optuna objective function and call suggest_float, suggest_int and suggest_categorical. You should also know how to score a scikit-learn model with cross-validation.
Why some spaces are conditional
Some hyperparameters only exist when an earlier choice makes them relevant. An SVM has a regularisation constant C. A random forest has a maximum depth. Asking for max_depth when you picked an SVM makes no sense.
A fixed grid of parameters cannot express this without wasted or invalid combinations. Optuna uses a define-by-run API instead. The search space is built while the objective function runs, so ordinary Python if statements and loops can shape it.
A conditional objective
The objective below first picks a classifier. It then suggests only the hyperparameters that classifier needs.
import optuna
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from sklearn.svm import SVC
X, y = load_iris(return_X_y=True)
def objective(trial):
name = trial.suggest_categorical("classifier", ["svc", "rf"])
if name == "svc":
c = trial.suggest_float("svc_c", 1e-3, 1e3, log=True)
model = SVC(C=c, gamma="scale")
else:
depth = trial.suggest_int("rf_max_depth", 2, 16)
model = RandomForestClassifier(max_depth=depth, n_estimators=100, random_state=0)
return cross_val_score(model, X, y, cv=3).mean()
sampler = optuna.samplers.TPESampler(seed=42)
study = optuna.create_study(direction="maximize", sampler=sampler)
study.optimize(objective, n_trials=30)
print(study.best_trial.params)Each trial records only the parameters it actually suggested. A trial that chose svc has classifier and svc_c. A trial that chose rf has classifier and rf_max_depth.
How the sampler handles it
The sampler is asked for each value at the moment you call suggest_*. By then the earlier choices are already known, so the sampler can condition on them. TPE, the default sampler, models parameters it has seen in earlier trials. Trials that lack a parameter simply do not contribute to that parameter's model.
Common errors
- Reusing a name with a different range. Within one study, a parameter name must keep the same distribution. Suggesting
"x"as an integer in one branch and a float in another raises an error. Give each branch its own prefix, such assvc_candrf_max_depth. - Using the same name in two branches on purpose. This is allowed only if both calls use identical ranges.
- Forgetting the branch variable is a parameter too.
classifierappears inbest_params. Read it first to know which other keys to expect. - Assuming all trials share the same keys. When you build a table of results, some columns will be empty for some trials. Code that indexes
trial.params["rf_max_depth"]must check the classifier first.
Loops for dynamic spaces
The space can also vary in size. A common case is a variable number of neural network layers.
import optuna
def objective(trial):
n_layers = trial.suggest_int("n_layers", 1, 3)
total = 0.0
for i in range(n_layers):
units = trial.suggest_int(f"units_l{i}", 8, 128)
total += abs(units - 64)
return total
study = optuna.create_study(direction="minimize")
study.optimize(objective, n_trials=20)
print(study.best_params)Here units_l1 exists only when n_layers is at least 2.
Exercise
In the classifier objective, a trial chose "rf". Which parameter names does that trial record, and why is "svc_c" absent?
Show answer
It records "classifier" and "rfmaxdepth". The "svc_c" call sits inside the "svc" branch of the if statement. It never runs for this trial, so the trial never records that parameter.
Exercise
Why should each branch use its own parameter name prefix, such as svcc and rfmax_depth?
Show answer
A name is tied to one distribution inside a study. Reusing a name with a different type or range raises an error. Distinct prefixes keep each branch's distribution separate and clear.