🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

MLOps: Experiment Tracking with MLflow

Module 15: Data Engineering and MLOpsđŸŸĸ Free Lesson
MLOps

The one-line mental model

Experiment tracking is a database for machine learning runs: every hyperparameter, metric, and artifact gets logged under a unique run ID, so months later you can answer which model shipped, on which data, with which settings — and reproduce it exactly.

You will be able to:

  • Log parameters, metrics, and artifacts to an MLflow tracking server
  • Compare runs in the MLflow UI and select a champion by metric
  • Register a model version and load it by stage for serving
  • Structure a training script so every run is self-documenting

Prerequisites

  • !Python functions, dicts, and path handling
  • !Train/test split and cross-validation
  • !Basic command line comfort

What You'll Learn

  • 1Explain why notebook-only experiment tracking fails at team scale
  • 2Wrap a training loop with mlflow.start_run and log calls
  • 3Log a scikit-learn model with its signature and input example
  • 4Load a registered model version inside a FastAPI endpoint

Why tracking beats memory and spreadsheets

In the first week of a project, a notebook scrollbar is a fine experiment log. By week six there are forty variants of the same script, three of which "definitely scored better," and nobody can reconstruct which data snapshot produced the model currently in production. Experiment tracking fixes this by giving every run a durable identity with the full context: code version, data hash, hyperparameters, metrics, and the serialized model itself.

What to logMLflow APIWhy it matters
Hyperparametersmlflow.log_paramsReproduce or audit the winning config
Metricsmlflow.log_metricsCompare runs without opening notebooks
Model artifactmlflow.sklearn.log_modelReload exact weights for serving
Plots, data slicesmlflow.log_figure / log_artifactDiagnose failure modes post-hoc
Git commit, dataset hashtags via mlflow.set_tagTie run to code and data provenance

Setting up a tracking server

For local work the default file store under ./mlruns needs zero infrastructure. On a team, run the MLflow server backed by a Postgres database and an S3-compatible artifact store so runs survive laptop changes and are visible to everyone.

# Local file store — default, no server needed
mlflow ui --backend-store-uri sqlite:///mlflow.db \
          --default-artifact-root ./mlruns

# Team server (Postgres metadata + S3 artifacts)
mlflow server \
  --backend-store-uri postgresql://user:pass@db:5432/mlflow \
  --artifacts-destination s3://my-bucket/mlartifacts \
  --host 0.0.0.0 --port 5000
python
import os
import warnings
import numpy as np
import pandas as pd
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.metrics import (
    roc_auc_score, average_precision_score, classification_report,
)
import mlflow
import mlflow.sklearn

warnings.filterwarnings("ignore")

mlflow.set_tracking_uri(os.environ.get("MLFLOW_TRACKING_URI", "sqlite:///mlflow.db"))
mlflow.set_experiment("churn-classification")

X, y = make_classification(
    n_samples=3000, n_features=12, n_informative=8,
    n_redundant=2, weights=[0.85, 0.15], flip_y=0.02,
    random_state=42,
)
feature_names = [f"feat_{i}" for i in range(X.shape[1])]
X = pd.DataFrame(X, columns=feature_names)

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42,
)
print(f"Train: {X_train.shape}, Test: {X_test.shape}, "
      f"positive rate: {y.mean():.3f}")

The tracking URI points MLflow at either the local sqlite file or the remote server; experiment and run state live there regardless of where the training script executes.

Logging a full training run

The core pattern is a context manager (with mlflow.start_run():) wrapping the entire training lifecycle. Inside it, log_params, log_metrics, and log_model attach everything to one run ID that the UI groups and compares automatically.

python
def train_and_log(model, params, run_name, tags=None):
    with mlflow.start_run(run_name=run_name):
        mlflow.set_tags(tags or {})

        for key, value in params.items():
            mlflow.log_param(key, value)

        cv = cross_val_score(
            model, X_train, y_train,
            cv=5, scoring="roc_auc", n_jobs=-1,
        )

        model.fit(X_train, y_train)
        proba = model.predict_proba(X_test)[:, 1]
        preds = model.predict(X_test)

        metrics = {
            "cv_roc_auc_mean": float(cv.mean()),
            "cv_roc_auc_std": float(cv.std()),
            "holdout_roc_auc": float(roc_auc_score(y_test, proba)),
            "holdout_avg_precision": float(
                average_precision_score(y_test, proba),
            ),
        }
        mlflow.log_metrics(metrics)

        signature = mlflow.models.infer_signature(X_train, model.predict(X_train))
        mlflow.sklearn.log_model(
            model,
            artifact_path="model",
            signature=signature,
            input_example=X_train.head(5),
        )

        print(f"[{run_name}] holdout ROC-AUC="
              f"{metrics['holdout_roc_auc']:.4f}")
        return metrics

rf_params = {
    "n_estimators": 300,
    "max_depth": 8,
    "min_samples_leaf": 5,
    "class_weight": "balanced_subsample",
    "random_state": 42,
}
train_and_log(
    RandomForestClassifier(**rf_params),
    rf_params,
    run_name="rf-baseline",
    tags={"model_family": "rf", "stage": "baseline"},
)

gb_params = {
    "n_estimators": 250,
    "max_depth": 4,
    "learning_rate": 0.08,
    "subsample": 0.8,
    "random_state": 42,
}
train_and_log(
    GradientBoostingClassifier(**gb_params),
    gb_params,
    run_name="gb-tuned",
    tags={"model_family": "gb", "stage": "candidate"},
)

Logging the signature and input_example is what allows the MLflow model registry and serving stack to validate incoming requests against the training schema — skipping it moves schema errors from CI to production.

Selecting a champion from the tracking UI

Open the UI with mlflow ui and the runs appear grouped by experiment with columns for every logged parameter and metric. Sort by holdout_roc_auc, inspect the loss curves and confusion-matrix figures you logged, and promote the winner. The run ID is the durable pointer: anyone can later call mlflow.artifacts.download or mlflow.sklearn.load_model on that exact run and get identical predictions.

python
from mlflow.tracking import MlflowClient

client = MlflowClient()
experiment = client.get_experiment_by_name("churn-classification")

runs = client.search_runs(
    experiment_ids=[experiment.experiment_id],
    order_by=["metrics.holdout_roc_auc DESC"],
    max_results=5,
)

print("Top runs:")
for run in runs:
    print(
        f"  {run.info.run_name:<16} "
        f"roc_auc={run.data.metrics['holdout_roc_auc']:.4f}  "
        f"params={ {k: v for k, v in list(run.data.params.items())[:3]} }",
    )

best = runs[0]
print(f"\nChampion: {best.info.run_name} ({best.info.run_id})")

loaded_model = mlflow.sklearn.load_model(
    f"runs:/{best.info.run_id}/model",
)
sample_scores = loaded_model.predict_proba(X_test.head(3))[:, 1]
print(f"Loaded model sample predictions: {sample_scores.round(4)}")

Automating this search — a nightly job that trains candidates, logs them, and promotes the best by a pre-registered metric — is the bridge from ad-hoc tracking to a real model registry workflow.

Registering and versioning models

The model registry adds lifecycle states (None → Staging → Production → Archived) and semantic versioning on top of raw run artifacts. Promotion is an explicit, auditable action, and loading by stage (models:/churn-model@Production) means the serving code never hard-codes a run ID.

A healthy registry discipline treats stage transitions like production deploys: they happen through a reviewed process (ideally a CI job, not a manual click), they are logged with the promoting user and timestamp, and the previous production version is archived rather than deleted so rollback is a one-line change. Teams that let models accumulate in Production without archiving eventually face the question "which of these four Production versions is actually serving traffic?" — a question that should never have been possible to ask. The registry is only as trustworthy as the discipline around it; the tooling does not enforce good habits by itself.

python
result = mlflow.sklearn.log_model(
    loaded_model,
    artifact_path="model",
    registered_model_name="churn-model",
)

model_version = result.registered_model_version
print(f"Registered churn-model version {model_version}")

client.transition_model_version_stage(
    name="churn-model",
    version=model_version,
    stage="Staging",
    archive_existing_versions=True,
)

prod_model = mlflow.sklearn.load_model(
    "models:/churn-model@Production",
)
print(f"Production model loaded: {type(prod_model).__name__}")

history = client.search_model_versions("name='churn-model'")
for mv in history:
    print(f"  v{mv.version}: stage={mv.current_stage}, "
          f"run={mv.run_id}")

Promotion should be gated by more than a metric threshold — a lightweight CI step that reloads the candidate from the registry, re-runs a holdout evaluation, and checks prediction parity against the previous production version prevents a silent regression from ever reaching users.

Structuring the training script for CI

The final piece is making the tracking calls part of an idempotent, parameterized script that CI can invoke with different hyperparameter sets or data snapshots. Command-line arguments feed the params dict; the data snapshot hash goes into tags; the exit code fails the build if the metric does not clear the gate.

Making the script CI-friendly also means removing interactive dependencies: no plt.show(), no input() prompts, no hard-coded absolute paths. Log figures with mlflow.log_figure instead of displaying them, read paths from arguments or environment variables, and seed every random source so a rerun with the same inputs produces the same metrics. These habits are what separate a script that works on a laptop from one that runs unattended at 2am on a build agent — and the difference shows up the first time a pull request needs a green CI check before merge.

python
import argparse
import hashlib
import json
import sys

def load_data_snapshot(path):
    df = pd.read_csv(path) if path.endswith(".csv") else None
    digest = hashlib.sha256(
        json.dumps(df.values.tolist()).encode(),
    ).hexdigest()[:12] if df is not None else "synthetic"
    return df, digest

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--n-estimators", type=int, default=300)
    parser.add_argument("--max-depth", type=int, default=8)
    parser.add_argument("--min-samples-leaf", type=int, default=5)
    parser.add_argument("--data-path", type=str, default=None)
    parser.add_argument("--roc-gate", type=float, default=0.80)
    args = parser.parse_args()

    mlflow.set_experiment("churn-classification")

    df, digest = load_data_snapshot(args.data_path) if args.data_path else (None, "synthetic")

    params = {
        "n_estimators": args.n_estimators,
        "max_depth": args.max_depth,
        "min_samples_leaf": args.min_samples_leaf,
        "random_state": 42,
    }
    model = RandomForestClassifier(**params)

    with mlflow.start_run(run_name="ci-training"):
        mlflow.set_tag("git_branch", os.environ.get("GIT_BRANCH", "unknown"))
        mlflow.set_tag("data_digest", digest)
        for key, value in params.items():
            mlflow.log_param(key, value)

        cv = cross_val_score(model, X_train, y_train, cv=5,
                             scoring="roc_auc", n_jobs=-1)
        model.fit(X_train, y_train)
        proba = model.predict_proba(X_test)[:, 1]
        roc = float(roc_auc_score(y_test, proba))

        mlflow.log_metrics({
            "cv_roc_auc_mean": float(cv.mean()),
            "holdout_roc_auc": roc,
        })
        mlflow.sklearn.log_model(model, artifact_path="model")

        print(f"Holdout ROC-AUC: {roc:.4f} (gate: {args.roc_gate})")
        if roc < args.roc_gate:
            print("GATE FAILED — aborting promotion", file=sys.stderr)
            sys.exit(1)

if __name__ == "__main__":
    main()

With this shape, the same script runs locally during exploration, on a schedule for nightly retraining, and in CI on pull requests — the tracking backend captures all three contexts under one experiment for unified comparison.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Data Science Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement