Sub topic 14
Reproducible tuning runs
This chapter assumes you can run GridSearchCV and RandomizedSearchCV, you know why a test set stays untouched during tuning, and you have seen random_state in scikit-learn. Here you will learn where randomness enters a tuning run, how to fix it, and what to record so someone else (or you in six months) can repeat the run and get the same answer.
What reproducible means here
A tuning run is reproducible when the same code, data, and environment give the same chosen settings and the same scores. Three levels are worth separating:
- Exact repeat: the same machine and library versions give identical numbers.
- Same-environment rerun: another machine with the same pinned versions gives identical or nearly identical numbers.
- Statistical reproduction: a different seed gives a similar score, and the same settings come out roughly on top.
Seeds give you the first level. Recording the environment gives you the second. Running several seeds gives you the third, and it is the one that tells you whether your result is real.
Where the randomness comes from
A single call to a search object hides several independent random processes. Each needs its own seed.
| Source | What it affects | How to fix it |
|---|---|---|
| Train/test split | Which rows end up in the held-out test set | `random_state` in `train_test_split` |
| Cross-validation folds | Which rows are in each fold | `StratifiedKFold(shuffle=True, random_state=...)` |
| Search sampler | Which settings random search tries | `random_state` in `RandomizedSearchCV`, or `seed` in an Optuna sampler |
| The model itself | Tree bootstrap samples, weight initialization, SGD order | `random_state` on the estimator |
| Parallel execution | Order of results, and floating-point sums on some backends | Fixed seeds, plus awareness of the limits below |
If you pass cv=5 to a classifier search, scikit-learn uses StratifiedKFold without shuffling. That is deterministic, but it depends on the row order in your data. If the file is sorted by date or by class, the folds are biased. Shuffling with a fixed seed removes the order dependence and still repeats exactly.
A common mistake is to set random_state on the search object and forget the estimator. The sampled settings then repeat, but a random forest trained with those settings still gets a fresh random bootstrap on every run, so the scores drift.
A run you can repeat
The script below sets every seed from a single value, runs the search twice, and checks that the two runs agree. It then writes the settings, scores, and environment to disk.
import json
import platform
import sys
import pandas as pd
import sklearn
from scipy.stats import randint
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import (
RandomizedSearchCV,
StratifiedKFold,
train_test_split,
)
def run_search(seed):
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=seed, stratify=y
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=seed)
model = RandomForestClassifier(random_state=seed)
distributions = {
"n_estimators": randint(50, 300),
"max_depth": randint(2, 16),
"min_samples_leaf": randint(1, 10),
}
search = RandomizedSearchCV(
model,
distributions,
n_iter=20,
cv=cv,
scoring="accuracy",
random_state=seed,
n_jobs=-1,
)
search.fit(X_train, y_train)
record = {
"seed": seed,
"n_iter": 20,
"cv": "StratifiedKFold(5, shuffle=True)",
"scoring": "accuracy",
"best_params": {k: int(v) for k, v in search.best_params_.items()},
"best_cv_score": float(search.best_score_),
"test_score": float(search.score(X_test, y_test)),
"python": sys.version.split()[0],
"platform": platform.platform(),
"sklearn": sklearn.__version__,
}
return search, record
search_a, record_a = run_search(seed=42)
search_b, record_b = run_search(seed=42)
assert record_a["best_params"] == record_b["best_params"]
assert record_a["best_cv_score"] == record_b["best_cv_score"]
with open("tuning_run.json", "w") as f:
json.dump(record_a, f, indent=2)
pd.DataFrame(search_a.cv_results_).to_csv("cv_results.csv", index=False)
print(record_a)Two details matter. The seed is one variable passed to every component, so you cannot change the split and forget the folds. The full cv_results_ table is saved too, not only the winner, because you need it to judge whether the winner was clearly better than its neighbors (see the chapter on interpreting results).
What to record
Seeds alone are not enough. A reader needs to know what the run was, not only how to restart it. Save these together in one folder, ideally named by date or by a short hash:
- The seed or seeds, and which components each one controls.
- The search space, written out exactly, including the scale (log or linear) of each range.
- The search method and budget: grid size,
n_iter, number of folds, number of Optuna trials, any time limit. - The scoring metric and the cross-validation scheme.
- A pointer to the data version: a file hash, a dataset release tag, or a commit of the code that builds it.
- Library versions, from
pip freezeor a lock file. A change in the scikit-learn version can change defaults, and a change in NumPy can change what a seed produces. - The full results table, the chosen settings, the cross-validated score, and the single test score.
Limits of seeding
Setting seeds does not guarantee identical numbers everywhere.
- Parallelism. In scikit-learn,
n_jobs=-1is safe when each trial has a fixed seed, because the work is split by candidate and fold, and each fit sees its own seeded state. Some libraries sum floating-point values across threads in a changing order, and the last digits can differ. - Optuna with parallel trials. Seeding
TPESamplergives repeatable results only when trials run one after another. Withstudy.optimize(..., n_jobs=4), or several worker processes sharing a database, the order in which trials finish changes what the sampler has seen, so the suggestions differ between runs even with the same seed. - GPUs. Many deep-learning kernels are non-deterministic unless you switch on deterministic modes, which can be slower. Some operations have no deterministic version.
- Time-based budgets. A limit such as "tune for 10 minutes" yields a different number of trials on a faster or busier machine. Prefer a fixed trial count when you need repeatability, and record the time limit only as a secondary cap.
- Library upgrades. The same seed can map to different random draws after a version change. Pin versions.
Seed sensitivity: the third level
A fixed seed makes a run repeatable, but it can also make a lucky result look solid. Different splits and folds shift scores, and on small data the shift can be larger than the gap between the best and second-best settings.
A simple check is to repeat the whole procedure with a handful of seeds, such as 0 through 4, and compare:
- Does the same region of the search space win each time, even if the exact best point moves?
- How large is the spread of the test scores across seeds? Report the mean and standard deviation instead of a single number.
- Does the ranking of two competing models stay the same?
If the winning settings jump around but the scores are close, the surface is flat and many settings are about equally good. That is useful to know, and it often means you can choose the cheaper or simpler setting. Do not pick the best seed after the fact. Choose the seeds before the run and report all of them.
Reproducing an Optuna study
For sequential Optuna runs, a seed on the sampler plus a fixed trial count repeats the study. To keep the results after the process ends, give the study a storage location and a name:
import optuna
study = optuna.create_study(
study_name="rf_breast_cancer_v1",
storage="sqlite:///tuning.db",
direction="maximize",
sampler=optuna.samplers.TPESampler(seed=0),
load_if_exists=True,
)The database keeps every trial's settings and value, so you can export them later with study.trials_dataframe(). Note that if you resume a study and run more trials, the sampler restarts from its seed, so the continued run is not identical to one long run. State that in your record when it happens.
Common errors
- Seeding the search but not the estimator or the folds.
- Reusing one seed for the data split and tuning, then reporting the test score from that single split as if it were general.
- Re-running the search after looking at the test score, which turns the test set into a second validation set. Record the test score once.
- Saving only
best_params_, so the evidence for the choice is lost. - Leaving library versions unrecorded.
Exercise
You tune a random forest with RandomizedSearchCV(randomstate=7, njobs=-1) and a plain integer cv=5. You run the script twice and get slightly different bestscore values. Name two seeds you probably forgot to set, and say which seed you would pick for each.
Show answer
First, the estimator: RandomForestClassifier needs randomstate (for example the same master seed), because its bootstrap samples and feature choices are random, so each fit differs between runs. Second, the folds or the split: pass StratifiedKFold(nsplits=5, shuffle=True, randomstate=seed) as cv, and set randomstate in traintestsplit. With shuffle off the folds are repeatable, but if you shuffled anywhere without a seed the rows land in different folds each time. Setting all of them from one master seed makes the run repeatable.