MLflow 跟踪服务器存储和管理试验数据、运行和模型。 配置跟踪服务器以控制 MLflow 数据存储的位置以及如何跨不同环境访问试验。
Databricks 托管的跟踪服务器
默认情况下,Databricks 提供一个托管 MLflow 跟踪服务器,用于:
- 无需其他设置或配置
- 在工作区中存储试验数据
- 与 Databricks 笔记本和群集无缝集成
设置活动试验
默认情况下,所有 MLflow 运行都使用活动试验记录到工作区的跟踪服务器。 如果未显式设置试验,则会将运行记录到 笔记本试验中。
通过设置活动试验来控制在 Databricks 中记录运行的位置:
Mlflow.set_experiment()
为执行中的所有后续运行设置试验。
import mlflow
mlflow.set_experiment("/Shared/my-experiment")
Mlflow.start_run()
为特定运行设置试验。
with mlflow.start_run(experiment_id="12345"):
mlflow.log_param("learning_rate", 0.01)
环境变量
为环境中的所有运行设置试验。
import os
os.environ["MLFLOW_EXPERIMENT_NAME"] = "/Shared/my-experiment"
# or
os.environ["MLFLOW_EXPERIMENT_ID"] = "12345"
设置远程 MLflow 跟踪服务器的跟踪
可能需要设置到远程 MLflow 跟踪服务器的连接。 这可能是因为你在本地开发并希望跟踪 Databricks 托管的服务器,或者想要跟踪到其他 MLflow 跟踪服务器。 例如,位于其他工作区中的工作区。
远程跟踪的常见方案:
| Scenario | 用例 |
|---|---|
| 跨工作区跟踪 | 跨多个工作区进行集中试验跟踪 |
| 本地开发 | 在本地开发,但在 Databricks 中跟踪试验 |
| 远程自承载 | 具有特定合规性要求的自定义 MLflow 基础结构 |
设置跟踪 URI 和试验
若要将试验记录到远程跟踪服务器,请配置跟踪 URI 和试验路径:
import mlflow
# Set the tracking URI to the remote server
mlflow.set_tracking_uri("databricks://remote-workspace-url")
# Set the experiment path in the remote server
mlflow.set_experiment("/Shared/centralized-experiments/my-project")
# All subsequent runs will be logged to the remote server
with mlflow.start_run():
mlflow.log_param("model_type", "random_forest")
mlflow.log_metric("accuracy", 0.95)
身份验证方法
远程跟踪服务器连接需要适当的身份验证。 使用服务主体在个人访问令牌(PAT)或 OAuth 之间进行选择。
PAT
使用 PAT 进行基于令牌的简单身份验证。
优点: 简单设置,适合开发
缺点: 特定于用户,需要手动令牌管理
import os
# Set authentication token
os.environ["DATABRICKS_TOKEN"] = "your-personal-access-token"
# Configure remote tracking
mlflow.set_tracking_uri("databricks://remote-workspace-url")
mlflow.set_experiment("/Shared/remote-experiment")
OAuth (服务主体)
将 OAuth 与自动工作流的服务主体凭据配合使用。
优点: 更适合自动化、集中式标识管理
缺点: 需要服务主体设置和 OAuth 配置
创建服务主体。 请参阅 管理服务主体。
import os
# Set service principal credentials
os.environ["DATABRICKS_CLIENT_ID"] = "your-service-principal-client-id"
os.environ["DATABRICKS_CLIENT_SECRET"] = "your-service-principal-secret"
# Configure remote tracking
mlflow.set_tracking_uri("databricks://remote-workspace-url")
mlflow.set_experiment("/Shared/remote-experiment")