Sub topic 14
Making runs reproducible
This chapter assumes you can run a basic Optuna study and know what a sampler does. A reproducible run gives the same trials, the same values and the same best parameters when you repeat it. Without that, you can't tell whether a change in score came from your edit or from chance.
Where randomness comes from
Three separate sources of randomness affect a study. Seeding only one of them leaves the others free to vary.
| Source | What varies | How to fix it |
|---|---|---|
| The sampler | Which parameters each trial suggests | Pass `seed=` to the sampler |
| The model | Weight initialisation, bootstrap samples, feature subsets | Set `random_state` in the model |
| The data splits | Which rows land in each fold | Use a fixed `random_state` in the splitter |
Optuna controls only the first row. The objective function owns the other two.
Seed the sampler and the objective
Every built-in sampler takes a seed argument, for example TPESampler(seed=42) or RandomSampler(seed=42). The example below builds a splitter with a fixed seed, passes random_state to the model and seeds the sampler. It then runs the same study twice and compares the results.
import optuna
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import StratifiedKFold, cross_val_score
optuna.logging.set_verbosity(optuna.logging.WARNING)
X, y = load_iris(return_X_y=True)
cv = StratifiedKFold(n_splits=3, shuffle=True, random_state=0)
def objective(trial):
depth = trial.suggest_int("rf_max_depth", 2, 16)
n = trial.suggest_int("n_estimators", 20, 200)
model = RandomForestClassifier(max_depth=depth, n_estimators=n, random_state=0)
return cross_val_score(model, X, y, cv=cv).mean()
def run():
sampler = optuna.samplers.TPESampler(seed=42)
study = optuna.create_study(direction="maximize", sampler=sampler)
study.optimize(objective, n_trials=20)
return study
a, b = run(), run()
print(a.best_params == b.best_params)
print([t.value for t in a.trials] == [t.value for t in b.trials])Both lines print True. Remove the seed=42 and the trials will differ between the two runs.
What still breaks reproducibility
- Parallel trials. With
n_jobsabove 1, or several processes sharing one storage, trials finish in an unpredictable order. TPE uses the finished trials to choose the next one, so the order changes the suggestions. For an exactly repeatable run, use a single worker. - Resumed studies. The database stores trials, not the sampler's random state. A study you stop and resume with
load_if_exists=Trueis valid, but it won't match an uninterrupted run with the same seed. - Library versions. Optuna and scikit-learn can change sampler or model internals between releases. Record the versions you used.
- Unseeded code. A call to
np.randomorrandominside the objective is outside Optuna's control. Seed it yourself or pass a generator. - Hardware and threading. Some models, especially on GPUs, give slightly different numbers even with fixed seeds.
A practical checklist
- Seed the sampler.
- Seed the model and the data splits inside the objective.
- Run with one worker when you need an exact repeat.
- Save the Optuna, scikit-learn and Python versions with your results.
- Store the study in a database, so the full trial history can be inspected later.
Exercise
You run the same seeded study twice, but this time with njobs=4, and the best parameters differ. The sampler seed, model randomstate and splitter seed are all fixed. What is the most likely cause?
Show answer
With several workers, trials finish in a varying order. TPE bases each suggestion on the trials completed so far, so a different completion order produces different suggestions. Run with n_jobs=1 to get an exact repeat.