3. 使用DVC管理数据集版本

任务目标

在机器学习模型开发过程中,需要记录每次实验的超参数、指标和模型产物,以便对比不同实验效果并复现最佳模型。本案例使用MLflow Tracking完成一次完整的实验跟踪闭环:记录逻辑回归模型的超参数与评估指标,并将训练好的模型注册到MLflow Model Registry。

环境与依赖

pip install mlflow scikit-learn pandas

完整实现代码

import mlflow
import mlflow.sklearn
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, f1_score

# 1. 准备数据
data = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
    data.data, data.target, test_size=0.2, random_state=42
)

# 2. 设置实验
mlflow.set_experiment("iris-classification")

# 3. 启动一次运行并记录
with mlflow.start_run(run_name="logreg-c1"):
    # 超参数
    C = 1.0
    solver = "lbfgs"
    mlflow.log_param("C", C)
    mlflow.log_param("solver", solver)
    mlflow.log_param("max_iter", 200)

    # 训练模型
    model = LogisticRegression(C=C, solver=solver, max_iter=200)
    model.fit(X_train, y_train)

    # 评估
    y_pred = model.predict(X_test)
    acc = accuracy_score(y_test, y_pred)
    f1 = f1_score(y_test, y_pred, average="weighted")

    # 记录指标
    mlflow.log_metric("accuracy", acc)
    mlflow.log_metric("f1_weighted", f1)

    # 记录模型
    mlflow.sklearn.log_model(model, "model")

    # 注册到Model Registry
    mlflow.register_model(
        model_uri=f"runs:/{mlflow.active_run().info.run_id}/model",
        name="IrisClassifier"
    )

    print(f"Run ID: {mlflow.active_run().info.run_id}")
    print(f"Accuracy: {acc:.4f}, F1: {f1:.4f}")

运行方式

# 启动MLflow UI(另开终端)
mlflow ui --port 5000

# 运行实验脚本
python experiment.py

验证方法与判定标准

执行脚本后,在终端看到输出的Run ID和指标值即表示运行成功。打开 http://localhost:5000,在MLflow UI中应能看到:

  • 实验名称“iris-classification”下出现一条run记录,run_name为“logreg-c1”;
  • Parameters栏包含C、solver、max_iter三个超参数;
  • Metrics栏包含accuracy和f1_weighted两个指标,数值与终端输出一致;
  • Artifacts栏包含model文件夹;
  • 左侧Model Registry中注册了名为“IrisClassifier”的模型,版本为Version 1。

满足以上条件即判定实验跟踪闭环完成。

常见问题

  • 端口冲突:若5000端口被占用,使用 mlflow ui --port 5001 更换端口。
  • 模型注册失败:确认MLflow服务端已启动(默认使用本地文件存储),且当前目录有写入权限。
  • 重复注册:每次运行脚本会为“IrisClassifier”创建新版本,可在UI中查看版本列表。