0Pricing
Machine Learning Academy · 课时

使用 MLflow 跟踪实验:记录参数、指标与制品

您将使用 mlflow.log_param 和 mlflow.log_metric 为训练脚本添加实验记录,启动 MLflow 界面,并比较不同超参数设置下的运行结果。

使用 MLflow 跟踪实验:记录参数、指标与制品 是 CoddyKit 上的免费 Machine Learning Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Machine Learning Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Machine Learning Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Experiment Tracking Matters

When you train multiple models with different hyperparameters, it is easy to lose track of which run achieved the best result. Experiment tracking automatically records every training run's parameters, metrics, and code version in a searchable database. Without it, teams resort to messy spreadsheets or simply forget what worked. MLflow is the industry-standard open-source tool for tracking ML experiments and managing the model lifecycle.

Installing and Starting MLflow

MLflow is a pure Python package that requires no external database for getting started — it stores runs locally in an mlruns/ directory. Install with pip, then launch the tracking UI to visualise runs in a browser. The UI shows all experiments, each run's parameters and metrics, and lets you compare runs side-by-side with interactive charts.

# Install MLflow
# pip install mlflow scikit-learn

import mlflow
import mlflow.sklearn

# Start the tracking UI (run this in a terminal):
# mlflow ui --host 0.0.0.0 --port 5000
# Then open http://localhost:5000

# Check MLflow version
print('MLflow version:', mlflow.__version__)

# Default tracking URI stores to ./mlruns
print('Tracking URI:', mlflow.get_tracking_uri())

Creating Experiments

MLflow organises runs into experiments — logical groupings of related runs. Create a named experiment with mlflow.set_experiment. All subsequent runs belong to this experiment. Use descriptive names that identify the project and date, e.g., 'random_forest_imdb_2024'. Each run within an experiment gets a unique ID, a human-readable name, and its own parameter/metric/artifact store.

import mlflow

# Create or switch to an experiment
experiment_name = 'sentiment_classification'
mlflow.set_experiment(experiment_name)

# List all experiments
for exp in mlflow.search_experiments():
    print(f'ID: {exp.experiment_id}  Name: {exp.name}')

# Get current experiment info
experiment = mlflow.get_experiment_by_name(experiment_name)
print('Artifact location:', experiment.artifact_location)

Logging Parameters with mlflow.log_param

Parameters are the configuration choices made before training begins: hyperparameters like learning rate, number of estimators, and regularisation strength. Log them with mlflow.log_param(key, value) inside an active run context. Parameters are immutable once logged — they define the experiment setup and help you filter runs to find the configuration that worked best.

import mlflow
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

X, y = make_classification(n_samples=1000, n_features=20, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

with mlflow.start_run(run_name='rf_baseline'):
    n_estimators = 100
    max_depth = 5
    mlflow.log_param('n_estimators', n_estimators)
    mlflow.log_param('max_depth', max_depth)
    mlflow.log_param('random_state', 42)

    clf = RandomForestClassifier(n_estimators=n_estimators, max_depth=max_depth, random_state=42)
    clf.fit(X_train, y_train)
    print('Params logged.')

Logging Metrics with mlflow.log_metric

Metrics are the quantitative results produced during and after training: accuracy, F1, loss values. Log them with mlflow.log_metric(key, value) or mlflow.log_metric(key, value, step=i) to track progress across epochs. Logging metrics at each epoch lets MLflow plot learning curves in the UI, making it easy to compare convergence speed across runs.

import mlflow
from sklearn.metrics import accuracy_score, f1_score

with mlflow.start_run(run_name='rf_run_1'):
    mlflow.log_param('n_estimators', 100)
    mlflow.log_param('max_depth', 5)

    # Train model (abbreviated)
    clf = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42)
    clf.fit(X_train, y_train)
    preds = clf.predict(X_test)

    acc = accuracy_score(y_test, preds)
    f1 = f1_score(y_test, preds)

    mlflow.log_metric('test_accuracy', acc)
    mlflow.log_metric('test_f1', f1)
    print(f'Logged accuracy={acc:.4f}, f1={f1:.4f}')

Logging Artifacts

Artifacts are files associated with a run: trained model weights, plots, confusion matrices, or feature importance charts. Log them with mlflow.log_artifact(local_path). MLflow stores the file in the run's artifact directory and makes it downloadable from the UI. Logging the confusion matrix image alongside metrics gives reviewers a complete picture without diving into code.

import mlflow
import matplotlib.pyplot as plt
from sklearn.metrics import ConfusionMatrixDisplay
import numpy as np

with mlflow.start_run():
    clf.fit(X_train, y_train)
    preds = clf.predict(X_test)

    # Save confusion matrix as an artifact
    fig, ax = plt.subplots(figsize=(5, 4))
    ConfusionMatrixDisplay.from_predictions(y_test, preds, ax=ax)
    plt.tight_layout()
    plt.savefig('/tmp/confusion_matrix.png')
    plt.close()

    mlflow.log_artifact('/tmp/confusion_matrix.png')
    print('Artifact logged.')

Auto-logging with mlflow.sklearn.autolog

For scikit-learn, MLflow provides auto-logging that captures all parameters, metrics, and the trained model automatically without any manual log calls. Simply call mlflow.sklearn.autolog() before fitting. Auto-logging supports XGBoost, LightGBM, PyTorch, TensorFlow, and more with similar one-line activation. It is the fastest way to start tracking without modifying existing training code.

import mlflow
import mlflow.sklearn
from sklearn.ensemble import GradientBoostingClassifier

# Enable auto-logging -- no manual log calls needed
mlflow.sklearn.autolog()

with mlflow.start_run(run_name='gb_autolog'):
    clf = GradientBoostingClassifier(n_estimators=200, max_depth=3, learning_rate=0.05)
    clf.fit(X_train, y_train)
    # MLflow automatically logs:
    # - All constructor params
    # - Training accuracy
    # - Model artifact
    print('Auto-logged run complete.')

Comparing Runs in the MLflow UI

After several runs with different hyperparameters, open the MLflow UI at http://localhost:5000. Select multiple runs with checkboxes and click Compare to view them side by side. The comparison page shows a parallel coordinates plot where each axis is a parameter or metric, making it easy to spot which parameter combination led to the highest accuracy. You can also sort the run table by any metric column.

import mlflow

# Search runs programmatically (useful in CI/CD pipelines)
runs = mlflow.search_runs(
    experiment_names=['sentiment_classification'],
    order_by=['metrics.test_accuracy DESC']
)

if not runs.empty:
    best_run = runs.iloc[0]
    print('Best run ID:', best_run['run_id'])
    print('Best accuracy:', best_run['metrics.test_accuracy'])
    print('n_estimators:', best_run['params.n_estimators'])
    print('max_depth:', best_run['params.max_depth'])

Logging Models with mlflow.sklearn.log_model

Beyond logging model files as generic artifacts, use mlflow.sklearn.log_model to log the model in MLflow's standardised format. This format includes the model object, its flavour metadata, and an automatically generated MLmodel config file. The standardised format enables one-click deployment to local REST servers (mlflow models serve) and cloud platforms like Azure ML and AWS SageMaker.

import mlflow
import mlflow.sklearn
from sklearn.ensemble import RandomForestClassifier

with mlflow.start_run(run_name='rf_logged_model'):
    clf = RandomForestClassifier(n_estimators=100, random_state=42)
    clf.fit(X_train, y_train)

    mlflow.log_metric('accuracy', accuracy_score(y_test, clf.predict(X_test)))

    # Log in sklearn flavour -- enables mlflow models serve
    mlflow.sklearn.log_model(
        sk_model=clf,
        artifact_path='random_forest',
        registered_model_name='SentimentRF'
    )
    print('Model registered in Model Registry.')

Tagging Runs for Organisation

MLflow runs can have tags: key-value metadata that goes beyond structured parameters and metrics. Use tags to store the dataset version, code commit hash, experimenter name, or notes about what changed. Tags are searchable and filterable in the UI. A good tagging convention — like always logging dataset_version and git_sha — ensures every run is reproducible and auditable months later.

import mlflow
import subprocess

def get_git_sha():
    try:
        return subprocess.check_output(
            ['git', 'rev-parse', 'HEAD'], text=True
        ).strip()
    except Exception:
        return 'unknown'

with mlflow.start_run():
    mlflow.set_tag('dataset_version', 'imdb_v2')
    mlflow.set_tag('git_sha', get_git_sha())
    mlflow.set_tag('author', 'mehmet.canker')
    mlflow.set_tag('notes', 'Testing higher max_depth after previous plateau')
    mlflow.log_param('max_depth', 8)
    print('Run tagged.')

Remote Tracking Server Setup

For team collaboration, point MLflow at a remote tracking server instead of the local mlruns/ folder. Set the tracking URI to your server's URL before any MLflow calls. All team members log to the same server, see each other's runs, and access shared artifacts. The server backend can use a PostgreSQL database for metadata and S3/GCS for artifact storage, providing enterprise-grade durability and access control.

import mlflow
import os

# Point to a remote MLflow tracking server
os.environ['MLFLOW_TRACKING_URI'] = 'http://mlflow.yourcompany.com:5000'
os.environ['MLFLOW_TRACKING_USERNAME'] = 'data_team'
os.environ['MLFLOW_TRACKING_PASSWORD'] = 'secret'

mlflow.set_tracking_uri(os.environ['MLFLOW_TRACKING_URI'])

# All subsequent mlflow calls go to the remote server
mlflow.set_experiment('shared_team_experiment')
with mlflow.start_run():
    mlflow.log_param('model_type', 'xgboost')
    mlflow.log_metric('auc', 0.94)
    print('Logged to remote server.')

Quick Check

Test your understanding of Machine Learning with Python concepts from this lesson.

Lesson Recap

In this lesson you learned: MLflow tracks parameters, metrics, and artifacts for every training run in a searchable database, mlflow.sklearn.autolog() captures everything automatically without manual log calls, and logged models in the sklearn flavour can be served as REST APIs or promoted through the Model Registry. Next up we build reproducible Docker containers for ML training to eliminate environment differences between machines.

常见问题解答

「使用 MLflow 跟踪实验:记录参数、指标与制品」课时是免费的吗?

是的 — 「使用 MLflow 跟踪实验:记录参数、指标与制品」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Machine Learning Academy 课程的其余内容,请升级到 CoddyKit PRO。 Machine Learning Academy 课程共包含 4 节课。

「使用 MLflow 跟踪实验:记录参数、指标与制品」这节课中我会学到什么?

您将使用 mlflow.log_param 和 mlflow.log_metric 为训练脚本添加实验记录,启动 MLflow 界面,并比较不同超参数设置下的运行结果。 你通过在浏览器中直接运行的动手代码来练习 Machine Learning Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Machine Learning Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Machine Learning Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「使用 MLflow 跟踪实验:记录参数、指标与制品」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Machine Learning Academy 课中编写并运行代码吗?

能。每节 Machine Learning Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 MLflow 跟踪实验:记录参数、指标与制品
  2. 使用 Docker 为机器学习构建可复现环境
  3. 模型注册表:暂存、生产与归档
  4. 使用 GitHub Actions 实现自动重新训练管道
← 返回 Machine Learning Academy