Track experiments with MLflow
In this task you'll record every training run's settings, scores and model so you can compare them later.
Without tracking, model work lives in notebooks and memory: which settings gave the best score last Tuesday? MLflow records each training run: its parameters (settings), metrics (scores), tags (notes such as the data version) and artifacts (the model file), grouped into experiments.
In this track everything is kept in one SQLite file, mlflow.db, which also holds the model registry used later. mlflow ui opens a local web page where you can sort runs by score and compare two side by side.
Example. Harbourline Design's data person tried 30 settings for a lead-scoring model over two weeks and couldn't say which one was in production. With MLflow, every run since has its settings, scores and model file in one place.
Before you start
You need: Python 3.10 or newer, and about 500 MB of disk for MLflow and scikit-learn. No cloud account. Time: 30 minutes.
Where to look
- mlops folder
- train.py
- mlflow ui
- http://127.0.0.1:5000
Steps
- Save
train.pyfrom Commands in the mlops folder. - Run
python train.py. It prints the run ID, AUC about 0.78 and the first characters of the data's fingerprint.Warnings about pip versions or input examples are normal and safe to ignore. - Run two more with different settings:
python train.py --C 0.05andpython train.py --algo forest. - Run
mlflow ui --backend-store-uri sqlite:///mlflow.dband open http://127.0.0.1:5000. Open the delivery-late experiment.Keep this terminal open; use a second terminal for the next commands. - Sort by auc, then tick two runs and choose Compare to see their parameters and scores side by side.
- Stop the UI with Ctrl+C.
Commands
# train.py: a repeatable training run, tracked in MLflow, with a quality gate and optional registration.
import argparse, hashlib, os, sys
import mlflow, mlflow.sklearn, pandas as pd
from mlflow import MlflowClient
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, f1_score, roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
p = argparse.ArgumentParser()
p.add_argument("--data", default="data/orders.csv")
p.add_argument("--algo", choices=["logreg", "forest"], default="logreg")
p.add_argument("--C", type=float, default=1.0)
p.add_argument("--trees", type=int, default=200)
p.add_argument("--min-auc", type=float, default=0.70, help="quality gate: fail the run below this")
p.add_argument("--register", action="store_true", help="register the model and point the challenger alias at it")
a = p.parse_args()
NAME, NUM, CAT = "delivery-late", ["distance_km", "items", "hour", "weekend"], ["warehouse"]
# Runs and the model registry live in one local file, unless MLFLOW_TRACKING_URI says otherwise (Azure ML sets it)
mlflow.set_tracking_uri(os.environ.get("MLFLOW_TRACKING_URI", "sqlite:///mlflow.db"))
mlflow.set_experiment("delivery-late")
data_hash = hashlib.sha256(open(a.data, "rb").read()).hexdigest() # data version: any change gives a new hash
df = pd.read_csv(a.data)
X_train, X_test, y_train, y_test = train_test_split(df[NUM + CAT], df["late"], test_size=0.2, random_state=42, stratify=df["late"])
clf = LogisticRegression(C=a.C, max_iter=1000) if a.algo == "logreg" else RandomForestClassifier(n_estimators=a.trees, min_samples_leaf=20, random_state=42)
model = Pipeline([("prep", ColumnTransformer([("num", StandardScaler(), NUM), ("cat", OneHotEncoder(), CAT)])), ("clf", clf)])
with mlflow.start_run() as run:
mlflow.log_params({"algo": a.algo, "C": a.C, "trees": a.trees, "rows": len(df)})
mlflow.set_tags({"data_file": a.data, "data_sha256": data_hash[:16]})
model.fit(X_train, y_train)
prob = model.predict_proba(X_test)[:, 1]
m = {"auc": roc_auc_score(y_test, prob), "accuracy": accuracy_score(y_test, prob > 0.5), "f1": f1_score(y_test, prob > 0.5)}
mlflow.log_metrics(m)
print(f"run {run.info.run_id[:8]} {a.algo} auc {m['auc']:.4f} accuracy {m['accuracy']:.4f} f1 {m['f1']:.4f} data {data_hash[:12]}")
if m["auc"] < a.min_auc:
mlflow.set_tag("gate", "failed")
print(f"GATE FAILED: auc {m['auc']:.4f} is under {a.min_auc}. Nothing registered.")
sys.exit(1)
mlflow.set_tag("gate", "passed")
# MLflow 3 saves scikit-learn models with skops, which refuses types it can't check. Tree models need their
# tree type named as trusted: only do this for models you trained yourself.
trusted = ["sklearn.tree._tree.Tree"] if a.algo == "forest" else None
info = mlflow.sklearn.log_model(model, name="model", input_example=X_test.head(3), skops_trusted_types=trusted,
registered_model_name=NAME if a.register else None)
if a.register:
version = info.registered_model_version
MlflowClient().set_registered_model_alias(NAME, "challenger", version)
print(f"registered {NAME} version {version} as @challenger")
# Run and compare
python train.py
python train.py --C 0.05
python train.py --algo forest
mlflow ui --backend-store-uri sqlite:///mlflow.db # then open http://127.0.0.1:5000
Watch out for
- Cost
- Free: the tracking database is a file on your computer.
- Security
- A shared tracking server needs sign-in in front of it; mlflow ui is for your own computer only.
- Common mistakes
- Logging scores without the settings and data version that produced them.
Clean up
Keep the mlops folder for the next tasks in this section; delete it (and its .venv) at the end.
Words to know
- Run
- One training attempt, with its settings, scores and outputs.
- Parameter
- A setting chosen before training, such as C or the number of trees.
- Metric
- A score measured after training, such as AUC.
- Artifact
- A file saved with a run, such as the model itself.
Tick off each step and track your progress in the guide.
Open this task in DevOps, Hands On