Sub topic 7
How the TPE sampler works
This chapter assumes you can write an Optuna objective function with suggest_* calls and run study.optimize. It also assumes you know what a sampler is: the component that proposes the next set of hyperparameters. Here you will see what the default sampler, TPE, does between those calls.
What TPE stands for
TPE is the Tree-structured Parzen Estimator. The name has two parts.
- Parzen estimator is a kernel density estimate. It places a small bell-shaped curve on each observed value and adds the curves together. The result is a smooth probability density fitted to a handful of points.
- Tree-structured refers to search spaces where some parameters exist only when another parameter takes a certain value. Optuna's define-by-run conditional spaces are an example.
Optuna uses TPE by default for single-objective studies. If you call optuna.create_study() without a sampler, you get TPESampler.
The core idea: model where good trials live
Many Bayesian optimisers model the objective directly. They fit a surrogate for p(score | parameters) and then pick parameters that look promising. TPE flips this and models p(parameters | score).
After some trials have finished, TPE does the following:
- Sort the finished trials by score.
- Split them into a "good" group (the best fraction) and a "bad" group (the rest).
- Fit a density
l(x)to the parameters of the good trials. - Fit a density
g(x)to the parameters of the bad trials. - Draw several candidate points from
l(x). - Evaluate
l(x) / g(x)for each candidate and pick the largest.
A high ratio means the point is common among good trials and rare among bad ones. Maximising it is closely related to maximising expected improvement, which is why TPE works as a Bayesian method without ever modelling the score itself.
The parts you can configure
The TPESampler constructor exposes the steps above as arguments.
| Argument | Default | What it controls |
|---|---|---|
| `n_startup_trials` | 10 | Number of purely random trials before TPE starts modelling. |
| `n_ei_candidates` | 24 | Number of candidates drawn from `l(x)` per suggestion. |
| `gamma` | a function of the trial count | Decides how many trials count as "good". |
| `consider_prior` | `True` | Mixes a wide prior into each density so it never collapses onto a few points. |
| `prior_weight` | 1.0 | How strongly that prior counts. |
| `multivariate` | `False` | Models parameters jointly instead of one at a time. |
| `group` | `False` | With `multivariate=True`, handles conditional spaces by grouping parameters. |
| `constant_liar` | `False` | Helps parallel workers avoid proposing near-duplicate points. |
| `seed` | `None` | Seeds the sampler's random number generator. |
The default gamma takes the best 10% of trials, capped at 25. With 100 finished trials, the good group has 10 members. With 1000 trials, it has 25. The cap keeps the good density focused on a small elite group even in long studies.
Startup trials and why they matter
With zero or few observations there is nothing to split, so TPE falls back to random sampling for the first n_startup_trials. This phase makes sure the good and bad densities are built from points spread across the space.
If your trials are expensive and you can afford only 20, the default of 10 means half your budget is random. Lowering it can help a little. Going too low gives densities fitted to two or three points, and those can lock onto a poor region early.
Independent versus multivariate TPE
By default, TPE fits a separate pair of densities for each parameter. When it suggests learning_rate, it ignores the current choice of batch_size. This is cheap and robust, but it cannot represent interactions, such as a good learning rate depending on batch size.
Setting multivariate=True fits a joint density over the parameters, so correlations between them are captured. It tends to help when parameters interact strongly. Two caveats apply:
- Older Optuna releases mark the option as experimental and emit an
ExperimentalWarning. - Joint densities need more data to be reliable, so the benefit shows up later in a study.
For conditional spaces, multivariate=True alone does not treat the conditions properly. Add group=True so that parameters that always appear together are modelled together.
How different parameter types are handled
- Floats and integers use Gaussian-mixture densities truncated to the search range. Integers are treated as rounded continuous values.
- Log-scaled parameters (
log=True) are modelled in log space. This is whylog=Truematters for TPE: the bell curves are placed where the values are evenly spread, not crowded near zero. - Categoricals use a weighted categorical distribution built from the counts of each choice among good and bad trials, smoothed by the prior.
- Conditional parameters are modelled only from the trials where they actually appeared.
Comparing TPE with random search
The following script runs both samplers on the same two-dimensional problem and prints the best value each one finds.
import optuna
from optuna.samplers import RandomSampler, TPESampler
optuna.logging.set_verbosity(optuna.logging.WARNING)
def objective(trial):
x = trial.suggest_float("x", -10, 10)
y = trial.suggest_float("y", -10, 10)
return (x - 2) ** 2 + (y + 1) ** 2
samplers = {
"random": RandomSampler(seed=0),
"tpe": TPESampler(seed=0),
"tpe multivariate": TPESampler(seed=0, multivariate=True),
"tpe few startup": TPESampler(seed=0, n_startup_trials=5),
}
for name, sampler in samplers.items():
study = optuna.create_study(direction="minimize", sampler=sampler)
study.optimize(objective, n_trials=60)
print(f"{name:18s} best value: {study.best_value:.5f}")On this smooth problem, TPE variants usually end up much closer to zero than random search. The exact numbers depend on your Optuna version, so treat a single seed as an illustration. To judge a configuration properly, repeat the comparison over several seeds.
Limits and failure modes
- Noise in scores. If cross-validation scores vary by more than the differences between configurations, the good/bad split is partly arbitrary and TPE learns little.
- Sequential bias. TPE depends on completed trials. Many parallel workers asking at once see the same data and may propose near-identical points.
constant_liar=Truereduces this. - Premature focus. A few lucky early trials can concentrate sampling in a mediocre region. The prior and the random startup phase soften this but do not remove it.
- Pruned trials. Pruned trials still contribute to the densities through their last reported value, but a pruned score is only a partial result and can mislead the split when it is compared with finished trials.
Exercise
A study has 200 finished trials and uses the default settings. How many trials fall in TPE's "good" group, and why might you set log=True for a parameter such as a regularisation strength that spans 1e-6 to 1e-1?
Show answer
The default gamma takes the best 10% of trials, capped at 25, so 10% of 200 is 20 trials. With log=True, TPE fits its densities in log space, so values at 1e-6 and 1e-1 get equal attention. Without it, the Parzen curves would concentrate on the large end of the range and barely distinguish small values.