Sub topic 2
Conditional Search Spaces with Define-by-Run
Assumes basic Python, Optuna, and scikit-learn, including cross-validation. This chapter shows how to tune different model families in one study.
Conditional search spaces
A conditional search space contains parameters that depend on an earlier choice. Optuna uses a define-by-run API: the objective function defines parameters while each trial runs.
For example, an SVM needs C, while a random forest needs max_depth. Suggest only the parameters required by the selected classifier.
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)Samplers and TPE
A sampler chooses values for the next trial. Random sampling explores without using earlier results. The TPE sampler models which parameter values belong to good and poor trials, then favours values that are more likely to improve the objective. TPE often finds good settings with fewer trials, especially when evaluations are expensive.
Cross-validation and pruning
Cross-validation trains and evaluates a model on several folds, producing a more stable score than one split. However, a trial that trains incrementally can report intermediate scores. A pruner uses these reports to stop trials that are unlikely to become competitive.
for step in range(20):
clf.partial_fit(X_train, y_train, classes=classes)
score = clf.score(X_val, y_val)
trial.report(score, step)
if trial.should_prune():
raise optuna.TrialPruned()
return scoretrial.report records the score at a step. trial.should_prune() asks the configured pruner whether to stop. Pruning saves time, but use it only when intermediate results predict final performance.
Exercise
Why should an objective function avoid suggesting svc_c when the selected classifier is a random forest?
Show answer
It keeps the search space meaningful and prevents irrelevant parameters from affecting that trial.