Sub topic 1
Why Experiments Need Tracking
Prerequisites
This chapter assumes you can write basic Python, train a scikit-learn model, install packages with pip, and run a command in a terminal. You should also know what a train/test split and accuracy mean.
Why untracked experiments are hard to reproduce
Model tuning means running training many times with different settings, data, and code. Without a record, you cannot tell which run produced the best score or rebuild that model later. File names such as model_final_v2.pkl and notebook cells that get edited in place do not capture this reliably.
MLflow Tracking is a library and service that records each run: its parameters, metrics, tags, and files.
How MLflow Tracking is put together
Four parts work together:
- Client: your Python code, which calls
mlflowfunctions. - Tracking server: an HTTP service that receives those calls.
- Backend store: a database that holds run metadata such as parameters and metrics.
- Artifact store: a folder or object store that holds files such as models and plots.
Start a local server with:
pip install mlflow scikit-learn
mlflow server --backend-store-uri sqlite:///mlflow.db --default-artifact-root ./mlartifacts --host 127.0.0.1 --port 5000Experiments and runs
An experiment is a named group of runs, such as iris-baseline. A run is one execution of your training code, with its own ID. Every value you log belongs to a run.
Logging parameters, metrics and tags
- Parameters (
log_param) are the inputs you chose, such as the regularization strengthC. MLflow stores them as strings. - Metrics (
log_metric) are numbers measured during or after the run, such as test accuracy. - Tags (
set_tag) are labels for filtering, such asstage=baseline.
import mlflow
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
mlflow.set_tracking_uri("http://127.0.0.1:5000")
mlflow.set_experiment("iris-baseline")
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
C = 1.0
with mlflow.start_run(run_name="logreg-c1"):
model = LogisticRegression(C=C, max_iter=200).fit(X_train, y_train)
mlflow.log_param("C", C)
mlflow.log_param("random_state", 42)
mlflow.log_metric("test_accuracy", model.score(X_test, y_test))
mlflow.set_tag("stage", "baseline")Exercise
The code already sets C = 1.0, so why log it with log_param as well?
Show answer
The run stores the exact value used. You can then compare runs with different C values, and you can rebuild a result without reading code that may have changed since the run.