Experiment Tracking: What to Record
Three weeks into a project, the best model so far had a validation AUC of 0.93. Nobody can rebuild it. The notebook that trained it has been edited since, the data extract was refreshed on Monday, a colleague upgraded scikit-learn, and the learning rate that worked was typed into a cell that no longer exists. This is the normal state of a project without experiment tracking: results without the facts needed to reproduce, compare or trust them. A tracker is a disciplined lab notebook: every training run writes down what went in and what came out, automatically, in a form that can be searched later.
This lesson is about what to record and why; it builds a tracker from scratch in plain Python. The next lesson does the same with MLflow, the most widely used open-source tracker.
The run record
The unit of tracking is a run: one execution of a training script with one configuration. Runs are grouped into experiments (all runs that try to solve the same problem, so that they can be compared). A run record has seven parts:
| Part | Examples | Why it is needed |
|---|---|---|
| Code version | git commit, and a flag if the working tree had uncommitted changes | the same parameters with different code are a different experiment |
| Data version | a content hash of each data set, a DVC version, a table snapshot id, and which rows went to which split | the most common reason a result cannot be reproduced |
| Parameters | hyperparameters, feature list, preprocessing choices, the whole config file | to know what was tried and to rerun it |
| Metrics | training loss per step, validation metrics per epoch, final scores, with the split and sample size | to compare runs; a number without its split is not comparable |
| Artifacts | the model file, plots, predictions on the validation set, a confusion matrix | to inspect and to deploy the exact object that was scored |
| Environment | Python and library versions (a lockfile), OS, CPU/GPU type | library upgrades change results (reproducibility) |
| Seed | every seed used: data split, initialisation, shuffling | without it, the run is one sample from a distribution of runs |
Two rules make the record useful. It is written by the training code, automatically, not by a person afterwards (people forget, round and pick). And failed and bad runs are recorded too: a log that only holds winners hides how many attempts it took, which is exactly what you need to judge whether the winner is real.
From scratch: a JSON-lines tracker
The format can be very simple: one JSON object per run, one run per line of a file (JSON lines, see JSON and JSONL). Appending a line is atomic enough for one machine, the file can be read with any tool, and a run that crashes still writes its record with status: failed because the record is written in __exit__. Artifacts are stored under their SHA-256 hash (content-addressed), so the record names the exact bytes, and two runs that produce the same file share it.
The example tunes the regularisation strength C of the course's running example, a StandardScaler + LogisticRegression pipeline on 2,000 synthetic rows with 8 features. The data is split once: 500 rows of test data are put aside and not touched, the remaining 1,500 are split into 1,200 for fitting and 300 for validation, and every run is scored on the validation rows only.
import hashlib, json, os, platform, subprocess, tempfile, uuid
import numpy as np, sklearn
import pandas as pd
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, accuracy_score
def code_version():
"""The commit the code ran from; say so explicitly when it is unknown."""
try:
out = subprocess.run(["git", "rev-parse", "--short", "HEAD"], capture_output=True, text=True)
return out.stdout.strip() or "unknown"
except Exception:
return "unknown (no git here)"
def fingerprint(*arrays):
h = hashlib.sha256()
for a in arrays:
h.update(np.ascontiguousarray(a).tobytes())
return h.hexdigest()[:12]
class Run:
def __init__(self, store, name):
self.store, self.rec = store, {"run_id": uuid.uuid4().hex, "name": name, "params": {},
"metrics": {}, "artifacts": {}, "tags": {}}
def log_params(self, **p):
self.rec["params"].update(p)
def log_metric(self, key, value, step=None):
self.rec["metrics"].setdefault(key, []).append({"step": step, "value": round(float(value), 4)})
def log_artifact(self, name, data: bytes):
digest = hashlib.sha256(data).hexdigest()
with open(os.path.join(self.store.root, digest), "wb") as f: # content-addressed: same bytes, same file
f.write(data)
self.rec["artifacts"][name] = digest[:12]
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
self.rec["status"] = "failed" if exc_type else "finished" # failed runs are recorded too
with open(self.store.path, "a") as f:
f.write(json.dumps(self.rec) + "\n") # one JSON object per line
return False
class Tracker:
def __init__(self, root):
self.root, self.path = root, os.path.join(root, "runs.jsonl")
def start_run(self, name, **tags):
run = Run(self, name)
run.rec["tags"].update(tags)
run.rec["code_version"] = code_version()
run.rec["environment"] = {"python": platform.python_version(), "numpy": np.__version__,
"scikit-learn": sklearn.__version__}
return run
def runs(self):
with open(self.path) as f:
return [json.loads(line) for line in f]
X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)
X_dev, X_test, y_dev, y_test = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)
X_fit, X_val, y_fit, y_val = train_test_split(X_dev, y_dev, test_size=0.2, stratify=y_dev, random_state=0)
data_version = fingerprint(X_fit, y_fit, X_val, y_val)
tracker = Tracker(tempfile.mkdtemp())
for C in (0.001, 0.01, 0.1, 1.0):
with tracker.start_run(f"logreg-C{C}", author="ana", purpose="tune C") as run:
seed = 0
run.log_params(model="LogisticRegression", C=C, scaler="StandardScaler", seed=seed,
data_version=data_version, n_fit=len(y_fit), n_val=len(y_val))
model = make_pipeline(StandardScaler(), LogisticRegression(C=C, random_state=seed)).fit(X_fit, y_fit)
p = model.predict_proba(X_val)[:, 1]
run.log_metric("val_auc", roc_auc_score(y_val, p))
run.log_metric("val_accuracy", accuracy_score(y_val, p > 0.5))
coef = model[-1].coef_.round(6)
run.log_artifact("coefficients.json", json.dumps(coef.tolist()).encode())
runs = tracker.runs()
print(f"{len(runs)} runs in runs.jsonl; record keys: {sorted(runs[0])}")
print(f"code_version: {runs[0]['code_version']!r}, data_version: {runs[0]['params']['data_version']}")
print(f"environment keys: {sorted(runs[0]['environment'])}")
table = pd.DataFrame([{"name": r["name"], "C": r["params"]["C"],
"val_auc": r["metrics"]["val_auc"][-1]["value"],
"val_accuracy": r["metrics"]["val_accuracy"][-1]["value"],
"coefficients": r["artifacts"]["coefficients.json"]} for r in runs])
print(table.sort_values("val_auc", ascending=False).to_string(index=False))4 runs in runs.jsonl; record keys: ['artifacts', 'code_version', 'environment', 'metrics', 'name', 'params', 'run_id', 'status', 'tags']
code_version: 'unknown (no git here)', data_version: cec5ca7719cc
environment keys: ['numpy', 'python', 'scikit-learn']
name C val_auc val_accuracy coefficients
logreg-C0.1 0.100 0.9191 0.8467 ac2bd7b7aab3
logreg-C1.0 1.000 0.9190 0.8433 dcbbf8d1509c
logreg-C0.01 0.010 0.9154 0.8333 578ffe03c4d3
logreg-C0.001 0.001 0.8973 0.8033 228aab353fea
Every run carries the same data fingerprint cec5ca7719cc, so the four runs are comparable: they saw the same rows. C = 0.1 and C = 1.0 are tied on validation AUC (0.9191 against 0.9190, a difference far below the noise of 300 validation rows), and C = 0.001 is clearly too strong (0.8973). Each run's coefficients went to a different artifact hash, so the four models are distinguishable even if someone renames the runs later.
Two details matter. The code version is 'unknown (no git here)': the browser has no git, and the tracker says so instead of leaving the field out. A field that silently disappears looks like "nothing to record"; a field that says "unknown" is a warning that this run cannot be traced to code. In a real project, a tracker also records whether git status showed uncommitted changes, because a commit id plus local edits is not a version. And the test rows are not used at all: they are for the one final estimate, after the choice is made.
Comparing runs
The point of a record is the question it answers later: why is today's model better than last week's? The answer is a diff of two records, ignoring the fields that always differ (run id, name).
import json
def flatten(d, prefix=""):
out = {}
for k, v in d.items():
key = f"{prefix}{k}"
if isinstance(v, dict):
out.update(flatten(v, key + "."))
else:
out[key] = v
return out
def diff_runs(a, b, ignore=("run_id", "name")):
fa, fb = flatten(a), flatten(b)
keys = sorted(set(fa) | set(fb))
return [(k, fa.get(k, "-"), fb.get(k, "-")) for k in keys
if k.split(".")[0] not in ignore and fa.get(k) != fb.get(k)]
# two lines from a runs.jsonl: last week's model and today's, which scores better
last_week = json.loads('{"run_id": "4f1c", "name": "baseline", "code_version": "9e2d41a", '
'"params": {"C": 0.1, "seed": 0, "data_version": "a41f0c9b2e77", "features": 8}, '
'"environment": {"scikit-learn": "1.6.1", "numpy": "2.2.5"}, '
'"metrics": {"val_auc": 0.912}}')
today = json.loads('{"run_id": "77b0", "name": "baseline-rerun", "code_version": "c03aa18", '
'"params": {"C": 0.1, "seed": 0, "data_version": "d5e81f3a0c42", "features": 8}, '
'"environment": {"scikit-learn": "1.7.0", "numpy": "2.2.5"}, '
'"metrics": {"val_auc": 0.931}}')
print(f"{'field':26} {'last week':>14} {'today':>14}")
for key, va, vb in diff_runs(last_week, today):
print(f"{key:26} {str(va):>14} {str(vb):>14}")field last week today
code_version 9e2d41a c03aa18
environment.scikit-learn 1.6.1 1.7.0
metrics.val_auc 0.912 0.931
params.data_version a41f0c9b2e77 d5e81f3a0c42
The two runs (hand-written records here, as they would be read from a runs.jsonl) have the same parameters and seed, but three things changed besides the score: the code (9e2d41a to c03aa18), the data (a new fingerprint) and the scikit-learn version (1.6.1 to 1.7.0). The improvement from 0.912 to 0.931 could come from any of them, or from a different validation set inside the new data. Without the record, the team would credit whatever change they remember making. With it, the next step is clear: rerun the old code on the new data (or the new code on the old data) to separate the causes. Changing one thing per run makes such diffs short.
Trackers add a user interface on top of this: tables of runs filtered by tags or parameters, sorted by a metric, metric-against-step charts of several runs on one plot, and parallel-coordinate plots of parameters against a score. The data underneath is the same record.
The pitfall that tracking makes visible: tuning on the test set
A tracker records every run's scores. If the test score is among them and you pick the best run by it, the test set has become a validation set, and its score is now optimistically biased: out of many runs, the one that happened to fit the test rows' noise best wins. The example runs 60 configurations (random feature subsets and C values) on a noisy synthetic problem, with 300 rows to fit, 200 to validate, 200 to test, and 2,300 rows of "new data" playing the role of the future.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
X, y = make_classification(n_samples=3000, n_features=20, n_informative=4, flip_y=0.1, random_state=1)
X_fit, X_rest, y_fit, y_rest = train_test_split(X, y, train_size=300, random_state=0)
X_val, X_rest, y_val, y_rest = train_test_split(X_rest, y_rest, train_size=200, random_state=0)
X_test, X_new, y_test, y_new = train_test_split(X_rest, y_rest, train_size=200, random_state=0)
rng = np.random.default_rng(0)
runs = []
for i in range(60): # 60 tracked runs: random feature subsets and C values
cols = np.sort(rng.choice(20, size=rng.integers(3, 12), replace=False))
C = float(10 ** rng.uniform(-3, 1))
m = LogisticRegression(C=C).fit(X_fit[:, cols], y_fit)
score = lambda Xs, ys: accuracy_score(ys, m.predict(Xs[:, cols]))
runs.append({"val": score(X_val, y_val), "test": score(X_test, y_test), "new": score(X_new, y_new)})
by_test = max(runs, key=lambda r: r["test"])
by_val = max(runs, key=lambda r: r["val"])
print(f"splits: fit {len(y_fit)}, validation {len(y_val)}, test {len(y_test)}, new data {len(y_new)}")
print(f"picked by test score: test {by_test['test']:.3f} -> new data {by_test['new']:.3f}")
print(f"picked by validation score: val {by_val['val']:.3f}, test {by_val['test']:.3f} -> new data {by_val['new']:.3f}")splits: fit 300, validation 200, test 200, new data 2300
picked by test score: test 0.830 -> new data 0.777
picked by validation score: val 0.785, test 0.810 -> new data 0.789
The run picked by its test score reports 0.830 on test but gets 0.777 on new data: an overestimate of more than 5 points, caused only by choosing among 60 runs with the same 200 rows. The run picked by validation score is a better model on new data (0.789), and its test score (0.810), which played no part in the choice, is a fairer estimate, though still noisy with 200 rows. Its validation score (0.785) was used for the choice, so in general it is optimistic too (here it happens to land close to the new-data score); that is why an untouched test set exists. The rule: choose on validation (or cross-validation), report test once. A tracker can enforce it by logging test metrics only from a separate, final evaluation run, and by recording how many runs preceded the choice (data leakage has other routes to the same problem).
Pitfalls
- Untracked notebook state. A notebook runs cells in any order; a variable set in a deleted cell, a scaler refitted twice, or a data frame filtered in place can all shape the result, and none of them is in the code at the commit. Track runs from scripts (or from a notebook restarted and run top to bottom), and make the training entry point a function of its config.
- Logging only the final number. Per-step training and validation curves show overfitting, instability and divergence that a final score hides.
- Metrics without their split and size. "AUC 0.93" from 300 validation rows and "AUC 0.93" from 50,000 test rows are different claims. Log
n_valand the split definition with the metric. - Data by name, not by content.
train.csvis a name; last month's and this month's file share it. Record a hash or a version id (Versioning Data and Models with DVC). - Deleting bad runs. It hides how many configurations were tried and makes the winner look more convincing than it is.
- Secrets and personal data in parameters. Config dumps can contain database passwords or rows of customer data; filter them before logging.
Practice
- A run record has the parameters, the metrics and the model file, but no data version. Name two ways the model could be impossible to reproduce.
- In the 60-run experiment, why is the test score of the run picked by test (0.830) higher than its score on new data (0.777), while the run picked by validation shows a smaller gap?
- Your tracker shows that a run's
val_aucjumped from 0.88 to 0.93 between two runs whose diff is onlyenvironment.scikit-learn. What do you do before believing the improvement?
Answers
- The data file may have been overwritten or refreshed (same name, different rows), or the split may have changed (a different set of rows in validation). Either way, rerunning the same code with the same parameters trains on different data.
- The test score was used to choose among 60 runs, so the winner is partly the run whose errors happened to fall outside those 200 test rows; that luck does not carry over to new data. The validation-picked run was scored on test after the choice, so its test score has no selection bias (only ordinary sampling noise).
- Read the library's changelog for changed defaults (solver, regularisation, tolerance), rerun both versions with several seeds to see whether 0.05 is beyond the run-to-run spread, and check that the validation data really is identical (same data version). A library upgrade should not improve a model by luck; if it changed a default, set that parameter explicitly and record it.
Test yourself
Which field of a run record is most often missing when a result cannot be reproduced?
- The run name
- The data version (content hash or version id of the data and splits)
- The plot colours
- The author
Why does the from-scratch tracker write the record in __exit__?
- It is faster
- So that runs that raise an exception are recorded too, with status failed
- JSON cannot be written earlier
- To avoid storing artifacts
Out of 60 runs, the one with the best test score had test accuracy 0.830. On new data it scored 0.777. What happened?
- The new data is corrupt
- Selecting on the test set made its score optimistically biased
- The model was overfitted on the validation set
- Accuracy is the wrong metric
Two runs differ in code version, data version and library version, and the second scores better. What is the right conclusion?
- The code change caused the improvement
- The cause is unknown until runs that change one thing at a time separate the factors
- The library upgrade caused it
- Scores cannot be compared across runs