MLflow 跟踪 API
MLflow Tracking 提供跨多种编程语言的全面 APIs 来捕获你的机器学习实验。无论你偏好自动化插装还是精细控制,MLflow 都能适应你的工作流。
选择你的方法
MLflow 提供两种主要的实验跟踪方法,每种方法针对不同的使用场景进行优化:
🤖 自动记录 - 零配置,全面覆盖
非常适合快速入门或在使用受支持的 ML 库时。只需添加一行代码,MLflow 会自动捕获所有内容。
import mlflow
mlflow.autolog() # That's it!
# Your existing training code works unchanged
model.fit(X_train, y_train)
自动记录的内容:
- 模型参数和超参数
- 训练和验证指标
- 模型工件和检查点
- 训练图表和可视化
- 特定于框架的元数据
支持的库: Scikit-learn, XGBoost, LightGBM, PyTorch, Keras/TensorFlow, Spark 等。
🛠️ 手动记录 - 完全控制,自定义工作流
适用于自定义训练循环、高级实验,或当您需要对被跟踪的内容进行精确控制时。
- Python
- Java
- R
import mlflow
with mlflow.start_run():
# Log parameters
mlflow.log_param("learning_rate", 0.01)
mlflow.log_param("batch_size", 32)
# Your training logic here
for epoch in range(num_epochs):
train_loss = train_model()
val_loss = validate_model()
# Log metrics with step tracking
mlflow.log_metrics({"train_loss": train_loss, "val_loss": val_loss}, step=epoch)
# Log final model
mlflow.sklearn.log_model(model, name="model")
MlflowClient client = new MlflowClient();
RunInfo run = client.createRun();
// Log parameters
client.logParam(run.getRunId(), "learning_rate", "0.01");
client.logParam(run.getRunId(), "batch_size", "32");
// Log metrics with timesteps
for (int epoch = 0; epoch < numEpochs; epoch++) {
double trainLoss = trainModel();
client.logMetric(run.getRunId(), "train_loss", trainLoss,
System.currentTimeMillis(), epoch);
}
library(mlflow)
with(mlflow_start_run(), {
# Log parameters
mlflow_log_param("learning_rate", 0.01)
mlflow_log_param("batch_size", 32)
# Training loop
for (epoch in 1:num_epochs) {
train_loss <- train_model()
mlflow_log_metric("train_loss", train_loss, step = epoch)
}
})
核心日志函数
设置与配置
| 函数 | 用途 | 示例 |
|---|---|---|
mlflow.set_tracking_uri() | Connect to tracking server or database | mlflow.set_tracking_uri("http://localhost:5000") |
mlflow.get_tracking_uri() | Get current tracking URI | uri = mlflow.get_tracking_uri() |
mlflow.create_experiment() | Create new experiment | exp_id = mlflow.create_experiment("my-experiment") |
mlflow.set_experiment() | Set active experiment | mlflow.set_experiment("fraud-detection") |