用途
MLflow 是一个机器学习生命周期管理平台,适用于需要跟踪 ML 实验、管理模型注册与版本、部署模型到生产环境以及复现实验的场景。它被设计为框架无关,可与任意 ML 框架集成。
主要能力
- 实验跟踪:记录每次运行的参数、指标和产物(文件、目录、字典等)。
- 自动日志(Autologging):为 Scikit-learn、PyTorch、Keras、XGBoost、HuggingFace Transformers 等框架自动记录参数、指标和模型。
- 模型注册表:管理模型版本,支持阶段转换(None → Staging → Production → Archived),可添加描述和标签。
- 模型部署:支持本地服务(mlflow models serve)以及部署到 AWS SageMaker、Azure ML 等云平台。
- 实验复现:通过项目配置和运行记录复现实验。
- 运行搜索:使用过滤条件和排序程序化搜索运行记录。
使用方式
安装
pip install mlflow
# 安装额外依赖
pip install mlflow[extras]
# 启动 UI
mlflow ui
# 访问 http://localhost:5000
基本跟踪
import mlflow
with mlflow.start_run():
mlflow.log_param("learning_rate", 0.001)
mlflow.log_param("batch_size", 32)
model = train_model()
mlflow.log_metric("train_loss", 0.15)
mlflow.log_metric("val_accuracy", 0.92)
mlflow.sklearn.log_model(model, "model")
自动日志
import mlflow
from sklearn.ensemble import RandomForestClassifier
mlflow.autolog()
model = RandomForestClassifier(n_estimators=100, max_depth=5)
model.fit(X_train, y_train)
模型注册与阶段转换
from mlflow.tracking import MlflowClient
client = MlflowClient()
client.transition_model_version_stage(
name="my-classifier",
version=3,
stage="Production",
archive_existing_versions=True
)
加载注册模型
import mlflow.pyfunc
model = mlflow.pyfunc.load_model("models:/my-classifier/Production")
predictions = model.predict(X_test)
本地服务
mlflow models serve -m "models:/my-classifier/Production" -p 5001
curl http://127.0.0.1:5001/invocations -H 'Content-Type: application/json' -d '{"inputs": [[1.0, 2.0, 3.0, 4.0]]}'
跟踪服务器配置
mlflow server \
--backend-store-uri postgresql://user:password@localhost/mlflow \
--default-artifact-root s3://my-bucket/mlflow \
--host 0.0.0.0 \
--port 5000
适用场景
- 需要跟踪大量 ML 实验并比较模型性能的团队。
- 需要管理模型版本、阶段和部署流程的 MLOps 工作流。
- 使用多种 ML 框架并希望统一管理实验和模型的场景。
- 需要复现实验或协作开发 ML 项目的团队。
限制
- 资料中未提供具体的收费、价格或平台限制信息。
- 资料中未提供关于性能、效果或使用步骤的额外说明。
- 部分功能(如云部署)的具体配置和依赖未在资料中详细展开。