AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
⚙ML Development & MLOps
  1. The ML development stack
  2. The ML lifecycle & MLOps maturity
  3. Experiment tracking with MLflow
  4. Model Registry, data versioning & lineage
  5. Deployment & model serving
  6. Monitoring, data drift & concept drift
  7. CI/CD, continuous training & feature stores
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/ML Development & MLOps

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.

Intermediate~22 min·3 references
Key terms
Experiment trackingMLflowRunArtifactHyperparameterReproducibilityModel registry

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].

≈
A lab notebook that writes itself
A good chemist writes down every reagent, quantity, temperature and result for each experiment. MLflow is that lab notebook for ML — except your code fills it in automatically, and you can sort and chart all past experiments in seconds.

The vocabulary

ConceptMeaningExample
ExperimentA named group of runs for one problemchurn-mlp
RunOne execution of training code; has a unique run_id“lr=3e-4, batch 64”
ParameterAn input setting, logged once (string key/value)lr, batch_size, epochs
MetricA number that can be logged many times with a step → becomes a curveval_loss per epoch
ArtifactAny output fileconfusion-matrix PNG, config YAML
Logged modelA model saved in an MLflow “flavor” format, loadable later anywheremlflow.sklearn.log_model(...)
TagFree-form metadata for filteringdataset_version=v3

1. Start a tracking server and the UI

bash
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 ./mlartifacts

Your 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.

Loading interactive…
How a team MLflow setup fits together. Walk through the path of one run, or tap the two stores to see what goes where. Notice the split: small metadata (params, metrics) lands in a database, big files (models, plots) in an artifact store — and serving only ever asks the registry for @champion.

2. Manual logging: full control

python
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)
A PyTorch-style training loop logged to MLflow. 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].

python
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
knobautolog(log_models=…)
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.
knobsklearn.autolog(max_tuning_runs=…)
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; None logs all of them.
Typical values
Default 5.
knobmetric logging interval (every N steps)
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

Loading interactive…
Illustrative runs from a simple deterministic simulator — not a real MLflow server.
  • Sort the run table by val_loss (ascending) and by val_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_param or log_metric call.
  • Click Register best model and note the version number and the @champion alias — 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].

python
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"]
!
Tracking pitfalls
• Logging metrics without 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

1.
You call mlflow.log_metric("val_loss", v) every epoch but the UI shows no curve, just one value. What did you forget?
2.
Which is the right way to choose the “best run” among 50 tuning runs?
3.
What does mlflow.sklearn.autolog() record for a GridSearchCV fit?
4.
Your team wants one place where everyone's runs are visible. What do you set up?
5.
What happens if you turn autolog's log_models off during a 300-run sweep?
Score: 0/5

References

  1. [1]
    MLflow Tracking
    DocsMLflowmlflow.org
  2. [2]
    MLflow Tracking — Automatic Logging
    DocsMLflowmlflow.org
  3. [3]
    mlflow Python API reference
    DocsMLflowmlflow.org
← Previous
The ML lifecycle & MLOps maturity
Next →
Model Registry, data versioning & lineage