MLflow Tracking 用于记录和管理机器学习实验,包括:
✅ 支持本地 / 远程
✅ 支持单机 / 多机
pip install mlflow(可选)如果你想用 UI 查看实验:
pip install mlflow[extras]import mlflow
import mlflow.sklearn
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 设置实验名
mlflow.set_experiment("iris_classification")
# 开始一次实验
with mlflow.start_run():
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)
model = LogisticRegression(max_iter=200)
model.fit(X_train, y_train)
preds = model.predict(X_test)
acc = accuracy_score(y_test, preds)
# 记录参数
mlflow.log_param("model_type", "LogisticRegression")
mlflow.log_param("max_iter", 200)
# 记录指标
mlflow.log_metric("accuracy", acc)
# 保存模型
mlflow.sklearn.log_model(model, "model")
print(f"Accuracy: {acc}")在项目目录下运行:
mlflow ui浏览器打开:
http://127.0.0.1:5000你可以看到:
| 概念 | 含义 |
|---|---|
| Experiment | 一组相关实验 |
| Run | 一次模型训练 |
| Param | 超参数 |
| Metric | 评估指标 |
| Artifact | 模型 / 图片 / 日志 |
mlflow.create_experiment("my_experiment")
mlflow.set_experiment("my_experiment")import mlflow
mlflow.set_experiment("hyperparam_tuning")
for C in [0.1, 1.0, 10.0]:
with mlflow.start_run():
mlflow.log_param("C", C)
mlflow.log_metric("val_acc", C * 0.1)mlflow.set_tracking_uri("file:///home/user/mlruns")启动 MLflow Tracking Server:
mlflow server \
--backend-store-uri sqlite:///mlflow.db \
--default-artifact-root ./artifacts \
--host 0.0.0.0 \
--port 5000代码中连接:
mlflow.set_tracking_uri("http://127.0.0.1:5000")mlflow.log_param("lr", 0.01)
mlflow.log_metric("loss", 0.23)
mlflow.log_artifact("confusion_matrix.png")mlflow.autolog()支持:
✅ 每个实验一个 experiment
✅ 关键指标必须 log_metric
✅ 模型必须保存
✅ 不用 print,用 MLflow UI 对比
❌ 忘记 start_run()
❌ 只 log param 不 log metric
❌ 远程 tracking URI 没配置
MLflow 实验跟踪 = 用 start_run() 包裹训练代码 + 记录参数 / 指标 / 模型如果你愿意,我可以:
你现在是个人学习还是生产环境部署?