Sub topic 2
Making runs reproducible
This chapter assumes you know Python functions and dataclasses, can run pytest, and have trained a scikit-learn model. It builds on the pipeline.py module from the stages chapter, which defines load_data, split, train, evaluate, and run_pipeline.
A run is reproducible when the same code, configuration, and data produce the same metrics. Three things usually break this: unseeded randomness, data that changes without notice, and library versions that drift.
Pinning seeds, data, and environments
Put the seed in the configuration, and pass it to every stage that uses randomness. Pin library versions in a lock file, such as one generated by pip freeze. Record a data version, such as a file hash or dataset tag.
A frozen dataclass prevents changes during a run. Its fingerprint changes whenever any setting changes, so equal fingerprints mean equal settings.
import dataclasses
import hashlib
import json
from dataclasses import dataclass
@dataclass(frozen=True)
class TrainConfig:
seed: int = 42
test_size: float = 0.2
n_estimators: int = 100
min_accuracy: float = 0.8
def config_fingerprint(cfg: TrainConfig) -> str:
payload = json.dumps(dataclasses.asdict(cfg), sort_keys=True)
return hashlib.sha256(payload.encode()).hexdigest()[:12]> Common error: calling np.random or creating a model without random_state. Each run then differs, and the test in the next section fails in a confusing way.
Testing stages and the whole pipeline
Write unit tests for single stages, then a smoke test for the full pipeline. Save this as test_pipeline.py:
from pipeline import TrainConfig, load_data, run_pipeline, split
def test_split_is_stable():
X, y = load_data()
cfg = TrainConfig()
first = split(X, y, cfg)
second = split(X, y, cfg)
assert (first[0] == second[0]).all()
def test_pipeline_is_deterministic():
cfg = TrainConfig()
_, first = run_pipeline(cfg)
_, second = run_pipeline(cfg)
assert first == secondRun pytest -q. A failure in the second test usually points to a seed you did not pass.
Recording what each run did
Save each run's configuration and metrics under its fingerprint. The file name then identifies the run.
import dataclasses
import json
from pathlib import Path
def record_run(cfg, metrics, out_dir="runs"):
run_id = config_fingerprint(cfg)
path = Path(out_dir) / f"{run_id}.json"
path.parent.mkdir(parents=True, exist_ok=True)
record = {"run_id": run_id, "config": dataclasses.asdict(cfg), "metrics": metrics}
path.write_text(json.dumps(record, indent=2))
return pathExercise
If you change only n_estimators from 100 to 200, what happens to the fingerprint and the record file name?
Show answer
The fingerprint changes because the sorted JSON payload changes. The record file gets a new name, so the old run's record stays intact.