Sub topic 6
Samplers: how Optuna picks the next trial
A sampler is the component that decides which parameter values the next trial will use. The objective function describes what to measure. The search space describes what is allowed. The sampler chooses where to look next, based on the trials that have already finished.
This chapter assumes you can write an objective function with suggest_float, suggest_int and suggest_categorical, and that you know what a study and a trial are. The next chapter covers the internals of the default sampler, TPE.
What a sampler does
Each time a trial calls trial.suggest_*, Optuna asks the study's sampler for a value. The sampler sees three things:
- The study's history: the parameters and scores of all finished trials.
- The distribution for the parameter being requested, such as a log-scaled float between 1e-3 and 1e3.
- The optimisation direction, so it knows whether lower or higher scores are better.
The sampler returns one value. The objective function never needs to know which sampler is in use, so you can change the sampler without editing the objective.
Choosing a sampler
You pass a sampler to create_study. If you pass none, Optuna uses TPESampler.
| Sampler | Idea | Good for | Watch out for |
|---|---|---|---|
| `RandomSampler` | Draws each value independently from the search space | Baselines, very cheap objectives, sanity checks | Ignores all past results |
| `GridSampler` | Tries every combination from a grid you provide | Small, discrete spaces where you want full coverage | Number of trials grows multiplicatively with each parameter |
| `TPESampler` | Models good and bad regions of past trials and favours good ones | Most general tuning, mixed and conditional spaces | Needs some trials before it helps |
| `CmaEsSampler` | Adapts a multivariate Gaussian search distribution | Continuous parameters, moderate dimension | Weak with categorical parameters; requires the `cmaes` package |
| `GPSampler` | Fits a Gaussian process to past trials | Expensive objectives with few trials | Cost per suggestion grows with trial count |
| `NSGAIISampler` | Evolutionary search that keeps a population | Multi-objective studies | Needs many trials to evolve |
Treat this as a starting guide. The available samplers and their defaults can change between Optuna versions, so check the documentation for the version you have installed.
Setting a sampler
The example below tunes the same classifier problem with two samplers, so you can compare them directly.
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
optuna.logging.set_verbosity(optuna.logging.WARNING)
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()
samplers = {
"random": optuna.samplers.RandomSampler(seed=42),
"tpe": optuna.samplers.TPESampler(seed=42),
}
for label, sampler in samplers.items():
study = optuna.create_study(direction="maximize", sampler=sampler)
study.optimize(objective, n_trials=30)
print(label, round(study.best_value, 4), study.best_trial.params)On a problem as easy as iris, both samplers will likely reach similar scores, because many settings work well. The gap between samplers shows up on harder problems, with more parameters and costlier trials.
Random search as a baseline
Random search is simple, but it is not a weak choice by default. With a fixed budget, it often beats a grid when only a few parameters really matter. A grid spends many trials repeating the same few values of the important parameter. Random search tries a new value of every parameter on every trial.
Always keep random search in mind as the baseline. If an adaptive sampler cannot beat RandomSampler with the same budget and seed handling, the extra complexity is not paying off.
Grid search and its limits
GridSampler takes a dictionary mapping parameter names to the exact values to try.
import optuna
search_space = {"x": [-2, 0, 2, 4], "y": [0.0, 0.5, 1.0]}
def objective(trial):
x = trial.suggest_int("x", -2, 4)
y = trial.suggest_float("y", 0.0, 1.0)
return (x - 2) ** 2 + (y - 0.5) ** 2
sampler = optuna.samplers.GridSampler(search_space)
study = optuna.create_study(direction="minimize", sampler=sampler)
study.optimize(objective, n_trials=len(sampler._all_grids))
print(study.best_params)Here the grid has 4 × 3 = 12 combinations. Adding a third parameter with 5 values would make it 60. The grid does not adapt, so it cannot focus on a promising region. The sampler stops the study once every combination has run.
Note that the names in the grid must match the names used in suggest_*, and the values you suggest must lie within the grid's values.
Independent and relative sampling
Samplers differ in how they treat dependencies between parameters.
- Independent sampling chooses each parameter on its own, ignoring the values chosen for the other parameters in the same trial. Random search works this way. TPE by default also samples each parameter independently.
- Relative sampling chooses several parameters together, so it can learn that certain combinations work well. CMA-ES and Gaussian process samplers work this way.
In define-by-run code, parameters appear one at a time as the objective runs, and the search space can change from trial to trial. Relative samplers need to know the space in advance, so Optuna infers it from past trials. Parameters that were not seen in earlier trials fall back to independent sampling. This matters when your search space is conditional: a relative sampler may handle the conditional parts less well than TPE.
TPE can model parameter interactions too if you create it with multivariate=True:
import optuna
sampler = optuna.samplers.TPESampler(seed=0, multivariate=True)
study = optuna.create_study(direction="minimize", sampler=sampler)This is worth trying when you suspect that parameters interact, for example learning rate and batch size.
Startup trials
Adaptive samplers need data before they can learn anything. TPE uses random sampling for its first trials, controlled by n_startup_trials (10 by default in current versions). With a budget of 20 trials, half your search is effectively random. For small budgets, lower n_startup_trials only if you have a good reason, and expect noisier results.
Common mistakes
- Comparing samplers with a single run. Results vary with the seed. Repeat each comparison with several seeds and compare the averages.
- Using a grid on continuous parameters. A grid forces you to choose values by hand, which defeats automatic search.
- Picking CMA-ES for a space dominated by categorical choices. It is designed for continuous parameters.
- Assuming a seed makes parallel runs repeatable. Seeds fix the sampler's random numbers, but the order in which parallel trials finish can still change the history the sampler sees.
- Expecting an adaptive sampler to help in the first few trials. It needs history.
Exercise
You have 25 trials and a space with one categorical parameter (4 options), two log-scaled floats and one integer. A colleague proposes GridSampler with 5 values per float and 5 integer values. How many trials would the full grid need, and which sampler would you use instead?
Show answer
The grid has 4 × 5 × 5 × 5 = 500 combinations, far beyond the 25-trial budget, so most of the grid would never run. Use TPESampler (the default) with a fixed seed, optionally lowering nstartuptrials a little. Compare it against RandomSampler with several seeds to check that the adaptive search helps.
Exercise
Why can a study created with the same TPESampler seed still produce different results across runs when n_jobs is greater than 1?
Show answer
The seed fixes the sampler's random numbers, but with parallel workers the trials finish in a varying order. The sampler's suggestions depend on which trials have finished at the moment each new trial starts, so the history, and therefore the suggestions, can differ between runs.