跳到主要内容

连接您的开发环境到 MLflow

本指南将指导您如何将开发环境连接到 MLflow 实验。您可以在本地机器上运行 MLflow,自行托管开源 MLflow 服务,或使用 Databricks Managed MLflow 等托管服务。

MLflow 实验

MLflow 实验是您的 GenAI 应用程序的容器。在MLflow 文档中了解更多关于实验的信息。

先决条件

  • Python 环境:Python 3.8+,已安装 pip
  • 本地或远程服务器:可以访问运行 MLflow 跟踪服务器

设置说明

步骤 1:安装 MLflow

为本地开发安装 MLflow

pip install --upgrade "mlflow>=3.1"

步骤 2:启动 MLflow 跟踪服务器

选项 A:本地跟踪(默认)

如果未指定跟踪 URI,MLflow 将自动使用本地文件存储

import mlflow

# Creates local mlruns directory for experiments
mlflow.set_experiment("my-genai-experiment")

选项 B:远程跟踪服务器

启动远程 MLflow 跟踪服务器

# Start MLflow server (in a separate terminal)
mlflow server --host 0.0.0.0 --port 5000

然后配置您的客户端以使用远程服务器

import mlflow

# Connect to remote MLflow server
mlflow.set_tracking_uri("https://:5000")
mlflow.set_experiment("my-genai-experiment")

选项 C:数据库后端

生产环境请配置 MLflow 使用数据库后端

# Example with PostgreSQL
mlflow server \
--backend-store-uri postgresql://user:password@localhost:5432/mlflow \
--default-artifact-root s3://my-mlflow-bucket/artifacts \
--host 0.0.0.0 \
--port 5000

步骤 3:配置环境(可选)

为了在团队中保持一致的配置,请使用环境变量

# .env file
MLFLOW_TRACKING_URI=https://:5000
MLFLOW_EXPERIMENT_NAME=my-genai-experiment

在您的 Python 代码中加载

import os
from dotenv import load_dotenv
import mlflow

load_dotenv()

# Set tracking URI and experiment
mlflow.set_tracking_uri(os.getenv("MLFLOW_TRACKING_URI", "file:./mlruns"))
mlflow.set_experiment(os.getenv("MLFLOW_EXPERIMENT_NAME", "default"))

步骤 4:验证您的连接

创建测试文件并运行此代码

import mlflow

# Print connection information
print(f"MLflow Tracking URI: {mlflow.get_tracking_uri()}")
print(f"Active Experiment: {mlflow.get_experiment_by_name('my-genai-experiment')}")

# Test logging
with mlflow.start_run():
mlflow.log_param("test_param", "test_value")
print("✓ Successfully connected to MLflow!")

步骤 5:访问 MLflow UI

在浏览器中打开以查看 MLflow UI

  • 本地跟踪https://:5000(如果正在运行 mlflow server)
  • 基于文件的跟踪:在您的项目目录中运行 mlflow ui,然后访问 https://:5000

后续步骤

现在您的环境已连接到 MLflow,请尝试其他 GenAI 快速入门指南