Sub topic 1
Why experiments need tracking
Prerequisites
This chapter assumes you can:
- Read and write basic Python, including
withblocks (context managers). - Train and evaluate a model with scikit-learn or a similar library.
- Use a terminal and install packages with
pip. - Interpret a train/test split and common metrics such as accuracy.
You don't need to install MLflow yet. The code below uses only scikit-learn and the standard library. The next chapter introduces the MLflow components.
The problem: a good result you cannot repeat
Training a model is an experiment. You change something (a hyperparameter, a feature, a data filter, a random seed), run the code, and look at a number. A project quickly accumulates dozens or hundreds of these runs.
A typical week goes like this:
- On Monday you train a logistic regression and get 0.97 accuracy.
- On Tuesday you tweak the preprocessing and get 0.93.
- On Wednesday a colleague asks which settings produced the 0.97 model.
- You open a notebook that has been re-executed three times since Monday.
The notebook now holds the Tuesday code. The Monday output is gone, and you cannot say whether the 0.97 came from C=1.0 or C=10.0. Nobody remembers whether the split was seeded. The result may be real, but you can't reproduce it, so you can't trust it or build on it.
Experiment tracking addresses this. You record, for every run, enough information to explain and repeat its outcome. You store those records somewhere searchable, so that you can ask questions across runs instead of relying on memory.
What a run needs to record
A run is one execution of your training code. To make it reproducible, you need to capture everything that could have influenced the result. The inputs and outputs fall into these categories:
| Category | Examples | Why it matters |
|---|---|---|
| Code version | Git commit hash, uncommitted changes, entry-point script | The same settings on different code give different results |
| Parameters | `C`, learning rate, number of trees, random seed, split ratio | These are the knobs you turned |
| Data version | File path, row count, a hash of the content, a snapshot ID | Silent changes to data are a common cause of "it worked before" |
| Environment | Python version, library versions, hardware | Library upgrades change defaults and numerical results |
| Metrics | Accuracy, loss per epoch, latency | These are the outcomes you compare |
| Artifacts | Trained model file, confusion matrix plot, feature list, config file | These are the outputs you need to inspect or deploy later |
| Context | Who ran it, when, how long, whether it succeeded, free-form notes | This lets you find and interpret the run later |
Two of these categories are easy to overlook. The first is the data version. Code and parameters sit in your editor, so you tend to remember them. A changed CSV does not announce itself. The second is the environment. Two runs with identical code and parameters can differ because a dependency was upgraded between them.
A hand-rolled tracker
Before using a tool, it helps to see how far a simple approach gets you. The script below trains a model and appends one JSON line to a log file. It records the code version, parameters, a data fingerprint, library versions and a metric.
import hashlib
import json
import platform
import subprocess
import time
import sklearn
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
def git_commit():
try:
return subprocess.check_output(
["git", "rev-parse", "HEAD"], text=True, stderr=subprocess.DEVNULL
).strip()
except (subprocess.CalledProcessError, FileNotFoundError):
return None
params = {"C": 1.0, "max_iter": 200, "test_size": 0.2, "random_state": 42}
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=params["test_size"], random_state=params["random_state"]
)
started = time.time()
model = LogisticRegression(C=params["C"], max_iter=params["max_iter"])
model.fit(X_train, y_train)
accuracy = model.score(X_test, y_test)
record = {
"timestamp": started,
"duration_s": round(time.time() - started, 3),
"git_commit": git_commit(),
"params": params,
"data_sha256": hashlib.sha256(X.tobytes()).hexdigest()[:12],
"python": platform.python_version(),
"sklearn": sklearn.__version__,
"metrics": {"test_accuracy": accuracy},
}
with open("runs.jsonl", "a") as f:
f.write(json.dumps(record) + "\n")
print(record)Every execution appends a line to runs.jsonl. After a few runs, you can open the file and answer the Wednesday question: which parameters produced 0.97?
This approach is a real improvement over memory, and some small projects never need more. It also has limits that appear as the project grows.
Where the hand-rolled approach breaks down
- Every script needs the boilerplate. The record-building code gets copied between scripts, drifts apart, and fields go missing in some runs.
- The log format is yours to maintain. When you add a parameter, old and new lines have different keys. Comparing them takes custom code.
- There is no way to explore it. To find the best run, sort by metric, or plot loss over epochs, you write analysis scripts. You will rewrite them for each project.
- Artifacts have no home. A model file, a plot or a feature list needs a naming scheme and a directory. Matching
model_final_v2.pklto a log line is a manual step that people get wrong. - Shared access is awkward. A file on your laptop isn't visible to a teammate. Two people appending to a shared file can corrupt it or overwrite each other's work.
- Per-step metrics don't fit. A training curve with hundreds of points per run doesn't fit well in one JSON line, and plotting it needs more code.
- Nothing links a run to the model you deployed. When a model misbehaves in production, you want to trace it to the exact run that produced it.
A tracking system exists to solve these problems once, so you don't solve them in every project.
What a tracking system provides
An experiment tracking system gives you five things:
- A standard record. Each run has the same structure: parameters, metrics, tags, artifacts, timestamps, status and source information. You log into it through a small API.
- Central storage. Records go to a shared store, not to files scattered over machines. Several people and jobs can write at once.
- A way to compare. You can view runs side by side, sort and filter them, and plot metrics.
- A way to query. You can ask questions from code, such as "all runs in this experiment with accuracy above 0.9," and get the answer as a table.
- A link to models. Logged models can be versioned and promoted. A production model can be traced back to the run that created it.
MLflow Tracking is one such system. It is open source and works with any Python ML library. It also has a REST API and clients for other languages. It records the data above through explicit logging calls, plus automatic capture for several common libraries (called autologging).
What MLflow records, and what you must supply
You should know early where automatic capture ends. MLflow does some of the work for you, and the rest depends on your logging.
MLflow records some information on its own for every run. This includes start and end times, status, the user, and the source (script or notebook name). It also records the Git commit when the code runs inside a Git repository. It does not record uncommitted changes to the working tree, so a commit hash alone can be misleading if you ran with local edits.
You supply the rest:
- Parameters appear in MLflow only if you log them, either with a call or through autologging.
- Data versions are not captured unless you log something that identifies the data, such as a hash, a path or a snapshot ID.
- Environment details are captured when you log a model, which stores its dependency list alongside it. A run that logs no model has no such list unless you add one.
- Random seeds are ordinary parameters. If you don't log them, the run cannot be reproduced exactly.
Tracking does not make a run reproducible by itself. It makes a run reproducible if you log what matters. Good habits matter as much as the tool, and a later chapter on team conventions covers them.
How tracking changes your workflow
The diagram shows the difference between a run you cannot explain and one that records itself.
The change in practice is small. You wrap your training code in a block that opens a run, and you log the values you already have in your script. For example, the next chapters use code in this shape:
import mlflow
with mlflow.start_run(run_name="logreg-c1"):
mlflow.log_param("C", 1.0)
mlflow.log_metric("test_accuracy", 0.97)You don't need to run this yet because it needs a tracking setup, which the next chapter covers. The point here is that the logging calls take one line each. The run opens and closes with the with block, so the record gets a start time, an end time and a status without extra work.
Edge cases and common mistakes
Tracking has pitfalls that appear even when the tool is in place.
- Tracking only the winners. If you log only runs you consider good, you lose the failures. Failed and mediocre runs show which directions you already tried, and they stop others from repeating them. Log everything, and filter later.
- Logging results but not inputs. A table of accuracies without parameters tells you what scored well and not why. Always log the settings with the outcome.
- Evaluating on the test set during tuning. If you pick the best run by test accuracy among hundreds of runs, the test score becomes optimistic. Tracking makes this easy to do by accident. Log a validation metric for selection and keep a final test metric for the chosen run.
- Non-determinism. Some algorithms, GPU operations and multi-threaded libraries give slightly different results even with a fixed seed. A tracked run explains how a result was produced, but it can't promise a bit-for-bit repeat. Log the seed and note the hardware, and expect small differences.
- Mutable data behind a stable name. If
train.csvis overwritten in place, the same path means different data on different days. Record a content hash or a snapshot ID, not only the path. - Secrets in parameters. Parameters and tags are visible to everyone with access to the store. Never log API keys, passwords or personal data.
- Inconsistent names.
learning_rate,lrandLRbecome three separate columns when you compare runs. Choose one name per concept and keep it.
What the rest of the tutorial covers
The chapters that follow build up the full workflow. You will see how the client, tracking server, backend store and artifact store fit together, and how experiments group runs. You will log parameters, metrics, tags and artifacts, then use autologging and learn what it leaves out. You will compare runs in the UI and with search_runs, log models with signatures, use nested runs for hyperparameter search, register models with aliases, and adopt team conventions.
Summary
Untracked experiments can't be reproduced because the settings, data and code that produced a result live in memory and in notebooks that change. A reproducible run records its code version, parameters, data version, environment, metrics and artifacts. A hand-rolled JSON log covers the basics, but it doesn't scale to comparison, shared access, artifacts or model traceability. MLflow Tracking provides a standard record, central storage, comparison, querying and a link to models. It captures some context automatically, and you must log the rest yourself.
Exercise
A teammate says: "We log every run's test accuracy to MLflow, so all our results are reproducible." Give two things that could still prevent a run from being reproduced, and say what you would log to fix each.
Show answer
Any two of the following. (1) Missing parameters or seeds: log all hyperparameters and the random seed, for example with mlflow.log_param. (2) Unversioned data: log a content hash, snapshot ID or exact path of the dataset as a parameter or tag, so you know which data the run saw. (3) Uncommitted code changes: MLflow records the Git commit but not local edits, so commit before running or log the diff as an artifact. (4) Unrecorded environment: log the model, which stores its dependency list, or log the library versions explicitly. Logging accuracy alone shows the outcome without the inputs that produced it.
Exercise
In the hand-rolled script, the data fingerprint is hashlib.sha256(X.tobytes()).hexdigest()[:12]. Why is this more useful than logging only the file name of the dataset?
Show answer
A file name stays the same when the file's content changes. The hash changes whenever the data changes, so two runs with the same name but different hashes show that they saw different data. Comparing hashes tells you whether a difference in results could come from the data.
Exercise
You run 300 experiments and choose the run with the highest test accuracy as your final model. Why might its reported accuracy be too optimistic, and how would you change what you log?
Show answer
Selecting the maximum over many runs on the same test set fits your choice to that set's noise, so the best score overstates how the model will perform on new data. Log a validation metric during tuning and use it to select the run. Then evaluate the chosen run once on the held-out test set and log that as a separate metric.