跳至主内容

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 等。

→ 探索自动日志记录

🛠️ 手动记录 - 完全控制,自定义工作流

适用于自定义训练循环、高级实验,或当您需要对被跟踪的内容进行精确控制时。

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")

核心日志函数

设置与配置

函数用途示例
mlflow.set_tracking_uri()Connect to tracking server or databasemlflow.set_tracking_uri("http://localhost:5000")
mlflow.get_tracking_uri()Get current tracking URIuri = mlflow.get_tracking_uri()
mlflow.create_experiment()Create new experimentexp_id = mlflow.create_experiment("my-experiment")
mlflow.set_experiment()Set active experimentmlflow.set_experiment("fraud-detection")

运行管理

功能用途示例
mlflow.start_run()Start new run (with context manager)with mlflow.start_run(): ...
mlflow.end_run()End current runmlflow.end_run(status="FINISHED")
mlflow.active_run()Get currently active runrun = mlflow.active_run()
mlflow.last_active_run()Get last completed runlast_run = mlflow.last_active_run()

数据记录

功能用途示例
mlflow.log_param() / mlflow.log_params()Log hyperparametersmlflow.log_param("lr", 0.01)
mlflow.log_metric() / mlflow.log_metrics()Log performance metricsmlflow.log_metric("accuracy", 0.95, step=10)
mlflow.log_input()Log dataset informationmlflow.log_input(dataset)
mlflow.set_tag() / mlflow.set_tags()Add metadata tagsmlflow.set_tag("model_type", "CNN")

工件管理

函数用途示例
mlflow.log_artifact()Log single file/directorymlflow.log_artifact("model.pkl")
mlflow.log_artifacts()Log entire directorymlflow.log_artifacts("./plots/")
mlflow.get_artifact_uri()Get artifact storage locationuri = mlflow.get_artifact_uri()

模型管理(在 MLflow 3 中新增)

功能用途示例
mlflow.initialize_logged_model()Initialize a logged model in PENDING statemodel = mlflow.initialize_logged_model(name="my_model")
mlflow.create_external_model()Create external model (artifacts stored outside MLflow)model = mlflow.create_external_model(name="agent")
mlflow.finalize_logged_model()Update model status to READY or FAILEDmlflow.finalize_logged_model(model_id, "READY")
mlflow.get_logged_model()Retrieve logged model by IDmodel = mlflow.get_logged_model(model_id)
mlflow.last_logged_model()Get most recently logged modelmodel = mlflow.last_logged_model()
mlflow.search_logged_models()Search for logged modelsmodels = mlflow.search_logged_models(filter_string="name='my_model'")
mlflow.log_model_params()Log parameters to a specific modelmlflow.log_model_params({"param": "value"}, model_id)
mlflow.set_logged_model_tags()Set tags on a logged modelmlflow.set_logged_model_tags(model_id, {"key": "value"})
mlflow.delete_logged_model_tag()Delete tag from a logged modelmlflow.delete_logged_model_tag(model_id, "key")

主动模型管理 (MLflow 3 新增)

函数用途示例
mlflow.set_active_model()Set active model for trace linkingmlflow.set_active_model(name="my_model")
mlflow.get_active_model_id()Get current active model IDmodel_id = mlflow.get_active_model_id()
mlflow.clear_active_model()Clear active modelmlflow.clear_active_model()

针对特定语言的 API 覆盖情况

功能PythonJavaRREST API
基本日志记录✅ 完全支持✅ 完全支持✅ 完全支持✅ 完全支持
自动记录✅ 15+ 个库❌ 不可用✅ 有限❌ 不可用
模型记录✅ 20+ 种格式✅ 基本支持✅ 基本支持✅ 通过工件
已记录模型管理✅ 完整 (MLflow 3)❌ 不可用❌ 不可用✅ 基本
数据集跟踪✅ 完整✅ 基本✅ 基本✅ 基本
搜索与查询✅ 高级✅ 基础✅ 基础✅ 完整
api-parity

Python API 提供了最全面的功能集。Java and R APIs 提供核心功能,并在每个版本中持续增加新功能。

高级跟踪模式

使用已记录模型(MLflow 3 新增)

MLflow 3 引入了强大的已记录模型管理功能,用于独立于运行跟踪模型:

创建和管理外部模型

对于存储在 MLflow 之外的模型(例如已部署的智能体或外部模型工件):

import mlflow

# Create an external model for tracking without storing artifacts in MLflow
model = mlflow.create_external_model(
name="chatbot_agent",
model_type="agent",
tags={"version": "v1.0", "environment": "production"},
)

# Log parameters specific to this model
mlflow.log_model_params(
{"temperature": "0.7", "max_tokens": "1000"}, model_id=model.model_id
)

# Set as active model for automatic trace linking
mlflow.set_active_model(model_id=model.model_id)


@mlflow.trace
def chat_with_agent(message):
# This trace will be automatically linked to the active model
return agent.chat(message)


# Traces are now linked to your external model
traces = mlflow.search_traces(model_id=model.model_id)

高级模型生命周期管理

对于需要自定义准备或验证的模型:

import mlflow
from mlflow.entities import LoggedModelStatus

# Initialize model in PENDING state
model = mlflow.initialize_logged_model(
name="custom_neural_network",
model_type="neural_network",
tags={"architecture": "transformer", "dataset": "custom"},
)

try:
# Custom model preparation logic
train_model()
validate_model()

# Save model artifacts using standard MLflow model logging
mlflow.pytorch.log_model(
pytorch_model=model_instance,
name="model",
model_id=model.model_id, # Link to the logged model
)

# Finalize model as READY
mlflow.finalize_logged_model(model.model_id, LoggedModelStatus.READY)

except Exception as e:
# Mark model as FAILED if issues occur
mlflow.finalize_logged_model(model.model_id, LoggedModelStatus.FAILED)
raise

# Retrieve and work with the logged model
final_model = mlflow.get_logged_model(model.model_id)
print(f"Model {final_model.name} is {final_model.status}")

搜索和查询已记录的模型

# Find all production-ready transformer models
production_models = mlflow.search_logged_models(
filter_string="tags.environment = 'production' AND model_type = 'transformer'",
order_by=[{"field_name": "creation_time", "ascending": False}],
output_format="pandas",
)

# Search for models with specific performance metrics
high_accuracy_models = mlflow.search_logged_models(
filter_string="metrics.accuracy > 0.95",
datasets=[{"dataset_name": "test_set"}], # Only consider test set metrics
max_results=10,
)

# Get the most recently logged model in current session
latest_model = mlflow.last_logged_model()
if latest_model:
print(f"Latest model: {latest_model.name} (ID: {latest_model.model_id})")

精确的指标跟踪

使用自定义时间戳和步骤精确控制指标何时以及如何记录:

import time
from datetime import datetime

# Log with custom step (training iteration/epoch)
for epoch in range(100):
loss = train_epoch()
mlflow.log_metric("train_loss", loss, step=epoch)

# Log with custom timestamp
now = int(time.time() * 1000) # MLflow expects milliseconds
mlflow.log_metric("inference_latency", latency, timestamp=now)

# Log with both step and timestamp
mlflow.log_metric("gpu_utilization", gpu_usage, step=epoch, timestamp=now)

步骤要求:

  • 必须是有效的64 位整数
  • 可以为负数或顺序混乱
  • 支持序列中的间隔(例如:1、5、75、-20)

实验组织

将你的实验结构化以便于轻松比较和分析:

# Method 1: Environment variables
import os

os.environ["MLFLOW_EXPERIMENT_NAME"] = "fraud-detection-v2"

# Method 2: Explicit experiment setting
mlflow.set_experiment("hyperparameter-tuning")

# Method 3: Create with custom configuration
experiment_id = mlflow.create_experiment(
"production-models",
artifact_location="s3://my-bucket/experiments/",
tags={"team": "data-science", "environment": "prod"},
)

具有父子关系的分层运行

组织复杂的实验,例如超参数搜索或交叉验证:

# Parent run for the entire experiment
with mlflow.start_run(run_name="hyperparameter_sweep") as parent_run:
mlflow.log_param("search_strategy", "random")

best_score = 0
best_params = {}

# Child runs for each parameter combination
for lr in [0.001, 0.01, 0.1]:
for batch_size in [16, 32, 64]:
with mlflow.start_run(
nested=True, run_name=f"lr_{lr}_bs_{batch_size}"
) as child_run:
mlflow.log_params({"learning_rate": lr, "batch_size": batch_size})

# Train and evaluate
model = train_model(lr, batch_size)
score = evaluate_model(model)
mlflow.log_metric("accuracy", score)

# Track best configuration in parent
if score > best_score:
best_score = score
best_params = {"learning_rate": lr, "batch_size": batch_size}

# Log best results to parent run
mlflow.log_params(best_params)
mlflow.log_metric("best_accuracy", best_score)

# Query child runs
child_runs = mlflow.search_runs(
filter_string=f"tags.mlflow.parentRunId = '{parent_run.info.run_id}'"
)
print("Child run results:")
print(child_runs[["run_id", "params.learning_rate", "metrics.accuracy"]])

Parallel Execution Strategies

使用不同的并行化方法高效地处理多个运行:

非常适合简单的超参数搜索或 A/B 测试:

configs = [
{"model": "RandomForest", "n_estimators": 100},
{"model": "XGBoost", "max_depth": 6},
{"model": "LogisticRegression", "C": 1.0},
]

for config in configs:
with mlflow.start_run(run_name=config["model"]):
mlflow.log_params(config)
model = train_model(config)
score = evaluate_model(model)
mlflow.log_metric("f1_score", score)

组织的智能标记

有策略地使用标签来组织和筛选实验:

with mlflow.start_run():
# Descriptive tags for filtering
mlflow.set_tags(
{
"model_family": "transformer",
"dataset_version": "v2.1",
"environment": "production",
"team": "nlp-research",
"gpu_type": "V100",
"experiment_phase": "hyperparameter_tuning",
}
)

# Special notes tag for documentation
mlflow.set_tag(
"mlflow.note.content",
"Baseline transformer model with attention dropout. "
"Testing different learning rate schedules.",
)

# Training code here...

按标签搜索实验:

# Find all transformer experiments
transformer_runs = mlflow.search_runs(filter_string="tags.model_family = 'transformer'")

# Find production-ready models
prod_models = mlflow.search_runs(
filter_string="tags.environment = 'production' AND metrics.accuracy > 0.95"
)

系统标签参考

MLflow 会自动设置若干系统标签以记录执行上下文:

标签描述何时设置
mlflow.source.nameSource file or notebook nameAlways
mlflow.source.typeSource type (NOTEBOOK, JOB, LOCAL, etc.)Always
mlflow.userUser who created the runAlways
mlflow.source.git.commitGit commit hashWhen run from git repo
mlflow.source.git.branchGit branch nameMLflow Projects only
mlflow.parentRunIdParent run ID for nested runsChild runs only
mlflow.docker.image.nameDocker image usedDocker environments
mlflow.note.contentUser-editable descriptionManual only
pro-tip

在 MLflow UI 中使用 mlflow.note.content 来直接记录实验见解、假设或结果。此标签会出现在运行页面的专用 Notes 部分。

与自动记录的集成

将自动记录与手动跟踪结合,以兼得两者之长:

import mlflow
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report

# Enable auto logging
mlflow.autolog()

with mlflow.start_run():
# Auto logging captures model training automatically
model = RandomForestClassifier(n_estimators=100)
model.fit(X_train, y_train)

# Add custom metrics and artifacts
predictions = model.predict(X_test)

# Log custom evaluation metrics
report = classification_report(y_test, predictions, output_dict=True)
mlflow.log_metrics(
{
"precision_macro": report["macro avg"]["precision"],
"recall_macro": report["macro avg"]["recall"],
"f1_macro": report["macro avg"]["f1-score"],
}
)

# Log custom artifacts
feature_importance = pd.DataFrame(
{"feature": feature_names, "importance": model.feature_importances_}
)
feature_importance.to_csv("feature_importance.csv")
mlflow.log_artifact("feature_importance.csv")

# Access the auto-logged run for additional processing
current_run = mlflow.active_run()
print(f"Auto-logged run ID: {current_run.info.run_id}")

# Access the completed run
last_run = mlflow.last_active_run()
print(f"Final run status: {last_run.info.status}")

语言特定指南


下一步: