怎样用MLflow跟踪实验

GPU
小华
2026-09-19

下面用实操视角给你讲清楚:怎样用 MLflow 跟踪机器学习实验。我会按“概念 → 安装 → 最小示例 → 常用功能 → 最佳实践”来说。

一、MLflow 跟踪实验的核心概念

MLflow Tracking 主要跟踪四类东西:

  1. Parameters(参数)

模型超参、配置项(如 learning_rate)

  1. Metrics(指标)

训练/验证过程中的数值(如 accuracy、loss)

  1. Artifacts(产物)

模型文件、图片、日志、配置文件

  1. Tags(标签)

实验说明、环境、作者等

二、安装 MLflow

pip install mlflow

如果你只想本地用,不需要额外服务。

三、最小可运行示例(本地跟踪)

1️⃣ 训练代码中记录实验

import mlflow
import mlflow.sklearn
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
mlflow.set_experiment("iris_classification")
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)
with mlflow.start_run():
n_estimators = 100
max_depth = 5
mlflow.log_param("n_estimators", n_estimators)
mlflow.log_param("max_depth", max_depth)
model = RandomForestClassifier(n_estimators=n_estimators, max_depth=max_depth)
model.fit(X_train, y_train)
acc = model.score(X_test, y_test)
mlflow.log_metric("accuracy", acc)
mlflow.sklearn.log_model(model, "model")

运行后,MLflow 会在当前目录生成 mlruns/

2️⃣ 启动 MLflow UI

mlflow ui

浏览器打开:

http://localhost:5000

你可以看到:

  • 每次 run
  • 参数对比
  • 指标变化
  • 模型下载

四、常用 MLflow 跟踪功能

✅ 记录多个 metric(如训练过程)

for epoch in range(10):
loss = train_one_epoch()
mlflow.log_metric("loss", loss, step=epoch)

✅ 记录图片 / 图表

import matplotlib.pyplot as plt
plt.plot([1,2,3], [1,4,9])
plt.savefig("curve.png")
mlflow.log_artifact("curve.png")

✅ 使用 tags 管理实验

mlflow.set_tag("model_type", "random_forest")
mlflow.set_tag("author", "alice")

✅ 嵌套 Run(适合调参)

with mlflow.start_run(run_name="parent"):
for lr in [0.01, 0.1]:
with mlflow.start_run(run_name=f"lr={lr}", nested=True):
mlflow.log_param("lr", lr)

五、进阶:远程 Tracking Server(团队协作)

启动服务器

mlflow server \
--host 0.0.0.0 \
--port 5000 \
--backend-store-uri sqlite:///mlflow.db \
--default-artifact-root s3://my-mlflow-bucket

代码中连接

mlflow.set_tracking_uri("http://server-ip:5000")
mlflow.set_experiment("team_exp")

六、最佳实践建议

✅ 每个实验一个 set_experiment
✅ 参数用 log_param,不要写死在代码里
✅ 模型一定要 log_model
✅ 对比实验时多看 metric + tag

✅ 团队用远程 Tracking Server

七、常见组合

场景工具
本地实验MLflow + sklearn
深度学习MLflow + PyTorch / TensorFlow
自动调参MLflow + Optuna / Ray Tune
模型部署MLflow Model Registry

如果你愿意,我可以:

  • 给你一个 PyTorch / TensorFlow 的 MLflow 示例
  • 教你 MLflow + Optuna 自动调参
  • 帮你搭 公司级 MLflow Server

你现在是个人用还是团队用?

亿速云提供售前/售后服务

售前业务咨询

售后技术保障

400-100-2938

7*24小时售后电话

官方微信小程序