Sub topic 5
Conditional search spaces with define-by-run
This chapter assumes you can write a basic Optuna objective function and call trial.suggest_float, trial.suggest_int and trial.suggest_categorical. It also assumes you know what a Study and a Trial are. Here you will see how to make the search space depend on earlier choices, and which mistakes this causes.
Why some spaces are conditional
Many models have parameters that only exist when another choice is made.
- A support vector machine (SVM) with a
linearkernel has nogamma. Anrbfkernel does. - A random forest has
max_depth. A support vector classifier does not. - A neural network with
n_layers = 2needs two layer widths. Withn_layers = 3it needs three.
A fixed grid cannot express this without wasting trials on meaningless combinations, such as tuning gamma for a linear kernel. Optuna avoids the problem by building the search space while the objective runs. This is called define-by-run. Each suggest_* call registers a parameter and returns a value for the current trial. If a branch is not executed, its parameters are never created for that trial.
The core idea: ordinary Python control flow
Optuna has no special syntax for conditions. You use if, for and function calls. The sampler sees only the parameters that the trial actually requested.
A complete example
The objective below chooses between an SVM and a small neural network. Each branch then requests only the parameters it needs.
import optuna
from sklearn.datasets import load_iris
from sklearn.model_selection import cross_val_score
from sklearn.neural_network import MLPClassifier
from sklearn.svm import SVC
X, y = load_iris(return_X_y=True)
def objective(trial):
name = trial.suggest_categorical("classifier", ["svc", "mlp"])
if name == "svc":
kernel = trial.suggest_categorical("svc_kernel", ["linear", "rbf"])
c = trial.suggest_float("svc_c", 1e-3, 1e3, log=True)
if kernel == "rbf":
gamma = trial.suggest_float("svc_gamma", 1e-4, 1e1, log=True)
model = SVC(C=c, kernel="rbf", gamma=gamma)
else:
model = SVC(C=c, kernel="linear")
else:
n_layers = trial.suggest_int("mlp_n_layers", 1, 3)
sizes = tuple(
trial.suggest_int(f"mlp_units_l{i}", 4, 64, log=True)
for i in range(n_layers)
)
alpha = trial.suggest_float("mlp_alpha", 1e-6, 1e-1, log=True)
model = MLPClassifier(
hidden_layer_sizes=sizes, alpha=alpha, max_iter=500, random_state=0
)
return cross_val_score(model, X, y, cv=3).mean()
optuna.logging.set_verbosity(optuna.logging.WARNING)
sampler = optuna.samplers.TPESampler(seed=42)
study = optuna.create_study(direction="maximize", sampler=sampler)
study.optimize(objective, n_trials=40)
print(study.best_value)
print(study.best_trial.params)Three patterns appear here.
- Branching on a categorical value. The value returned by
suggest_categoricalis a plain string, so you can compare it in anif. - Nested conditions.
svc_gammadepends onsvc_kernel, which depends onclassifier. You can nest as deeply as the model requires. - Dynamic structure. The number of
mlp_units_l{i}parameters depends onmlp_n_layers. The loop creates a differently shaped space for each trial.
What the study records
Each trial stores only the parameters it requested. study.best_trial.params for an SVM trial contains no mlp_* keys. To see this across all trials, use the DataFrame export, which requires pandas.
df = study.trials_dataframe(attrs=("number", "value", "params"))
print(df.filter(regex="number|value|params_").head(10))Parameters a trial never requested show up as NaN. This is expected. It is not a sign of a failed trial.
When you rebuild the best model from best_params, repeat the branching logic. Do not index keys that may be missing.
params = study.best_trial.params
if params["classifier"] == "svc":
if params["svc_kernel"] == "rbf":
model = SVC(C=params["svc_c"], kernel="rbf", gamma=params["svc_gamma"])
else:
model = SVC(C=params["svc_c"], kernel="linear")
else:
n_layers = params["mlp_n_layers"]
sizes = tuple(params[f"mlp_units_l{i}"] for i in range(n_layers))
model = MLPClassifier(
hidden_layer_sizes=sizes,
alpha=params["mlp_alpha"],
max_iter=500,
random_state=0,
)If you keep the model construction in a helper such as build_model(params), you can call it from both the objective and this final step. The two paths then cannot drift apart.
Rules for parameter names
Optuna identifies a parameter by its name within a study. This leads to several rules.
- Names are per study, not per branch. If two branches both call
suggest_float("lr", ...), they share one parameter calledlr. Prefix branch-specific names, as insvc_candmlp_alpha. - Asking twice in one trial returns the same value. Calling
trial.suggest_float("x", 0, 1)a second time in the same trial gives back the earlier value. It does not draw a new one. - A name must keep its type. Using the same name as a float in one trial and as a categorical in another raises a
ValueError. - Categorical choices must stay identical. Reusing a name with a different
choiceslist raises aValueError. - Loop-generated names must be stable. Use
f"mlp_units_l{i}", whereiis the layer index. Do not build names from random values or object identities.
Common errors and their causes
| Symptom | Likely cause | Fix |
|---|---|---|
| `ValueError` about a changed distribution | The same name was used with different categorical choices or a different kind | Give each branch its own prefixed name |
| `KeyError` when rebuilding the best model | The code indexes a parameter from a branch the best trial did not take | Branch on the categorical value first, as above |
| Unwanted `NaN` columns in the DataFrame | Conditional parameters were skipped in some trials | Expected. Filter by branch before analysis |
| Study cannot be reloaded or compared | Choices contain objects such as model classes | Use strings, numbers, booleans or `None` as choices and map them to objects inside the objective |
| Branch is almost never explored | The sampler favours an early winner | Run more trials, or check the history to see how trials split across branches |
How samplers cope with conditional spaces
Samplers see each parameter's history only from trials that requested it. The default TPE sampler models each parameter independently. A conditional parameter such as svc_gamma is therefore fitted using only the trials in which it appeared. This works well in practice.
TPE also has multivariate=True, which models parameters jointly. It has a group=True option intended for conditional spaces. Both are marked experimental in the Optuna documentation, and they may emit a warning. Check your installed version before relying on them.
Branching has a cost. Splitting 40 trials across two classifiers and two kernels leaves few trials per leaf. If a branch is clearly worse after a first run, remove it and search the rest more thoroughly.
Summary of the working model
- The search space is whatever the objective requests during that trial.
- Control flow decides which parameters exist. Names identify them across trials.
- The study stores only requested parameters. Rebuild models by repeating the branching logic.
- Prefix names per branch and keep categorical choices fixed.
Exercise
An objective suggests trial.suggest_categorical("optimizer", ["sgd", "adam"]). For sgd it suggests trial.suggest_float("lr", 1e-4, 1e-1, log=True) and trial.suggest_float("momentum", 0.0, 0.99). For adam it suggests trial.suggest_float("lr", 1e-5, 1e-2, log=True). Will this run, and what is the risk? How would you restructure it?
Show answer
Float ranges can differ for the same name, so it will probably run without an error. The risk is that both branches share one parameter called lr, so the sampler fits one model of lr from trials with two different ranges and two different optimisers. This distorts the search and the importance plots. Rename them sgd_lr and adam_lr, and keep sgd_momentum inside the sgd branch. When rebuilding the best model, read params["optimizer"] first and then pick the matching keys.