Skip to content
Visual explainer 3h to learn 5 steps

Experiment tracking with MLflow: runs, metrics and lineage

Log dataset lineage, split, features, parameters, seeds, metrics and artifacts to MLflow and compare two runs against a baseline.

By Invicly Tech, , in AI and Machine Learning with Python. About 11 minutes to read.

Topic 26 of 34

In short

Experiment tracking means recording everything that produced a model: the data version, the split, the features, the parameters, the random seed, the metrics and the saved files. MLflow is a free, open-source tracker that stores each training attempt as a run you can search and compare. Without it, a good result from last week is often impossible to reproduce or explain.

Think of it like this: A run is a lab notebook page: if the recipe, ingredients and oven temperature are not written down, nobody can bake the same cake again.

Explained simply

When you train a model, you make dozens of small choices: which rows to use, how to split them, which columns become features, which settings the model gets and which random seed starts it. Change any one and the score moves. Experiment tracking is the habit of writing all of these down automatically, every time you train.

MLflow is a free, open-source tool for this. Each training attempt becomes a run. A run stores parameters (your settings), metrics (your scores), inputs (the data you used) and artifacts (files such as the saved model or a chart). Runs live inside an experiment, which is just a folder name for related work.

You can run MLflow entirely on your own laptop. A small local server keeps the runs in a SQLite file and a folder of artifacts, and gives you a web page where you can sort runs by score, filter them and put two side by side.

The most useful run is often the dullest one: the naive baseline. That might be predicting the most common class or last week's value. Logging it on the same split means every new model has to prove it is better than doing almost nothing.

Press Play on a diagram to walk through it one step at a time.

MapWhat one MLflow run records
Run
  • Parameters
    • Model settings such as max_depth
    • Random seed
    • Feature list version
  • Metrics
    • Validation score
    • Baseline score
    • Training time
  • Inputs
    • Dataset name and digest
    • Split version and context
  • Artifacts
    • Saved pipeline
    • Plots and reports
    • Environment file
  • Tags
    • Git commit
    • Author
    • Purpose of the run
CycleThe tracked experiment loop
  1. 1
    Change one thing

    A feature, a setting or the model type

  2. 2
    Run and log

    Params, data version, seed, metrics

  3. 3
    Compare

    Against baseline on the same split

  4. 4
    Decide

    Keep, drop or try another seed

  5. Back to step 1

In depth

Setting up a local tracking server

Install MLflow into a virtual environment with pip install mlflow. Then start a server that stores run data in a SQLite database and files in a local folder. The web UI opens at http://127.0.0.1:5000. In your training code, point MLflow at that address with mlflow.set_tracking_uri and choose an experiment with mlflow.set_experiment, which creates it if it does not exist.

If you skip the server, MLflow writes to a local store in the current folder, which is fine for quick tests but easy to lose or duplicate. A shared server matters as soon as two people, or a laptop and a CI job, train the same model. Everything here is free and runs on a CPU. To clean up, stop the server and delete mlflow.db and the artifact folder.

  • pip install mlflow
  • mlflow server --backend-store-uri sqlite:///mlflow.db --port 5000
  • mlflow.set_tracking_uri("http://127.0.0.1:5000")
  • Stop with Ctrl+C; delete mlflow.db and mlartifacts to reset

Lineage: recording where the data came from

Lineage answers the question: which data and code produced this model? Record four things. The dataset identity: its name, source and a digest, which MLflow computes when you log a dataset with mlflow.log_input. The split: a version label such as v3 and the rule used, for example a time cut-off date or a stratified split with seed 42. The feature set: a version label or the list of column names. The code: the Git commit, which MLflow tags automatically when you run a script inside a Git repository.

With these, anyone can rebuild the exact training set later. Without them, a model that scored well can only be described as 'something I trained in March'.

FlowLineage from raw data to model
  1. 1
    Raw data

    Source, licence, extract date

  2. 2
    Cleaned table

    Dataset name and digest

  3. 3
    Split v3

    Rule, cut-off date, seed

  4. 4
    Features v2

    Column list and transforms

  5. 5
    Run

    Params, metrics, Git commit

  6. 6
    Model artifact

    Linked back to the run

Seeds and what reproducible really means

Many training steps use randomness: shuffling rows, splitting data, initialising weights, picking features in a random forest. Setting random_state=42 in scikit-learn, or seeding NumPy and PyTorch, makes those steps repeat. Log the seed as a parameter.

Even with seeds, results can drift slightly across library versions, operating systems or CPU and GPU hardware, so also log the environment. A stronger habit is to train with three or five different seeds and report the mean and spread. If the candidate beats the baseline by 0.4 points but seed-to-seed spread is 0.6 points, you have not shown a real improvement.

  • Log seed, library versions and Git commit
  • Repeat key runs with several seeds
  • Report mean and standard deviation, not one lucky number

Comparing runs fairly

A comparison is only fair when the runs share the same evaluation data and metric. In the MLflow UI, filter by the split tag, select the runs and click Compare to see parameters and metrics side by side. In code, mlflow.search_runs returns a pandas DataFrame you can sort and filter.

Put the baseline in the same table. A useful summary has one row per run with the split version, the main metric, the gap to the baseline and the seed spread. Keep the test set out of this loop: choose models on validation scores, then evaluate the single winner on the test set once and log that as a separate, clearly named metric.

Learn it in 5 short steps

About 35m each. Track them with a timer in your plan.

  1. 1
    Start a local tracking server~35m
  2. 2
    Log parameters, seeds and metrics~35m
  3. 3
    Record dataset and split versions~35m
  4. 4
    Store artifacts with each run~35m
  5. 5
    Compare runs against the baseline~35m

Key points

  • Log the data version and split, not only the model settings; most surprises come from the data.
  • Fix and log the random seed so a rerun gives the same numbers.
  • Always log the naive baseline as its own run so every candidate has something to beat.
  • Store the trained pipeline and evaluation plots as artifacts of the run that made them.
  • Compare runs on the same split and metric; a different test set makes the comparison meaningless.

Key terms

Tap a card to flip it. 0/6 known

Examples

python
import mlflow
import mlflow.data
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score

mlflow.set_tracking_uri("http://127.0.0.1:5000")
mlflow.set_experiment("churn")
with mlflow.start_run(run_name="logreg-c1"):
    mlflow.log_params({"C": 1.0, "seed": 42, "split": "v3"})
    mlflow.log_input(mlflow.data.from_pandas(train_df, name="churn-train-v3"), context="training")
    model = LogisticRegression(C=1.0, random_state=42).fit(X_train, y_train)
    mlflow.log_metric("val_f1", f1_score(y_val, model.predict(X_val)))
    mlflow.sklearn.log_model(model, name="model")

One run that logs parameters, the training data, a metric and the model.

Logging a baseline and a candidate on the same split

You predict customer churn on a synthetic table. Step 1: log a DummyClassifier that always predicts the majority class; it gets F1 of 0 for the churn class, which is the floor. Step 2: log a logistic regression with the same split tag and seed. Step 3: open the UI, filter on split = v3 and compare. The candidate is worth keeping only if it clearly beats the baseline and the gap is larger than the seed spread.

python
import mlflow
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score

mlflow.set_experiment("churn")
for name, model in [("baseline", DummyClassifier(strategy="most_frequent")),
                    ("logreg", LogisticRegression(max_iter=1000, random_state=42))]:
    with mlflow.start_run(run_name=name):
        mlflow.set_tags({"split": "v3", "features": "v2"})
        mlflow.log_param("seed", 42)
        model.fit(X_train, y_train)
        mlflow.log_metric("val_f1", f1_score(y_val, model.predict(X_val)))

Finding the best run with search_runs

After twenty runs you want the best validation score on split v3 and its gap to the baseline. mlflow.search_runs takes a filter string and returns a DataFrame. Step 1: filter by tag. Step 2: sort by the metric. Step 3: subtract the baseline score. The result is a small table you can paste into a model report.

python
import mlflow

runs = mlflow.search_runs(
    experiment_names=["churn"],
    filter_string="tags.split = 'v3'",
    order_by=["metrics.val_f1 DESC"],
)
base = runs.loc[runs["tags.mlflow.runName"] == "baseline", "metrics.val_f1"].iloc[0]
runs["gain"] = runs["metrics.val_f1"] - base
print(runs[["tags.mlflow.runName", "params.seed", "metrics.val_f1", "gain"]].head())

Quick reference

  • Start: mlflow server --backend-store-uri sqlite:///mlflow.db --port 5000
  • mlflow.set_experiment("name") creates the experiment if it is missing
  • Params = settings, metrics = numbers that change, artifacts = files, tags = labels
  • Log data with mlflow.log_input(mlflow.data.from_pandas(df, name=...), context="training")
  • Always log a naive baseline run on the same split
  • Compare only runs with the same split tag and metric definition
  • Use mlflow.search_runs(filter_string=...) to get runs as a DataFrame

Common mistakes

  • Logging metrics but not the data version, so two runs look comparable when they used different rows.
  • Tuning on the test set and logging that score as if it were an honest estimate.
  • Leaving the seed unset, so a rerun differs and you cannot tell noise from a real gain.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which of these belongs in an MLflow metric rather than a parameter?

Question 2

2Candidate scores 0.812 and baseline 0.808, but reruns with other seeds vary by 0.01. What should you conclude?

Question 3

3Why record a dataset digest with each run?

Question 4

4When should you score the test set during model selection?

Question 5

5What does an MLflow experiment group together?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Start a local MLflow server and log one run with a parameter, a metric and a tag, then find it in the UI.

  2. Exercise 2medium

    Train a RandomForestClassifier with seeds 1 to 5 on the same split, log each as a run, and compute the mean and standard deviation of the validation score.

  3. Exercise 3hard

    Make every run record full lineage: dataset digest, split rule, feature list file, Git commit and a pip freeze file. Show that two runs on different data versions can be told apart.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I need a cloud account to use MLflow?
No. MLflow is open source and runs locally with a SQLite file and a folder for artifacts. Managed versions exist on some cloud platforms, but they are optional.
What is the difference between a parameter and a tag in MLflow?
A parameter is an input setting of the run, such as a learning rate, and is fixed once logged. A tag is a free label, such as the split version or the purpose of the run, and can be changed later.
Is MLflow the only experiment tracker?
No. Weights and Biases, Neptune, DVC experiments and others do similar work. The habits matter more than the tool: log data versions, seeds, metrics and artifacts every time.
Should I log every notebook experiment?
Log anything whose result might influence a decision. Throwaway checks can stay unlogged, but if you might quote the number later, it needs a run.

Go deeper

ShareXLinkedInWhatsApp