Lab: Track and Compare Runs
Track gradient-boosting runs in MLflow with a local SQLite store: log parameters, a validation-loss curve with steps, a confusion-matrix artifact, the training data digest and a code version, run a six-run sweep, compare the runs with search_runs, select one on validation data and score it on the test set exactly once.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: A local store and a fixed split
- Step 2: Log one run and read it back
- Step 3: Run a small sweep
- Step 4: Compare runs and select on validation
- Step 5: Score the selected run on the test set, once
- Check your understanding
- Apply it
- Review prompt
Lessons of Experiment Tracking & Reproducibility
- Why Results Become Unrepeatable Concept · 15 min
- Lab: Track and Compare Runs Lab · 25 min
- Versioning Data and Models Next to Code Concept · 20 min
- Worked Example: Rebuild Last Month's Model from Scratch Worked example · 25 min
- Model Registry: Versions, Aliases and Promotion Rules Concept · 15 min
- Check: Can You Reproduce It? Knowledge check · 8 questions
What you will learn
- Log parameters, metrics, artifacts and the code version of training runs to an experiment tracker such as MLflow, and compare runs to select a model.
01. Goal and setup
An experiment tracker is a database of training runs. For each run, one execution of your training code, it stores what went in and what came out, so that weeks later you can still answer "which settings gave this number, on which data, with which code?". In this lab you use MLflow, a widely used open-source tracker, to record a small hyperparameter sweep and choose a model from it.
MLflow sorts what you log into kinds, and the difference matters when you compare runs. Parameters are inputs you chose before training, such as the learning rate; each is logged once per run. Metrics are numbers that training produces; a metric can be logged many times with a step, so you get a curve instead of a single value. Artifacts are files, such as a confusion matrix, a plot or the model itself. Tags are free-form labels; you will use them for the code version and to mark the chosen run.
You need: Python 3.12, MLflow 3.18 and scikit-learn 1.9. Everything stays in one folder: runs, parameters and metrics go to a SQLite file, mlflow.db, and artifact files go to mlartifacts/. No server is needed. The model is gradient boosting on the breast cancer dataset that ships with scikit-learn, and every seed is fixed, so your numbers should match the expected output.
tracking-lab/
├── tracking.py step 1: where MLflow stores runs, quieter logs
├── data.py step 1: one fixed train / validation / test split
├── train.py step 2: one tracked run
├── sweep.py step 3: six runs over a small grid
├── compare.py step 4: query the runs, select on validation
├── test_once.py step 5: one test-set score for the selected run
├── mlflow.db created: runs, parameters, metrics, tags
└── mlartifacts/ created: artifact files and logged modelsmkdir tracking-lab && cd tracking-lab
python3.12 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install "mlflow==3.18.0" "scikit-learn==1.9.1"02. Step 1: A local store and a fixed split
tracking.py points MLflow at the SQLite file with a tracking URI, sqlite:///mlflow.db. It creates the experiment (a named group of runs) once, with its artifact location inside the lab folder. It also turns MLflow's own log lines down to warnings and silences one hint about integer columns that does not apply here, so that the output shows only what the scripts print.
data.py makes one split, 60% train, 20% validation and 20% test, with a fixed seed. Every run uses the same split. If each run drew its own split, a better score could just mean an easier validation set.
"""Point MLflow at a store inside this folder and keep its own log lines quiet."""
import logging
import os
import warnings
from pathlib import Path
os.environ.setdefault("MLFLOW_ENABLE_ARTIFACTS_PROGRESS_BAR", "false")
import mlflow # noqa: E402
EXPERIMENT = "cancer-gbm"
def setup():
logging.getLogger("mlflow").setLevel(logging.WARNING)
warnings.filterwarnings("ignore", message="Hint: Inferred schema contains integer")
mlflow.set_tracking_uri("sqlite:///mlflow.db") # runs, params, metrics
if mlflow.get_experiment_by_name(EXPERIMENT) is None:
artifacts = Path("mlartifacts").resolve().as_uri() # files, next to the db
mlflow.create_experiment(EXPERIMENT, artifact_location=artifacts)
mlflow.set_experiment(EXPERIMENT)"""One fixed split, used by every run: 60% train, 20% validation, 20% test."""
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
SPLIT_SEED = 0
def splits():
df = load_breast_cancer(as_frame=True).frame # 569 rows, 30 features
rest, test = train_test_split(df, test_size=0.2, stratify=df["target"],
random_state=SPLIT_SEED)
train, val = train_test_split(rest, test_size=0.25, stratify=rest["target"],
random_state=SPLIT_SEED)
return train, val, test
def xy(df):
return df.drop(columns="target"), df["target"]python -c "from data import splits; print([len(d) for d in splits()])"[341, 114, 114]03. Step 2: Log one run and read it back
train() opens a run with with mlflow.start_run(...), which also closes it when the block ends, even after an error. Inside it logs each kind of record:
- the four parameters with
log_params, including the seed; - the code version as tags. A results table is only useful if you know which code produced each row.
code_sha256is a hash of the training source files, so it changes whenever the code does. In a Git repository the function also records the commit and whether uncommitted changes were present (code_dirty), because a commit does not describe edits that were never committed; - the training data with
log_input. MLflow computes a digest, a short hash of the data's content, and links it to the run; val_log_lossevery 10 trees withstep=trees, usingstaged_predict_proba, which gives the predictions of the model after each tree;- final
val_aucandtrain_auc, a confusion matrix as a JSON artifact, and the model itself withmlflow.sklearn.log_model.
The script then reads the run back from the store, as any later script or teammate would.
import hashlib
import json
import subprocess
import sys
from pathlib import Path
import mlflow
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import confusion_matrix, log_loss, roc_auc_score
from data import splits, xy
from tracking import setup
def code_version():
"""A hash of the training source, plus the Git commit when there is one."""
source = b"".join(Path(f).read_bytes() for f in ("train.py", "data.py"))
tags = {"code_sha256": hashlib.sha256(source).hexdigest()[:12]}
git = ["git", "-C", str(Path(__file__).parent)]
try:
commit = subprocess.run(git + ["rev-parse", "HEAD"], capture_output=True,
text=True, check=True).stdout.strip()
changed = subprocess.run(git + ["status", "--porcelain", "-uno"],
capture_output=True, text=True, check=True).stdout
tags.update(code_commit=commit, code_dirty=str(bool(changed)).lower())
except (OSError, subprocess.CalledProcessError):
pass # not a Git repository: hash only
return tags
def train(learning_rate, max_depth, n_estimators=150, seed=0):
train_df, val_df, _ = splits()
X_tr, y_tr = xy(train_df)
X_val, y_val = xy(val_df)
params = {"learning_rate": learning_rate, "max_depth": max_depth,
"n_estimators": n_estimators, "seed": seed}
with mlflow.start_run(run_name=f"lr{learning_rate}-depth{max_depth}") as run:
mlflow.log_params(params) # the inputs you chose
mlflow.set_tags(code_version()) # which code ran
dataset = mlflow.data.from_pandas(train_df, name="cancer-train",
targets="target")
mlflow.log_input(dataset, context="training") # which data, by digest
model = GradientBoostingClassifier(
learning_rate=learning_rate, max_depth=max_depth,
n_estimators=n_estimators, random_state=seed).fit(X_tr, y_tr)
# one value every 10 trees: a curve, not only a final number
for trees, proba in enumerate(model.staged_predict_proba(X_val), start=1):
if trees % 10 == 0:
mlflow.log_metric("val_log_loss", log_loss(y_val, proba), step=trees)
p_val = model.predict_proba(X_val)[:, 1]
p_tr = model.predict_proba(X_tr)[:, 1]
mlflow.log_metrics({"val_auc": roc_auc_score(y_val, p_val),
"train_auc": roc_auc_score(y_tr, p_tr)})
cm = confusion_matrix(y_val, (p_val >= 0.5).astype(int)).tolist()
mlflow.log_dict({"labels": [0, 1], "matrix": cm}, "confusion_val.json")
mlflow.sklearn.log_model(
model, name="model",
pip_requirements=["scikit-learn==1.9.1", "skops"],
skops_trusted_types=["sklearn.tree._tree.Tree"])
return run.info.run_id
if __name__ == "__main__":
setup()
run_id = train(float(sys.argv[1]), int(sys.argv[2]))
client = mlflow.MlflowClient()
run = client.get_run(run_id)
print("params:", json.dumps(run.data.params, sort_keys=True))
print("tags:", {k: v for k, v in run.data.tags.items() if k.startswith("code_")})
print("val_auc:", round(run.data.metrics["val_auc"], 4))
history = client.get_metric_history(run_id, "val_log_loss")
print("val_log_loss at steps 10, 50, 100, 150:",
[round(m.value, 3) for m in history if m.step in (10, 50, 100, 150)])
print("dataset:", [(d.dataset.name, d.dataset.digest)
for d in run.inputs.dataset_inputs])
print("artifacts:", [a.path for a in client.list_artifacts(run_id)])python train.py 0.1 3params: {"learning_rate": "0.1", "max_depth": "3", "n_estimators": "150", "seed": "0"}
tags: {'code_sha256': '4c929511b05f'}
val_auc: 0.9941
val_log_loss at steps 10, 50, 100, 150: [0.253, 0.098, 0.123, 0.147]
dataset: [('cancer-train', '73e7de66')]
artifacts: ['confusion_val.json']Parameters come back as strings: MLflow stores them as text, so convert them before doing arithmetic. The tags hold only code_sha256 because this folder is not a Git repository; if it is one on your machine, you will also see code_commit and code_dirty, and MLflow adds its own mlflow.source.git.commit tag. The hash will also differ if you changed a single character of train.py or data.py, which is exactly its job.
The curve is the reason to log with steps. Validation log loss falls to 0.098 at 50 trees and then rises to 0.147 at 150, while training AUC is 1.0: after about 50 trees, this model fits noise in the training rows. A single final metric would have hidden that. The artifact list shows only confusion_val.json because MLflow 3 stores a logged model as its own entity, linked to the run; you load it with runs:/<run_id>/model in step 5.
04. Step 3: Run a small sweep
A sweep trains the same code with several settings. This one tries three learning rates and two tree depths, six runs, in one process, which saves importing MLflow six times. Each run gets a readable name from its settings, but MLflow identifies it by a random run ID, so two runs can share a name.
import itertools
import mlflow
from tracking import setup
from train import train
setup()
for lr, depth in itertools.product([0.03, 0.1, 0.3], [1, 3]):
run_id = train(lr, depth)
metrics = mlflow.get_run(run_id).data.metrics
print(f"lr {lr:<4} depth {depth} val_auc {metrics['val_auc']:.4f} "
f"final val_log_loss {metrics['val_log_loss']:.3f}")python sweep.pylr 0.03 depth 1 val_auc 0.9925 final val_log_loss 0.137
lr 0.03 depth 3 val_auc 0.9948 final val_log_loss 0.085
lr 0.1 depth 1 val_auc 0.9938 final val_log_loss 0.113
lr 0.1 depth 3 val_auc 0.9941 final val_log_loss 0.147
lr 0.3 depth 1 val_auc 0.9921 final val_log_loss 0.154
lr 0.3 depth 3 val_auc 0.9948 final val_log_loss 0.272When a metric is logged with steps, run.data.metrics holds its latest value, here the loss after 150 trees. The full curve stays available through get_metric_history.
05. Step 4: Compare runs and select on validation
mlflow.search_runs returns runs as a pandas DataFrame, with columns named params.…, metrics.… and tags.…. You can filter (filter_string) and sort (order_by) in the query, the same way the MLflow UI does. The choice of metric matters. AUC measures only how well the model ranks positive cases above negative ones. Log loss also scores the probabilities, and punishes confident wrong ones heavily. The script sorts by validation log loss and records the choice as a selected tag, so the decision itself is part of the record.
The test set is not used here. Choosing among runs is itself a kind of fitting: with enough runs, one will look good on any fixed set partly by luck. That is why you choose on validation and keep the test set for one final, unbiased estimate.
import mlflow
from tracking import EXPERIMENT, setup
setup()
runs = mlflow.search_runs(
experiment_names=[EXPERIMENT],
filter_string="attributes.status = 'FINISHED'",
order_by=["metrics.val_log_loss ASC"],
)
cols = ["tags.mlflow.runName", "params.learning_rate", "params.max_depth",
"metrics.val_auc", "metrics.val_log_loss", "metrics.train_auc"]
table = runs[cols].rename(columns=lambda c: c.split(".")[-1]).round(4)
print(f"{len(runs)} runs, lowest validation log loss first:")
print(table.to_string(index=False))
best = runs.iloc[0]
client = mlflow.MlflowClient()
client.set_tag(best.run_id, "selected", "true") # the choice is recorded too
history = client.get_metric_history(best.run_id, "val_log_loss")
low = min(history, key=lambda m: m.value)
print(f"selected: {best['tags.mlflow.runName']}")
print(f"its val_log_loss is lowest at step {low.step}: {low.value:.3f}")python compare.py7 runs, lowest validation log loss first:
runName learning_rate max_depth val_auc val_log_loss train_auc
lr0.03-depth3 0.03 3 0.9948 0.0849 1.0000
lr0.1-depth1 0.1 1 0.9938 0.1128 1.0000
lr0.03-depth1 0.03 1 0.9925 0.1375 0.9976
lr0.1-depth3 0.1 3 0.9941 0.1469 1.0000
lr0.1-depth3 0.1 3 0.9941 0.1469 1.0000
lr0.3-depth1 0.3 1 0.9921 0.1536 1.0000
lr0.3-depth3 0.3 3 0.9948 0.2724 1.0000
selected: lr0.03-depth3
its val_log_loss is lowest at step 150: 0.085There are seven runs: the six from the sweep and the one from step 2. Those two lr0.1-depth3 rows have identical numbers, because the same code, data, parameters and seed ran twice.
Two runs tie on validation AUC at 0.9948, yet their log losses are 0.085 and 0.272. Both rank the validation rows equally well, but the lr0.3 model is far more overconfident when it is wrong. The selected run, lr0.03-depth3, still has its lowest loss at the last step, 150, so its curve suggests that more trees could help; that would be the next sweep.
06. Step 5: Score the selected run on the test set, once
test_once.py finds the run tagged selected, loads its logged model, scores the 114 test rows and adds test_auc to the same run with start_run(run_id=...). Before doing so, it checks whether that run already has a test score and stops if it does. The rule is easy to say and easy to break by accident: once you have looked at a test score, any further tuning based on it turns the test set into a second validation set.
import mlflow
from sklearn.metrics import roc_auc_score
from data import splits, xy
from tracking import EXPERIMENT, setup
setup()
chosen = mlflow.search_runs(experiment_names=[EXPERIMENT],
filter_string="tags.selected = 'true'")
assert len(chosen) == 1, f"expected one selected run, found {len(chosen)}"
run = chosen.iloc[0]
if "metrics.test_auc" in chosen.columns and chosen["metrics.test_auc"].notna().any():
raise SystemExit("this run already has a test score: report it, do not retest")
model = mlflow.sklearn.load_model(f"runs:/{run.run_id}/model")
X_test, y_test = xy(splits()[2])
test_auc = roc_auc_score(y_test, model.predict_proba(X_test)[:, 1])
with mlflow.start_run(run_id=run.run_id): # add to the same run
mlflow.log_metric("test_auc", test_auc)
print(f"{run['tags.mlflow.runName']}: val_auc {run['metrics.val_auc']:.4f}, "
f"test_auc {test_auc:.4f} on {len(y_test)} test rows")python test_once.pylr0.03-depth3: val_auc 0.9948, test_auc 0.9742 on 114 test rowspython test_once.pythis run already has a test score: report it, do not retestThe test AUC, 0.9742, is lower than the validation AUC of 0.9948. Some drop is expected: the selected run won on validation partly because of how those particular 114 rows fell, and the test set removes that advantage. With only 114 test rows, treat it as one estimate, not a precise value. The second call refuses to score again, as intended.
To browse the same runs in a browser, start the MLflow UI on the same store. It reads mlflow.db and shows the parameters, the metric curves and the artifacts of each run.
mlflow ui --backend-store-uri sqlite:///mlflow.db --port 5000
# then open http://127.0.0.1:5000 and stop the server with Ctrl+C07. Check your understanding
08. Apply it
In the practice project, add tracking to your own training script.
- Log every hyperparameter and the seed as parameters, the training curve as a metric with steps, and at least one diagnostic file as an artifact.
- Record the code version: the Git commit and a dirty flag, as in
code_version(). Log the training data withlog_input, or log its content hash as a tag. - Run a sweep of at least six settings, choose one with
search_runson validation data, tag it, and score it on the test set once. - Extend the grid with more trees for the selected learning rate, and check whether the curve flattens.
09. Review prompt
Without looking back, define a run, a parameter, a metric with steps, an artifact and a tag, with one example of each from this lab; explain how code_version() identifies the code when there is no Git repository and what code_dirty adds when there is one; say why every run shares one fixed split; explain why runs are chosen on validation data and the test set is scored once; and say what AUC misses that log loss catches.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.