Experiment tracking with MLflow
Log every run's parameters, metric curves, artifacts and model with MLflow; use autolog, the MLflow UI and `search_runs` to compare runs and pick a winner.
After a week of experiments you will have dozens of runs: different learning rates, features, seeds, data versions. Without Experiment tracking you end up with files like model_final_v2_REAL.pkl and no idea which settings produced your best score. [[mlflow]] is an open-source platform whose Tracking component records, for every Run, its parameters, metrics over time, artifacts (plots, configs, the model itself) and metadata, and shows them in a web UI where runs can be compared side by side[1].
The vocabulary
| Concept | Meaning | Example |
|---|---|---|
| Experiment | A named group of runs for one problem | churn-mlp |
| Run | One execution of training code; has a unique run_id | “lr=3e-4, batch 64” |
| Parameter | An input setting, logged once (string key/value) | lr, batch_size, epochs |
| Metric | A number that can be logged many times with a step → becomes a curve | val_loss per epoch |
| Artifact | Any output file | confusion-matrix PNG, config YAML |
| Logged model | A model saved in an MLflow “flavor” format, loadable later anywhere | mlflow.sklearn.log_model(...) |
| Tag | Free-form metadata for filtering | dataset_version=v3 |
1. Start a tracking server and the UI
pip install mlflow
# Quick local UI (reads the local tracking store in the current directory)
mlflow ui # open http://127.0.0.1:5000
# A proper tracking server: database for metadata + a folder/bucket for artifacts
mlflow server --host 127.0.0.1 --port 5000 \
--backend-store-uri sqlite:///mlflow.db \
--default-artifact-root ./mlartifactsYour code points at a store with mlflow.set_tracking_uri(...) (or the MLFLOW_TRACKING_URI environment variable). It can be a local path, a sqlite:/// database, or the URL of a shared server — teams usually run one server with PostgreSQL/MySQL as backend and S3/GCS/Azure Blob as artifact storage, so everyone sees everyone's runs.
@champion.2. Manual logging: full control
import mlflow
mlflow.set_tracking_uri("http://127.0.0.1:5000")
mlflow.set_experiment("churn-mlp") # created if it doesn't exist
params = {"lr": 3e-4, "batch_size": 64, "epochs": 20, "hidden": 128, "seed": 42}
with mlflow.start_run(run_name="mlp-lr3e-4") as run:
mlflow.log_params(params) # or mlflow.log_param("lr", 3e-4)
mlflow.set_tag("dataset_version", "v3")
for epoch in range(params["epochs"]):
train_loss = train_one_epoch(model, train_loader)
val_loss, val_acc = evaluate(model, val_loader)
mlflow.log_metrics(
{"train_loss": train_loss, "val_loss": val_loss, "val_acc": val_acc},
step=epoch,
)
mlflow.log_metric("test_acc", evaluate(model, test_loader)[1])
fig.savefig("confusion_matrix.png")
mlflow.log_artifact("confusion_matrix.png", artifact_path="plots")
mlflow.log_artifact("configs/base.yaml")
# Save the model in MLflow's pytorch flavor
# (MLflow 3: name="model"; MLflow 2.x used artifact_path="model")
mlflow.pytorch.log_model(model, name="model")
print("run_id:", run.info.run_id)step= turns repeated metric values into curves.3. Autologging: one line
For popular libraries MLflow can log everything for you. mlflow.autolog() enables autologging for every supported library that is installed; flavor-specific calls such as mlflow.sklearn.autolog() give extra options. For scikit-learn it records all estimator parameters, training metrics, the fitted model, and — for GridSearchCV/RandomizedSearchCV — the best parameters plus child runs for the candidates[2].
import mlflow
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV
mlflow.set_experiment("churn-rf")
mlflow.sklearn.autolog(log_models=True, max_tuning_runs=5)
grid = {"n_estimators": [100, 300], "max_depth": [5, 10, None]}
search = GridSearchCV(RandomForestClassifier(random_state=0), grid,
cv=5, scoring="roc_auc")
with mlflow.start_run(run_name="rf-grid"):
search.fit(X_train, y_train) # params, CV scores, best model: all logged- What it is
- Whether autologging also serialises the trained model as an artifact of the run.
- ↑ If you increase it
- True: every run is directly deployable/registrable, but storage grows quickly (large models × many runs).
- ↓ If you decrease it
- False: lightweight runs (only params/metrics); you log the final model yourself with
mlflow.<flavor>.log_model. - Typical values
- True for small tabular models; False during big sweeps, then log only the winner.
- What it is
- How many of the best candidates from a scikit-learn search get their own child run.
- ↑ If you increase it
- More child runs → you can inspect more of the search space in the UI, but clutter and logging time grow.
- ↓ If you decrease it
- Fewer child runs → tidy UI with only the top candidates;
Nonelogs all of them. - Typical values
- Default 5.
- What it is
- How often you call
log_metric(s)inside the training loop — every step, every N steps or once per epoch. - ↑ If you increase it
- Logging less often (larger N) reduces network calls and storage, but you may miss short loss spikes.
- ↓ If you decrease it
- Logging every step gives detailed curves but can slow training noticeably when the server is remote.
- Typical values
- Per epoch for small jobs; every 10–100 steps for long deep-learning runs.
Try it: a mini MLflow UI
- Sort the run table by
val_loss(ascending) and byval_acc(descending). Is the best run the same in both? - Tick two or three runs and overlay their curves. Switch the metric between loss and accuracy: look for a run whose train loss keeps falling while val loss rises (overfitting).
- Create a New run with a very high learning rate, then one with a very low one. Compare how their curves differ from a middle value.
- Select a run and read the generated Python snippet: every value in the table comes from a
log_paramorlog_metriccall. - Click Register best model and note the version number and the
@championalias — the topic of the next lesson.
4. Comparing runs programmatically
In the UI, select runs and press Compare to get parallel-coordinate plots, scatter plots of a parameter vs a metric, and overlaid metric charts. In code, mlflow.search_runs returns a pandas DataFrame you can filter with a SQL-like string[3].
import mlflow
runs = mlflow.search_runs(
experiment_names=["churn-mlp"],
filter_string="metrics.val_acc > 0.80 and params.batch_size = '64'",
order_by=["metrics.val_loss ASC"],
max_results=10,
)
print(runs[["run_id", "params.lr", "metrics.val_loss", "metrics.val_acc"]])
best_run_id = runs.iloc[0]["run_id"]step= → you get a single point instead of a curve. • Choosing the best run by test metrics — selection must use validation data, or the test score becomes optimistic. • Not logging the data version, git commit and seed → a “best run” you cannot rebuild. • Params are stored as strings: filter with quotes (params.batch_size = '64'). • Forgetting to end runs in notebooks — prefer with mlflow.start_run(): so the run closes even on errors.▸Go deeper: nested runs, datasets and MLflow alternatives
mlflow.start_run(nested=True) inside an outer run creates parent/child runs — ideal for one hyperparameter sweep (parent) with many trials (children). mlflow.log_input(mlflow.data.from_pandas(df, name=...), context="training") records which dataset a run used. MLflow also logs a model signature (input/output schema) and an input example when you pass them to log_model, which later lets serving validate requests. Similar tools: Weights & Biases, Neptune, Comet, ClearML, Aim, TensorBoard (curves only); the concepts — run, params, metrics, artifacts — transfer directly.
Quiz
mlflow.log_metric("val_loss", v) every epoch but the UI shows no curve, just one value. What did you forget?mlflow.sklearn.autolog() record for a GridSearchCV fit?log_models off during a 300-run sweep?References
- [1]MLflow TrackingDocsMLflowmlflow.org
- [2]MLflow Tracking — Automatic LoggingDocsMLflowmlflow.org
- [3]mlflow Python API referenceDocsMLflowmlflow.org