Sub topic 14
Reproducible tuning runs
This chapter assumes you can run GridSearchCV or RandomizedSearchCV and know why tuning uses cross-validation. It covers how to make a tuning run repeatable and what to record so others can check it.
Where the randomness comes from
Two runs of the same script can pick different "best" settings. Several separate sources of randomness cause this:
| Source | Controlled by |
|---|---|
| Train/test split | `random_state` in `train_test_split` |
| Cross-validation folds | `random_state` in `StratifiedKFold` with `shuffle=True` |
| Sampled settings in random search | `random_state` in `RandomizedSearchCV` |
| Model internals (tree bagging, initial weights) | the model's own `random_state` |
| Sequential samplers such as Optuna's TPE | the sampler's `seed` |
Fixing only one of these leaves the others free to change the result. Set each one explicitly.
A seeded run that records itself
The script below fixes every seed and saves the settings, versions, and results in one JSON file.
import json
import platform
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,
)
SEED = 0
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)
search = RandomizedSearchCV(
RandomForestClassifier(random_state=SEED),
{
"n_estimators": [100, 200, 300],
"max_depth": [3, 5, 8, None],
"min_samples_leaf": randint(1, 10),
},
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",
"python": platform.python_version(),
"sklearn": sklearn.__version__,
"best_params": search.best_params_,
"best_cv_score": search.best_score_,
"test_score": search.score(X_test, y_test),
}
with open("tuning_run.json", "w") as f:
json.dump(record, f, indent=2, default=lambda o: o.item() if hasattr(o, "item") else str(o))
print(record)Run it twice. The two tuning_run.json files should match. If they differ, one source of randomness is still unseeded.
What to record
A run is reproducible only if someone else can rebuild the same conditions. Save these items next to the results:
- All seeds, plus the search space and
n_iteror the grid. - The scoring metric and the CV scheme.
- The library versions and the Python version.
- A hash or version label of the dataset.
- The full
search.cv_results_, not only the winner. Convert it withpandas.DataFrame(search.cv_results_)and save it as CSV.
The full results let a reader see how close the runner-up settings were. They also show whether the scores had a clear peak or a flat plateau.
Seeds are not evidence
A seed makes one run repeatable. It does not show that the result is stable. If you tune with seed 0 and report one score, you may have picked a lucky split. To check stability, repeat the whole procedure with a few seeds, such as 0 to 4. Report the mean and spread of the scores. If the chosen settings change a lot from seed to seed, the surface is flat, and many settings are about equally good.
Exercise
You set random_state=0 in RandomizedSearchCV and in train_test_split, but two runs still give different best settings when the model is a random forest. What did you most likely forget, and how do you check that your fix works?
Show answer
The forest's own random_state. Its bootstrap sampling and feature choices change every run. Set RandomForestClassifier(random_state=0), and also give the CV splitter a seed if it shuffles. To check, run the script twice and compare the saved best_params and best_cv_score. They should be identical.