Sub topic 7
Tracking experiments, parameters and metrics
This chapter assumes you can train and evaluate a supervised model in scikit-learn, write basic Python, and use Git from the command line. It also builds on the previous chapter, which covered reproducible training runs. Here you will record what each run did so you can compare runs and repeat the best one.
Why training runs need a record
Model development is a search. You change a hyperparameter, a feature set, a data snapshot or a random seed, train again, and look at a metric. After twenty runs, notebook cells and file names such as model_final_v3_real.pkl no longer tell you which configuration produced which number.
An experiment tracker is a tool that stores one structured record per training run. Each record answers three questions:
- What went in: parameters, code version, data version and environment.
- What came out: metrics and artifacts such as model files and plots.
- When and by whom: timestamps, user and run status.
The tracker is the link between the reproducibility practices from the previous chapter and the model registry covered later. A registry entry is only trustworthy if you can trace it back to the run that produced it.
What a run record contains
The terms below are used by most trackers. The names here follow MLflow, one widely used open-source tracker.
| Item | What it holds | Example |
|---|---|---|
| Run | One execution of training code | A single `fit` and evaluation |
| Experiment | A named group of related runs | `iris-classifier` |
| Parameter | An input that is fixed for the run | `C = 1.0`, `seed = 42` |
| Metric | A numeric result, optionally logged over steps | `accuracy = 0.97` |
| Artifact | A file produced by the run | Serialized model, confusion matrix image |
| Tag | Free-form label for filtering | `data_version = v12` |
Parameters and metrics differ in one practical way. A parameter is logged once and is not expected to change within a run. A metric can be logged many times with a step number, such as one validation loss per epoch, which gives you a curve.
Logging a first run
The example below trains a logistic regression on the iris dataset. It records the regularization strength C, the seed and the test accuracy in one MLflow run. Install the dependencies with pip install mlflow scikit-learn.
import mlflow
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
SEED = 42
C = 1.0
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=SEED
)
with mlflow.start_run():
model = LogisticRegression(C=C, max_iter=200).fit(X_train, y_train)
accuracy = accuracy_score(y_test, model.predict(X_test))
mlflow.log_param("C", C)
mlflow.log_param("seed", SEED)
mlflow.log_metric("accuracy", accuracy)Running this script creates a local mlruns directory in the current folder. Start the web interface with mlflow ui and open http://127.0.0.1:5000 to see the run listed with its parameters and metric.
Three details are easy to miss:
- The
withblock marks the run as finished when the block exits. If an exception escapes, the run is marked as failed, so crashed runs stay visible instead of silently disappearing. - The seed is logged as a parameter. A number without its seed cannot be reproduced, and two runs that differ only in seed show you how much of a metric difference is noise.
- With no tracking URI set, MLflow writes to the local file system. Teams normally point
MLFLOW_TRACKING_URIat a shared server so everyone's runs land in one place.
Querying runs to compare them
Logging pays off when you can ask questions of the results. mlflow.search_runs returns a pandas DataFrame with one row per run, and parameters and metrics appear as params.<name> and metrics.<name> columns.
import mlflow
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
SEED = 42
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=SEED
)
mlflow.set_experiment("iris-classifier")
for c in [0.01, 0.1, 1.0, 10.0]:
with mlflow.start_run():
model = LogisticRegression(C=c, max_iter=200).fit(X_train, y_train)
accuracy = accuracy_score(y_test, model.predict(X_test))
mlflow.log_param("C", c)
mlflow.log_param("seed", SEED)
mlflow.log_metric("accuracy", accuracy)
runs = mlflow.search_runs(
experiment_names=["iris-classifier"],
order_by=["metrics.accuracy DESC"],
)
print(runs[["params.C", "params.seed", "metrics.accuracy"]].head())The loop creates four runs in one named experiment, and the query sorts them by accuracy. Note that this compares runs on a single test split. A winner picked this way on a small test set may just be the run that got lucky, a point the next chapter on evaluation returns to.
What to log beyond parameters and metrics
A run with only C and accuracy is a start, but it cannot be fully reproduced. Add the following when it matters for your project:
- Code version. The Git commit hash. MLflow records it automatically when you run from a Git repository, but only if the working tree state is meaningful. Uncommitted changes make the hash misleading, so commit before you run experiments you care about.
- Data version. A dataset identifier, content hash or snapshot tag. Without it, a changed table silently changes your results.
- Environment. Package versions or the container image tag.
- Artifacts. The trained model and any evaluation plots, so the run holds the thing it produced.
- Tags. Labels such as
owner,stageordataset_versionto filter runs later.
import subprocess
import mlflow
commit = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip()
with mlflow.start_run():
mlflow.set_tag("git_commit", commit)
mlflow.set_tag("data_version", "customers-2026-11-01")
mlflow.log_param("model_type", "logistic_regression")This snippet must run inside a Git repository, otherwise git rev-parse fails.
Common errors
- Logging too little. Missing seeds, data versions or preprocessing choices make the best run impossible to rebuild. Log every input that can change the result.
- Logging a metric under varying names.
acc,accuracyandtest_accuracyend up as three columns. Agree on names and keep a single evaluation function that logs them. - Mixing validation and test metrics. If you pick the best run by test accuracy, the test set is no longer an unbiased estimate. Log validation metrics for selection and report the test metric once, for the chosen model.
- Comparing runs that used different data. A higher metric on an easier dataset says nothing. Compare only runs that share the same data version and evaluation split.
- Logging secrets. Parameters are stored in plain text and visible to everyone with access. Never log API keys or database passwords.
- Ignoring failed runs. Failed runs show unstable settings, such as divergence at a high learning rate. Keep them when they are informative.
Choosing a tracker
MLflow is one option. Weights & Biases, Neptune and the experiment tracking built into cloud platforms offer similar concepts with different hosting and interface trade-offs. When you choose, check four things: whether you can self-host, how access control works, whether it integrates with your training framework, and how easily you can export your run data if you switch tools. The ideas in this chapter, logging inputs, outputs and versions per run, carry over to all of them.
Exercises
Exercise
You ran 30 experiments and the best one reports accuracy 0.96. A colleague cannot reproduce it. List four things the run record should contain so they can rebuild it.
Show answer
The Git commit hash of the training code, the data version (snapshot ID or content hash), the full set of hyperparameters including the random seed, and the environment (package versions or container image). Preprocessing settings and the evaluation split also qualify.
Exercise
Modify the loop in the comparison example so each run also logs the validation-set size as a parameter and sets a tag called stage with the value tuning. Then write a search_runs call that returns only runs with that tag. What do you gain by filtering on the tag?
Show answer
Inside the with block add mlflow.log_param("n_test", len(y_test)) and mlflow.set_tag("stage", "tuning"). Query with mlflow.search_runs(experiment_names=["iris-classifier"], filter_string="tags.stage = 'tuning'"). Filtering keeps exploratory tuning runs apart from other runs, such as final evaluation runs, so you compare like with like.