Tracking Experiments with MLflow
The previous lesson built a run log from scratch: one JSON line per run with parameters, metrics, artifacts, code, data and environment. MLflow is an open-source tool that does the same job for a team: a Python API that the training code calls, a store for run records and artifacts, a web UI to compare runs, and (in the next lessons) a model registry. Other trackers (Weights & Biases, Neptune, Comet, ClearML, Aim, TensorBoard for curves) have the same concepts with different names, so what you learn here transfers.
MLflow is not available in the browser, so the examples on this page are recorded: they ran with MLflow 3.17.2 in the course's Docker image, and the output shown is what they printed. Each example uses a fresh SQLite file as its store.
The concepts
| MLflow | Meaning | From-scratch equivalent |
|---|---|---|
| tracking URI | where run records go: a local folder, a SQLite or Postgres database, or a tracking server's URL | the runs.jsonl path |
| experiment | a named group of runs for one problem; set_experiment creates it on first use |
a file per problem |
| run | one execution, with an id, a name, a status (RUNNING, FINISHED, FAILED) and start/end times |
one JSON line |
| params | strings, logged once per run (log_param, log_params) |
params |
| metrics | floats, optionally with a step; every logged value is kept as a history |
metrics lists |
| tags | free-form strings for filtering (team, dataset); MLflow sets system tags mlflow.* itself (source file, git commit when it can find one, user, parent run) |
tags |
| artifacts | files: models, plots, reports, stored in an artifact store (a folder, S3, GCS, Azure Blob) | content-addressed files |
mlflow.start_run() is a context manager. Like the from-scratch tracker, it marks the run FAILED if the block raises, and FINISHED otherwise.
Logging a run: params, per-step metrics, artifacts
The running example again (2,000 synthetic rows, 8 features; 1,200 rows to fit, 300 to validate, 500 kept for test), this time an SGDClassifier trained for 5 epochs with partial_fit, so that the validation loss has a value per epoch. The coefficients are written to a text file and logged as an artifact under reports/. After the run, MlflowClient reads the record back, as the UI would.
import logging, os, tempfile
import numpy as np
import mlflow
from mlflow import MlflowClient
logging.getLogger("mlflow").setLevel(logging.ERROR)
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import log_loss, roc_auc_score
mlflow.set_tracking_uri("sqlite:///mlflow.db")
mlflow.set_experiment("risk-model")
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)
scaler = StandardScaler().fit(X_fit)
X_fit_s, X_val_s = scaler.transform(X_fit), scaler.transform(X_val)
params = {"loss": "log_loss", "alpha": 1e-4, "eta0": 0.01, "epochs": 5, "seed": 0}
with mlflow.start_run(run_name="sgd-baseline") as run:
mlflow.log_params(params)
mlflow.set_tags({"model_family": "linear", "dataset": "synthetic-2000"})
clf = SGDClassifier(loss="log_loss", alpha=params["alpha"], learning_rate="constant",
eta0=params["eta0"], random_state=params["seed"])
rng = np.random.default_rng(params["seed"])
for epoch in range(params["epochs"]):
order = rng.permutation(len(y_fit))
clf.partial_fit(X_fit_s[order], y_fit[order], classes=[0, 1])
p = clf.predict_proba(X_val_s)[:, 1]
mlflow.log_metric("val_log_loss", log_loss(y_val, p), step=epoch) # one point per epoch
mlflow.log_metric("val_auc", roc_auc_score(y_val, p))
with tempfile.TemporaryDirectory() as d:
path = os.path.join(d, "coefficients.txt")
np.savetxt(path, clf.coef_.ravel(), fmt="%.4f")
mlflow.log_artifact(path, artifact_path="reports")
run_id = run.info.run_id
client = MlflowClient()
r = client.get_run(run_id)
print("experiment:", client.get_experiment(r.info.experiment_id).name, "| run:", r.info.run_name,
"| status:", r.info.status)
print("params:", dict(sorted(r.data.params.items())))
print("tags:", {k: v for k, v in sorted(r.data.tags.items()) if not k.startswith("mlflow.")})
print("val_auc:", round(r.data.metrics["val_auc"], 4))
for m in client.get_metric_history(run_id, "val_log_loss"):
print(f" step {m.step}: val_log_loss {m.value:.4f}")
print("artifacts:", [a.path for a in client.list_artifacts(run_id, "reports")])experiment: risk-model | run: sgd-baseline | status: FINISHED
params: {'alpha': '0.0001', 'epochs': '5', 'eta0': '0.01', 'loss': 'log_loss', 'seed': '0'}
tags: {'dataset': 'synthetic-2000', 'model_family': 'linear'}
val_auc: 0.9183
step 0: val_log_loss 0.3781
step 1: val_log_loss 0.3619
step 2: val_log_loss 0.3556
step 3: val_log_loss 0.3520
step 4: val_log_loss 0.3547
artifacts: ['reports/coefficients.txt']
Everything is in the store: parameters come back as strings ('0.0001', '5'; MLflow stores params as text, so compare them as text in queries or convert them), the custom tags, the final val_auc of 0.9183 and the whole history of val_log_loss. The history shows the loss falling from 0.3781 after the first epoch to 0.3520 after the fourth and rising again to 0.3547 after the fifth, which a single final number would hide; in the UI the same history is a curve, and curves of several runs can be overlaid. Note that log_metric(..., step=epoch) is what makes this a history: logging the same key without a step appends values with step 0.
The output prints no run id, timestamp or artifact path: those change on every run. In real use you would print or link run.info.run_id, since it is how other tools (the registry, a deployment) refer to the run.
Nested runs for a small grid, and search_runs
A hyperparameter search produces many runs that belong together. Nested runs express that: a parent run for the search, a child run per configuration (nested=True), each child linked by the system tag mlflow.parentRunId. Here the grid is penalty (l1, l2) times C (0.01, 0.1, 1.0) for the scaled logistic regression, and every child also logs its fitted pipeline with mlflow.sklearn.log_model. mlflow.search_runs returns runs as a pandas DataFrame, filtered with a small SQL-like language (params.x = '...', metrics.y > 0.9, tags.z = '...', combined with and) and sorted with order_by.
import logging, os
os.environ["MLFLOW_ENABLE_ARTIFACTS_PROGRESS_BAR"] = "false" # no download progress bars in the output
import mlflow
logging.getLogger("mlflow").setLevel(logging.ERROR)
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
mlflow.set_tracking_uri("sqlite:///mlflow.db")
mlflow.set_experiment("risk-model")
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)
with mlflow.start_run(run_name="grid-C-penalty") as parent:
mlflow.log_param("search", "grid over C x penalty")
for penalty in ("l2", "l1"):
for C in (0.01, 0.1, 1.0):
with mlflow.start_run(run_name=f"{penalty}-C{C}", nested=True):
mlflow.log_params({"C": C, "penalty": penalty})
model = make_pipeline(StandardScaler(), LogisticRegression(C=C, penalty=penalty,
solver="liblinear", random_state=0))
model.fit(X_fit, y_fit)
mlflow.log_metric("val_auc", roc_auc_score(y_val, model.predict_proba(X_val)[:, 1]))
mlflow.sklearn.log_model(model, name="model", pip_requirements=["scikit-learn==1.7.0"])
children = mlflow.search_runs(filter_string=f"tags.mlflow.parentRunId = '{parent.info.run_id}'",
order_by=["metrics.val_auc DESC"])
print(type(children).__name__, children.shape[0], "child runs")
print(children[["tags.mlflow.runName", "params.penalty", "params.C", "metrics.val_auc"]]
.round(4).to_string(index=False))
l1 = mlflow.search_runs(filter_string=(f"tags.mlflow.parentRunId = '{parent.info.run_id}' "
"and params.penalty = 'l1' and metrics.val_auc > 0.915"))
print("l1 runs with val_auc > 0.915:", sorted(l1["tags.mlflow.runName"]))
best = children.iloc[0]
model = mlflow.sklearn.load_model(f"runs:/{best.run_id}/model") # the exact object that was scored
print("best:", best["tags.mlflow.runName"], "| test AUC (once):",
round(roc_auc_score(y_test, model.predict_proba(X_test)[:, 1]), 4), f"on {len(y_test)} rows")DataFrame 6 child runs
tags.mlflow.runName params.penalty params.C metrics.val_auc
l2-C1.0 l2 1.0 0.9191
l2-C0.1 l2 0.1 0.9191
l1-C1.0 l1 1.0 0.9189
l1-C0.1 l1 0.1 0.9178
l2-C0.01 l2 0.01 0.9155
l1-C0.01 l1 0.01 0.9059
l1 runs with val_auc > 0.915: ['l1-C0.1', 'l1-C1.0']
best: l2-C1.0 | test AUC (once): 0.9318 on 500 rows
The DataFrame has one column per param, metric and tag, named params.C, metrics.val_auc, tags.mlflow.runName. Sorting by validation AUC puts l2-C1.0 and l2-C0.1 on top (both 0.9191; the gap to l1-C1.0 at 0.9189 is far below what 300 validation rows can resolve), and C = 0.01 with the L1 penalty is clearly worse (0.9059): strong L1 regularisation removes informative features. The second query shows the filter language: L1 runs with val_auc > 0.915 are l1-C0.1 and l1-C1.0. In a filter, parameter values are strings and must be quoted (params.penalty = 'l1'); metrics are numbers.
The last step loads the chosen model back with the URI runs:/<run_id>/model and scores it on the 500 test rows, once: test AUC 0.9318. Loading from the run, rather than refitting, guarantees that the object evaluated (and later deployed) is the object that was tracked. The log line pip_requirements=["scikit-learn==1.7.0"] pins the environment saved with the model; without it MLflow infers the requirements from the current environment (Model Artifacts, Signatures and Metadata covers what is stored with a model).
Nested runs are also how integrations such as Optuna's MLflow callback or a cross-validation loop (a child per fold) organise their runs. A flat alternative is a tag such as search_id; nesting has the advantage that the UI shows the tree.
Autologging
For popular libraries, mlflow.<flavor>.autolog() patches the training functions so that a fit call logs its parameters, some metrics and (optionally) the model without any log_* calls. Here for a random forest, with model and dataset logging switched off to keep the example small.
import logging
import mlflow
logging.getLogger("mlflow").setLevel(logging.ERROR)
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
mlflow.set_tracking_uri("sqlite:///mlflow.db")
mlflow.set_experiment("risk-model")
X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)
X_fit, X_val, y_fit, y_val = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)
mlflow.sklearn.autolog(log_models=False, log_datasets=False)
with mlflow.start_run(run_name="forest-autolog") as run:
RandomForestClassifier(n_estimators=50, max_depth=6, random_state=0).fit(X_fit, y_fit)
mlflow.sklearn.autolog(disable=True)
r = mlflow.get_run(run.info.run_id)
print(len(r.data.params), "params logged, e.g.",
{k: r.data.params[k] for k in ("n_estimators", "max_depth", "criterion", "random_state")})
print("metrics:", {k: round(v, 4) for k, v in sorted(r.data.metrics.items())})
print("estimator tag:", r.data.tags.get("estimator_name"))19 params logged, e.g. {'n_estimators': '50', 'max_depth': '6', 'criterion': 'gini', 'random_state': '0'}
metrics: {'training_accuracy_score': 0.9393, 'training_f1_score': 0.9393, 'training_log_loss': 0.2007, 'training_precision_score': 0.9404, 'training_recall_score': 0.9393, 'training_roc_auc': 0.9886, 'training_score': 0.9393}
estimator tag: RandomForestClassifier
Autolog recorded all 19 constructor parameters of the forest (not only the 2 we set, so the defaults are on record too, which matters when a library changes a default) and seven metrics. But read their names: training_. Autolog for scikit-learn scores the model on the data passed to fit, so training_accuracy_score 0.9393 and training_roc_auc 0.9886 are training scores, optimistic by construction. Validation metrics are still yours to log. Autolog is a convenient default for parameters and models; it does not decide what an honest evaluation is.
Where the records go: stores and servers
The examples used sqlite:///mlflow.db, a single-user database file. In a team, the setup is usually a tracking server with two stores behind it (the flags below were checked against mlflow server --help of MLflow 3.17; check them against your version):
- a backend store for run records (params, metrics, tags): a SQL database such as PostgreSQL or MySQL;
- an artifact store for files: S3, Google Cloud Storage, Azure Blob Storage, or a shared file system;
- the server started with something like
mlflow server --backend-store-uri postgresql://... --artifacts-destination s3://bucket/mlflow --host 0.0.0.0 --port 5000, and the clients pointed at it withmlflow.set_tracking_uri("http://mlflow.internal:5000")or theMLFLOW_TRACKING_URIenvironment variable.
Without any configuration, older MLflow versions write to a local ./mlruns folder (the file store); recent MLflow 3 releases (3.17 here) default to a local SQLite database, sqlite:///mlflow.db, and keeps using an existing ./mlruns folder if it finds one. A server proxies artifact uploads by default (--serve-artifacts) and stores them in ./mlartifacts unless --artifacts-destination names a bucket. mlflow ui (or mlflow server) starts the web UI on port 5000 by default. Managed offerings (Databricks, and MLflow on the major clouds) run the server for you. Whatever the setup, the training code changes only in its tracking URI.
Pitfalls
- Comparing params as numbers. They are strings:
params.C > 0.1in a filter compares text. Sort or filter numerically in pandas aftersearch_runs, or log the value as a metric too. - Training metrics from autolog mistaken for validation metrics. Check the metric names.
- Every run in the
Defaultexperiment. Withoutset_experiment, runs pile up in one experiment and comparisons become meaningless. Name experiments after the problem, not the person. - Logging inside a loop without
step. The values overwrite each other's meaning; passstep=. - Huge artifacts per run. Logging the whole training set with every run fills the artifact store; log a data version (a hash or DVC version) as a param or tag instead, and the data once.
- A tracking server open to the network. The open-source server has no authentication by default (an optional basic-auth app exists,
mlflow server --app-name basic-auth); put it behind a proxy with authentication, and never log secrets as params.
Practice
- Why does
r.data.params["epochs"]return'5'and not5, and what does that mean for a filter likeparams.epochs > 10? - You run a 20-configuration search and want the UI to show it as one search with 20 entries. Which MLflow feature do you use, and how do you then select only that search's runs in
search_runs? - A colleague reports "AUC 0.99" from an autologged random forest. What do you check first?
Answers
- MLflow stores parameters as strings. A filter compares them as text, so
'5' > '10'is true in string order; compare numerically in pandas or log numeric settings as metrics as well. - Nested runs: one parent run,
start_run(nested=True)for each configuration. Select the children withfilter_string="tags.mlflow.parentRunId = '<parent id>'", as in the grid example. - The metric's name: autolog's scikit-learn metrics start with
training_and are computed on the training data (0.9886 AUC in the example). Ask for the validation or test metric and how that split was made.
Test yourself
What does mlflow.log_metric("val_log_loss", v, step=epoch) inside an epoch loop produce?
- Only the last value
- A metric history with one value per epoch
- A new run per epoch
- A parameter
How are the child runs of a grid search linked to their parent run in MLflow?
- By run name
- By the system tag
mlflow.parentRunId, set when the child is started withnested=True - By a shared artifact
- They are not linked
mlflow.sklearn.autolog() logged training_roc_auc = 0.9886 for a random forest. What is this number?
- The validation AUC
- The AUC on the data passed to
fit, an optimistic training score - The test AUC
- The cross-validated AUC
Why load the chosen model with runs:/<run_id>/model instead of refitting it with the best parameters?
- Loading is always faster
- It guarantees that the evaluated and deployed object is exactly the one that was tracked
- Refitting is not allowed in MLflow
- The URI also retrains it