This is Module 6, the last module of the Machine Learning Engineer path. Six months from now someone will ask which data, code and settings produced the model in production, or why a retrained model scores differently. If the answer is “I’d have to check my notebook”, the model can’t be trusted, audited or improved safely. This module makes every run repeatable and recorded.
You’ll build: one command that rebuilds the data, trains, evaluates against a baseline and appends a record of the run, plus a script that compares runs.
You need: make_data.py from Module 2, and the pinned libraries below.
What makes a run reproducible
| Ingredient | How to fix it | What to record |
|---|---|---|
| Data | Rebuild it with a script, or store an immutable copy | A hash of the file’s contents |
| Code | Commit it to version control | The commit ID |
| Settings | Keep them in a config file, not in the code | The full config |
| Randomness | Set seeds for anything that shuffles or samples | The seed (part of the config) |
| Libraries | Pin exact versions | Library versions at run time |
Pin the libraries in requirements.txt and install from it:
pandas==3.1.1
scikit-learn==1.9.1
Keep the settings in config.json:
{"seed": 42, "cv_folds": 5, "C": 1.0, "features": ["tenure_months", "support_tickets", "monthly_spend", "plan"]}
One command for the whole run
Save this as run.py:
# One command: rebuild the data, train, evaluate against the baseline, and record the run.
# python run.py (or: python run.py --C 0.1 to try a setting; the record says what changed)
import argparse
import hashlib
import json
import platform
import subprocess
import sys
from datetime import datetime, timezone
import pandas as pd
import sklearn
from sklearn.compose import ColumnTransformer
from sklearn.dummy import DummyClassifier
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
cfg = json.load(open("config.json"))
ap = argparse.ArgumentParser()
ap.add_argument("--C", type=float, default=cfg["C"])
cfg["C"] = ap.parse_args().C
subprocess.run([sys.executable, "make_data.py"], check=True, capture_output=True) # 1. rebuild the data
data_hash = hashlib.sha256(open("customers.csv", "rb").read()).hexdigest()[:12]
df = pd.read_csv("customers.csv")
X, y = df[cfg["features"]], df["churned"]
numeric = [f for f in cfg["features"] if f != "plan"]
model = Pipeline([
("prep", ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), numeric),
("cat", OneHotEncoder(handle_unknown="ignore"), ["plan"]),
])),
("clf", LogisticRegression(C=cfg["C"], max_iter=1000)),
])
folds = StratifiedKFold(n_splits=cfg["cv_folds"], shuffle=True, random_state=cfg["seed"]) # 2. fixed seed
auc = cross_val_score(model, X, y, cv=folds, scoring="roc_auc").mean() # 3. evaluate
base = cross_val_score(DummyClassifier(), X, y, cv=folds, scoring="roc_auc").mean()
try:
commit = subprocess.run(["git", "rev-parse", "--short", "HEAD"], capture_output=True, text=True).stdout.strip()
except FileNotFoundError:
commit = ""
record = {"time": datetime.now(timezone.utc).isoformat(timespec="seconds"), "code": commit or "not in git",
"data_sha256": data_hash, "config": cfg, "python": platform.python_version(),
"sklearn": sklearn.__version__, "pandas": pd.__version__,
"roc_auc": round(auc, 4), "baseline_roc_auc": round(base, 4)}
with open("runs.jsonl", "a") as f: # 4. record
f.write(json.dumps(record) + "\n")
print(json.dumps({k: record[k] for k in ("data_sha256", "config", "roc_auc", "baseline_roc_auc")}))
Run it twice, then once with a different setting:
python run.py
python run.py
python run.py --C 0.01
{"data_sha256": "8379dd217ab5", "config": {"seed": 42, "cv_folds": 5, "C": 1.0, "features": ["tenure_months", "support_tickets", "monthly_spend", "plan"]}, "roc_auc": 0.7617, "baseline_roc_auc": 0.5}
{"data_sha256": "8379dd217ab5", "config": {"seed": 42, "cv_folds": 5, "C": 1.0, "features": ["tenure_months", "support_tickets", "monthly_spend", "plan"]}, "roc_auc": 0.7617, "baseline_roc_auc": 0.5}
{"data_sha256": "8379dd217ab5", "config": {"seed": 42, "cv_folds": 5, "C": 0.01, "features": ["tenure_months", "support_tickets", "monthly_spend", "plan"]}, "roc_auc": 0.7613, "baseline_roc_auc": 0.5}
The first two runs are identical: same data hash, same score. That’s the test of reproducibility, and it’s worth running in CI. The third run changed one setting, and the record says exactly which.
Three details do most of the work:
- The data hash. If someone edits or re-exports the data, the hash changes even if the file name doesn’t, so the run record shows a different dataset.
- The seeded folds. Cross-validation shuffles rows; without
random_state, each run would split differently and scores would wobble for no reason you could trace. - The baseline in every record. A score means little without the baseline beside it (Module 1’s rule), and recording both stops anyone from quoting the model’s number alone.
Compare runs
Save this as compare.py:
# Compare recorded runs side by side.
import json
import pandas as pd
runs = pd.DataFrame([json.loads(line) for line in open("runs.jsonl")])
runs["C"] = runs["config"].map(lambda c: c["C"])
print(runs[["time", "data_sha256", "C", "sklearn", "roc_auc", "baseline_roc_auc"]].to_string(index=False))
time data_sha256 C sklearn roc_auc baseline_roc_auc
2026-12-01T00:07:39+00:00 8379dd217ab5 1.00 1.9.1 0.7617 0.5
2026-12-01T00:07:40+00:00 8379dd217ab5 1.00 1.9.1 0.7617 0.5
2026-12-01T00:07:41+00:00 8379dd217ab5 0.01 1.9.1 0.7613 0.5
Your times will differ. Inside a Git repository, the code field holds the commit ID; outside one, the script records “not in git”, which is itself a warning sign.
When to add a tracking tool
A JSON-lines file is enough for one person and a few hundred runs. When a team shares experiments, wants charts or needs to store model files with their runs, a tracking tool earns its place. MLflow Tracking, for example, describes itself as “an API and UI for logging parameters, code versions, metrics, and output files when running your machine learning code and for later visualizing the results.” The record you built here maps directly onto it: config to parameters, scores to metrics, data hash and commit to tags.
Checklist
- One command rebuilds the data, trains, evaluates and records.
- Two runs in a row give identical results.
- Every record has the data hash, commit, config, library versions, score and baseline.
- Library versions are pinned.
- The model’s version from Module 4 points to the run that produced it.
Project: finish the path
Make your project reproducible end to end: one command that rebuilds the dataset, trains, evaluates against the baseline and records the run. Then connect it to the previous modules: the run produces the versioned model file and record from Module 4, and the retraining rule from Module 5 calls this command. That’s a complete, small production ML system, and a strong portfolio piece.