mlflow.client
The mlflow.client 模块提供了一个用于 MLflow 实验、运行、模型版本和注册模型 的 Python CRUD 接口。这是一个较低级别的 API,直接转换为 MLflow REST API 调用。
对于管理“active run”的更高级别 API,请使用 mlflow 模块。
- class mlflow.client.MlflowClient(tracking_uri: Optional[str] = None, registry_uri: Optional[str] = None)[source]
基类:
object用于 MLflow 跟踪服务器的客户端,用于创建和管理实验和运行,以及用于 MLflow 注册表服务器的客户端,用于创建和管理已注册模型和模型版本。它是对 TrackingServiceClient 和 RegistryClient 的一个薄包装,因此提供了统一的 API,但我们可以保持跟踪客户端和注册客户端的实现相互独立。
- copy_model_version(src_model_uri, dst_name) ModelVersion[source]
将某个已注册模型的模型版本复制到另一个已注册模型,作为新的模型版本。
- Parameters
src_model_uri – 要复制的模型版本的模型 URI。This must be a model registry URI with a “models:/” scheme (e.g., “models:/iris_model@champion”).
dst_name – 要将模型版本复制到的已注册模型的名称。如果不存在具有此名称的已注册模型,将创建该模型。
- Returns
表示已复制模型版本的单个
mlflow.entities.model_registry.ModelVersion对象。
import mlflow.sklearn from mlflow import MlflowClient from mlflow.models import infer_signature from sklearn.datasets import make_regression from sklearn.ensemble import RandomForestRegressor def print_model_version_info(mv): print(f"Name: {mv.name}") print(f"Version: {mv.version}") print(f"Source: {mv.source}") mlflow.set_tracking_uri("sqlite:///mlruns.db") X, y = make_regression(n_features=4, n_informative=2, random_state=0, shuffle=False) # Log a model with mlflow.start_run() as run: params = {"n_estimators": 3, "random_state": 42} rfr = RandomForestRegressor(**params).fit(X, y) signature = infer_signature(X, rfr.predict(X)) mlflow.log_params(params) mlflow.sklearn.log_model(rfr, name="sklearn-model", signature=signature) # Create source model version client = MlflowClient() src_name = "RandomForestRegression-staging" client.create_registered_model(src_name) src_uri = f"runs:/{run.info.run_id}/sklearn-model" mv_src = client.create_model_version(src_name, src_uri, run.info.run_id) print_model_version_info(mv_src) print("--") # Copy the source model version into a new registered model dst_name = "RandomForestRegression-production" src_model_uri = f"models:/{mv_src.name}/{mv_src.version}" mv_copy = client.copy_model_version(src_model_uri, dst_name) print_model_version_info(mv_copy)
- create_experiment(name: str, artifact_location: Optional[str] = None, tags: Optional[dict[str, typing.Any]] = None) str[source]
创建一个实验。
- Parameters
name – 实验名称,必须是唯一的字符串。
artifact_location – 存储运行产物的位置。如果未提供,服务器会选择一个合适的默认值。
tags – 一个键值对字典,会被转换为
mlflow.entities.ExperimentTag对象,并在创建实验时设置为实验标签。
- Returns
表示已创建实验的整数 ID 的字符串。
from pathlib import Path from mlflow import MlflowClient # Create an experiment with a name that is unique and case sensitive. client = MlflowClient() experiment_id = client.create_experiment( "Social NLP Experiments", artifact_location=Path.cwd().joinpath("mlruns").as_uri(), tags={"version": "v1", "priority": "P1"}, ) client.set_experiment_tag(experiment_id, "nlp.framework", "Spark NLP") # Fetch experiment metadata information experiment = client.get_experiment(experiment_id) print(f"Name: {experiment.name}") print(f"Experiment_id: {experiment.experiment_id}") print(f"Artifact Location: {experiment.artifact_location}") print(f"Tags: {experiment.tags}") print(f"Lifecycle_stage: {experiment.lifecycle_stage}")
- create_logged_model(experiment_id: str, name: Optional[str] = None, source_run_id: Optional[str] = None, tags: Optional[dict[str, str]] = None, params: Optional[dict[str, str]] = None, model_type: Optional[str] = None) LoggedModel[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
创建一个新的已记录模型。
- Parameters
experiment_id – 模型所属实验的 ID。
name – 模型的名称。如果未指定,将生成一个随机名称。
source_run_id – 生成该模型的运行 ID。
tags – 在模型上设置的标签。
params – 要在模型上设置的参数。
model_type – 模型的类型。这是一个用户定义的字符串,可用于搜索和比较相关模型。例如,设置
model_type="agent"可让您轻松搜索此模型,并将其与将来其他类型为"agent"的模型进行比较。
- Returns
已创建的模型。
- create_model_version(name: str, source: str, run_id: Optional[str] = None, tags: Optional[dict[str, typing.Any]] = None, run_link: Optional[str] = None, description: Optional[str] = None, await_creation_for: int = 300, model_id: Optional[str] = None) ModelVersion[source]
从给定源创建一个新的模型版本。
- Parameters
name – 包含该项的已注册模型的名称。
source – 指示模型工件位置的 URI。该工件 URI 可以是相对于运行的(例如
runs:/)、模型注册表 URI(例如/ models:/),或模型注册表后端支持的其他 URI(例如 “s3://my_bucket/my/model”)。/ run_id – 生成该模型的 MLflow 跟踪服务器中的运行 ID。
tags – 一个由键值对组成的字典,这些键值对被转换为
mlflow.entities.model_registry.ModelVersionTag对象。run_link – 指向生成该模型的 MLflow 跟踪服务器中 run 的链接。
description – 版本的描述。
await_creation_for – 等待模型版本创建完成并处于
READY状态的秒数。默认情况下,该函数会等待五分钟。指定 0 或 None 可跳过等待。model_id – 表示模型的 ID(来自某个 Experiment),如果适用,指正在被提升为已注册模型版本的模型。
- Returns
由后端创建的单个
mlflow.entities.model_registry.ModelVersion对象。
import mlflow.sklearn from mlflow.store.artifact.runs_artifact_repo import RunsArtifactRepository from mlflow import MlflowClient from mlflow.models import infer_signature from sklearn.datasets import make_regression from sklearn.ensemble import RandomForestRegressor mlflow.set_tracking_uri("sqlite:///mlruns.db") params = {"n_estimators": 3, "random_state": 42} name = "RandomForestRegression" X, y = make_regression(n_features=4, n_informative=2, random_state=0, shuffle=False) rfr = RandomForestRegressor(**params).fit(X, y) signature = infer_signature(X, rfr.predict(X)) # Log MLflow entities with mlflow.start_run() as run: mlflow.log_params(params) mlflow.sklearn.log_model(rfr, name="sklearn-model", signature=signature) # Register model name in the model registry client = MlflowClient() client.create_registered_model(name) # Create a new version of the rfr model under the registered model name desc = "A new version of the model" runs_uri = f"runs:/{run.info.run_id}/sklearn-model" model_src = RunsArtifactRepository.get_underlying_uri(runs_uri) mv = client.create_model_version(name, model_src, run.info.run_id, description=desc) print(f"Name: {mv.name}") print(f"Version: {mv.version}") print(f"Description: {mv.description}") print(f"Status: {mv.status}") print(f"Stage: {mv.current_stage}")
- create_prompt(name: str, description: str | None = None, tags: dict[str, str] | None = None) Prompt[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
在注册表中创建一个新的提示词。
此方法直接委托给 store,在与 Unity Catalog 注册表一起使用时,提供对 Unity Catalog 的完整支持。
- Parameters
name – 提示的名称。
description – 可选的提示描述。
tags – 可选的提示标签字典。
- Returns
一个 Prompt 对象。
示例:
from mlflow import MlflowClient client = MlflowClient() prompt_info = client.create_prompt( name="my_prompt", description="A helpful prompt", tags={"team": "data-science"}, )
- create_prompt_version(name: str, template: str | list[dict[str, typing.Any]], description: str | None = None, tags: dict[str, str] | None = None, response_format: pydantic.main.BaseModel | dict[str, typing.Any] | None = None) PromptVersion[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
创建现有提示的新版本。
该方法直接委托给 store,在与 Unity Catalog registries 一起使用时提供完整的 Unity Catalog 支持。
- Parameters
name – 提示的名称。
template – 此版本的提示模板内容。
description – 可选的提示版本描述。
tags – 可选的提示版本标签字典。
response_format – 可选的 Pydantic 类或字典,用于定义预期的响应结构。可用于为来自 LLM 调用的结构化输出指定模式。
- Returns
一个 PromptVersion 对象。
示例:
from mlflow import MlflowClient client = MlflowClient() prompt_version = client.create_prompt_version( name="my_prompt", template="Respond as a {{style}} assistant: {{query}}", description="Added style parameter", tags={"author": "alice"}, )
- create_registered_model(name: str, tags: Optional[dict[str, typing.Any]] = None, description: Optional[str] = None, deployment_job_id: Optional[str] = None) RegisteredModel[source]
在后端存储中创建一个新的已注册模型。
- Parameters
name – 新模型的名称。期望在后端存储中是唯一的。
tags – 一个由键值对组成的字典,这些键值对会被转换成
mlflow.entities.model_registry.RegisteredModelTag对象。description – 模型的描述。
deployment_job_id – 可选的部署作业 ID。
- Returns
由后端创建的
mlflow.entities.model_registry.RegisteredModel的单个对象。
import mlflow from mlflow import MlflowClient def print_registered_model_info(rm): print(f"name: {rm.name}") print(f"tags: {rm.tags}") print(f"description: {rm.description}") name = "SocialMediaTextAnalyzer" tags = {"nlp.framework": "Spark NLP"} desc = "This sentiment analysis model classifies the tone-happy, sad, angry." mlflow.set_tracking_uri("sqlite:///mlruns.db") client = MlflowClient() client.create_registered_model(name, tags, desc) print_registered_model_info(client.get_registered_model(name))
- create_run(experiment_id: str, start_time: Optional[int] = None, tags: Optional[dict[str, typing.Any]] = None, run_name: Optional[str] = None) Run[source]
创建一个
mlflow.entities.Run对象,可与指标、参数、工件等关联。 与mlflow.projects.run()不同,创建对象但不运行代码。 与mlflow.start_run()不同,不会更改由mlflow.log_param()使用的“活动运行”。- Parameters
experiment_id – 要在其中创建运行的实验的字符串 ID。
start_time – 如果未提供,则使用当前时间戳。
tags – 一个键值对的字典,转换为
mlflow.entities.RunTag对象。run_name – 此运行的名称。
- Returns
mlflow.entities.Run已创建。
from mlflow import MlflowClient # Create a run with a tag under the default experiment (whose id is '0'). tags = {"engineering": "ML Platform"} name = "platform-run-24" client = MlflowClient() experiment_id = "0" run = client.create_run(experiment_id, tags=tags, run_name=name) # Show newly created run metadata info print(f"Run tags: {run.data.tags}") print(f"Experiment id: {run.info.experiment_id}") print(f"Run id: {run.info.run_id}") print(f"Run name: {run.info.run_name}") print(f"lifecycle_stage: {run.info.lifecycle_stage}") print(f"status: {run.info.status}")
- create_webhook(name: str, url: str, events: list[typing.Union[typing.Literal['registered_model.created', 'model_version.created', 'model_version_tag.set', 'model_version_tag.deleted', 'model_version_alias.created', 'model_version_alias.deleted'], WebhookEvent]], description: Optional[str] = None, secret: Optional[str] = None, status: Optional[Union[str, WebhookStatus]] = None) Webhook[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
创建一个新的 webhook。
- Parameters
name – Webhook 的名称。
url – Webhook 端点的 URL。
events – 触发此 webhook 的事件列表。可以是字符串或 WebhookEvent 对象。
description – 可选的 webhook 描述。
secret – 可选的 secret,用于 HMAC 签名验证。
status – Webhook 状态(默认为 ACTIVE)。可以是字符串或 WebhookStatus 枚举。 有效状态:“ACTIVE”、“DISABLED”
- Returns
一个
Webhook对象,表示已创建的 webhook。
- delete_experiment(experiment_id: str) None[source]
从后端存储中删除一个实验。
此删除为软删除,而非永久删除。实验名称不能被重新使用,除非被删除的实验由数据库管理员永久删除。
- Parameters
experiment_id – 从
create_experiment返回的实验 ID。
from mlflow import MlflowClient # Create an experiment with a name that is unique and case sensitive client = MlflowClient() experiment_id = client.create_experiment("New Experiment") client.delete_experiment(experiment_id) # Examine the deleted experiment details. experiment = client.get_experiment(experiment_id) print(f"Name: {experiment.name}") print(f"Artifact Location: {experiment.artifact_location}") print(f"Lifecycle_stage: {experiment.lifecycle_stage}")
- delete_experiment_tag(experiment_id: str, key: str) None[source]
从具有指定 ID 的实验中删除一个标签。
- Parameters
experiment_id – 实验的字符串 ID。
key – 要删除的标签的名称。
from mlflow import MlflowClient # Create an experiment and set its tag client = MlflowClient() experiment_id = client.create_experiment("Social Media NLP Experiments") client.set_experiment_tag(experiment_id, "nlp.framework", "Spark NLP") # Fetch experiment metadata information, validate that tag is set experiment = client.get_experiment(experiment_id) assert experiment.tags == {"nlp.framework": "Spark NLP"} client.delete_experiment_tag(experiment_id, "nlp.framework") # Fetch experiment metadata information, validate that tag is deleted experiment = client.get_experiment(experiment_id) assert experiment.tags == {}
- delete_logged_model(model_id: str) None[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
删除具有指定 ID 的已记录模型。
- Parameters
model_id – 要删除的模型的 ID。
- delete_logged_model_tag(model_id: str, key: str) None[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
从指定的已记录模型中删除一个标签。
- Parameters
model_id – 模型的 ID。
key – 要删除的标签键。
- delete_model_version(name: str, version: str) None[source]
在后端删除模型版本。
- Parameters
name – 包含的注册模型的名称。
version – 模型版本的版本号。
import mlflow.sklearn from mlflow import MlflowClient from mlflow.models import infer_signature from sklearn.datasets import make_regression from sklearn.ensemble import RandomForestRegressor def print_models_info(mv): for m in mv: print(f"name: {m.name}") print(f"latest version: {m.version}") print(f"run_id: {m.run_id}") print(f"current_stage: {m.current_stage}") mlflow.set_tracking_uri("sqlite:///mlruns.db") X, y = make_regression(n_features=4, n_informative=2, random_state=0, shuffle=False) # Create two runs and log MLflow entities with mlflow.start_run() as run1: params = {"n_estimators": 3, "random_state": 42} rfr = RandomForestRegressor(**params).fit(X, y) signature = infer_signature(X, rfr.predict(X)) mlflow.log_params(params) mlflow.sklearn.log_model(rfr, name="sklearn-model", signature=signature) with mlflow.start_run() as run2: params = {"n_estimators": 6, "random_state": 42} rfr = RandomForestRegressor(**params).fit(X, y) signature = infer_signature(X, rfr.predict(X)) mlflow.log_params(params) mlflow.sklearn.log_model(rfr, name="sklearn-model", signature=signature) # Register model name in the model registry name = "RandomForestRegression" client = MlflowClient() client.create_registered_model(name) # Create a two versions of the rfr model under the registered model name for run_id in [run1.info.run_id, run2.info.run_id]: model_uri = f"runs:/{run_id}/sklearn-model" mv = client.create_model_version(name, model_uri, run_id) print(f"model version {mv.version} created") print("--") # Fetch latest version; this will be version 2 models = client.get_latest_versions(name, stages=["None"]) print_models_info(models) print("--") # Delete the latest model version 2 print(f"Deleting model version {mv.version}") client.delete_model_version(name, mv.version) models = client.get_latest_versions(name, stages=["None"]) print_models_info(models)
model version 1 created model version 2 created -- name: RandomForestRegression latest version: 2 run_id: 9881172ef10f4cb08df3ed452c0c362b current_stage: None -- Deleting model version 2 name: RandomForestRegression latest version: 1 run_id: 9165d4f8aa0a4d069550824bdc55caaf current_stage: None
- delete_model_version_tag(name: str, version: Optional[str] = None, key: Optional[str] = None, stage: Optional[str] = None) None[source]
删除与模型版本关联的标签。
当设置了 stage 时,tag 将从该 stage 的最新模型版本中被删除。设置 version 和 stage 参数会导致错误。
- Parameters
name – 已注册模型名称。
version – 注册的模型版本。
key – 标签 key. key 是必需的.
stage – 注册模型阶段。
import mlflow.sklearn from mlflow import MlflowClient from mlflow.models import infer_signature from sklearn.datasets import make_regression from sklearn.ensemble import RandomForestRegressor def print_model_version_info(mv): print(f"Name: {mv.name}") print(f"Version: {mv.version}") print(f"Tags: {mv.tags}") mlflow.set_tracking_uri("sqlite:///mlruns.db") params = {"n_estimators": 3, "random_state": 42} name = "RandomForestRegression" X, y = make_regression(n_features=4, n_informative=2, random_state=0, shuffle=False) rfr = RandomForestRegressor(**params).fit(X, y) signature = infer_signature(X, rfr.predict(X)) # Log MLflow entities with mlflow.start_run() as run: mlflow.log_params(params) mlflow.sklearn.log_model(rfr, name="sklearn-model", signature=signature) # Register model name in the model registry client = MlflowClient() client.create_registered_model(name) # Create a new version of the rfr model under the registered model name # and delete a tag model_uri = f"runs:/{run.info.run_id}/sklearn-model" tags = {"t": "1", "t1": "2"} mv = client.create_model_version(name, model_uri, run.info.run_id, tags=tags) print_model_version_info(mv) print("--") # using version to delete tag client.delete_model_version_tag(name, mv.version, "t") # using stage to delete tag client.delete_model_version_tag(name, key="t1", stage=mv.current_stage) mv = client.get_model_version(name, mv.version) print_model_version_info(mv)
- delete_prompt(name: str) None[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
从注册表中删除一个提示。
对于 Unity Catalog 注册表,该方法首先检查提示是否存在任何版本,如果发现未删除的版本则抛出错误。在删除提示本身之前,必须先显式删除所有版本。
对于其他注册表,该提示会在不进行版本检查的情况下正常删除。
- Parameters
name – 要删除的提示的名称。
示例:
from mlflow import MlflowClient client = MlflowClient() # For Unity Catalog, delete all versions first if client.get_registry_uri().startswith("databricks-uc"): versions = client.search_prompt_versions("my_prompt") for version in versions.prompt_versions: client.delete_prompt_version("my_prompt", version.version) # Then delete the prompt client.delete_prompt("my_prompt")
- delete_prompt_alias(name: str, alias: str) None[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
为
Prompt删除一个别名。- Parameters
name – 提示的名称。
alias – 要为提示删除的别名。
- delete_prompt_tag(name: str, key: str) None[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
从提示中删除一个标签。
该方法直接委托给 store,在与 Unity Catalog registries 一起使用时提供完整的 Unity Catalog 支持。
- Parameters
name – 提示的名称。
key – 要删除的标签键。
示例:
from mlflow import MlflowClient client = MlflowClient() client.delete_prompt_tag("my_prompt", "environment")
- delete_prompt_version(name: str, version: str) None[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
删除特定的提示版本。
该方法直接委托给 store,在与 Unity Catalog registries 一起使用时提供完整的 Unity Catalog 支持。
- Parameters
name – 提示的名称。
version – 要删除的提示的版本。
示例:
from mlflow import MlflowClient client = MlflowClient() client.delete_prompt_version("my_prompt", "1")
- delete_prompt_version_tag(name: str, version: str | int, key: str) None[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
从特定的提示版本中删除一个标签。
- Parameters
name – 提示的名称。
version – 提示的版本号。
key – 要删除的标签键。
- delete_registered_model(name: str)[source]
删除已注册模型。如果不存在具有给定名称的已注册模型,后端会抛出异常。
- Parameters
name – 要删除的已注册模型的名称。
import mlflow from mlflow import MlflowClient def print_registered_models_info(r_models): print("--") for rm in r_models: print(f"name: {rm.name}") print(f"tags: {rm.tags}") print(f"description: {rm.description}") mlflow.set_tracking_uri("sqlite:///mlruns.db") client = MlflowClient() # Register a couple of models with respective names, tags, and descriptions for name, tags, desc in [ ("name1", {"t1": "t1"}, "description1"), ("name2", {"t2": "t2"}, "description2"), ]: client.create_registered_model(name, tags, desc) # Fetch all registered models print_registered_models_info(client.search_registered_models()) # Delete one registered model and fetch again client.delete_registered_model("name1") print_registered_models_info(client.search_registered_models())
- delete_registered_model_alias(name: str, alias: str) None[source]
删除与已注册模型关联的别名。
- Parameters
name – 已注册模型名称。
alias – 别名的名称。
import mlflow from mlflow import MlflowClient from mlflow.models import infer_signature from sklearn.datasets import make_regression from sklearn.ensemble import RandomForestRegressor def print_model_info(rm): print("--Model--") print("name: {}".format(rm.name)) print("aliases: {}".format(rm.aliases)) def print_model_version_info(mv): print("--Model Version--") print("Name: {}".format(mv.name)) print("Version: {}".format(mv.version)) print("Aliases: {}".format(mv.aliases)) mlflow.set_tracking_uri("sqlite:///mlruns.db") params = {"n_estimators": 3, "random_state": 42} name = "RandomForestRegression" X, y = make_regression(n_features=4, n_informative=2, random_state=0, shuffle=False) rfr = RandomForestRegressor(**params).fit(X, y) signature = infer_signature(X, rfr.predict(X)) # Log MLflow entities with mlflow.start_run() as run: mlflow.log_params(params) mlflow.sklearn.log_model(rfr, artifact_path="sklearn-model", signature=signature) # Register model name in the model registry client = MlflowClient() client.create_registered_model(name) model = client.get_registered_model(name) print_model_info(model) # Create a new version of the rfr model under the registered model name model_uri = "runs:/{}/sklearn-model".format(run.info.run_id) mv = client.create_model_version(name, model_uri, run.info.run_id) print_model_version_info(mv) # Set registered model alias client.set_registered_model_alias(name, "test-alias", mv.version) print() print_model_info(model) print_model_version_info(mv) # Delete registered model alias client.delete_registered_model_alias(name, "test-alias") print() print_model_info(model) print_model_version_info(mv)
--Model-- name: RandomForestRegression aliases: {} --Model Version-- Name: RandomForestRegression Version: 1 Aliases: [] --Model-- name: RandomForestRegression aliases: {"test-alias": "1"} --Model Version-- Name: RandomForestRegression Version: 1 Aliases: ["test-alias"] --Model-- name: RandomForestRegression aliases: {} --Model Version-- Name: RandomForestRegression Version: 1 Aliases: []
- delete_registered_model_tag(name: str, key: str) None[source]
删除与已注册模型关联的标签。
- Parameters
name – 已注册模型名称。
key – 已注册模型标签键。
import mlflow from mlflow import MlflowClient def print_registered_models_info(r_models): print("--") for rm in r_models: print(f"name: {rm.name}") print(f"tags: {rm.tags}") mlflow.set_tracking_uri("sqlite:///mlruns.db") client = MlflowClient() # Register a couple of models with respective names and tags for name, tags in [("name1", {"t1": "t1"}), ("name2", {"t2": "t2"})]: client.create_registered_model(name, tags) # Fetch all registered models print_registered_models_info(client.search_registered_models()) # Delete a tag from model `name2` client.delete_registered_model_tag("name2", "t2") print_registered_models_info(client.search_registered_models())
- delete_run(run_id: str) None[source]
删除具有给定 ID 的运行。
- Parameters
run_id – 要删除的唯一运行 ID。
from mlflow import MlflowClient # Create a run under the default experiment (whose id is '0'). client = MlflowClient() experiment_id = "0" run = client.create_run(experiment_id) run_id = run.info.run_id print(f"run_id: {run_id}; lifecycle_stage: {run.info.lifecycle_stage}") print("--") client.delete_run(run_id) del_run = client.get_run(run_id) print(f"run_id: {run_id}; lifecycle_stage: {del_run.info.lifecycle_stage}")
- delete_tag(run_id: str, key: str) None[source]
从运行中删除一个标签。此操作不可逆。
- Parameters
run_id – 运行的字符串 ID。
key – 标签的名称。
from mlflow import MlflowClient def print_run_info(run): print(f"run_id: {run.info.run_id}") print(f"Tags: {run.data.tags}") # Create a run under the default experiment (whose id is '0'). client = MlflowClient() tags = {"t1": 1, "t2": 2} experiment_id = "0" run = client.create_run(experiment_id, tags=tags) print_run_info(run) print("--") # Delete tag and fetch updated info client.delete_tag(run.info.run_id, "t1") run = client.get_run(run.info.run_id) print_run_info(run)
- delete_trace_tag(trace_id: str, key: str) None[source]
在具有给定 trace ID 的 trace 上删除一个标签。
该跟踪可以是正在活动的,也可以是已经结束并记录在后端。下面是一个在活动跟踪上删除标签的示例。您可以替换
trace_id参数以在已结束的跟踪上删除标签。from mlflow import MlflowClient client = MlflowClient() root_span = client.start_trace("my_trace", tags={"key": "value"}) client.delete_trace_tag(root_span.trace_id, "key") client.end_trace(root_span.trace_id)
- Parameters
trace_id – 要从中删除标签的 trace 的 ID。
key – 标签的字符串键。必须最多为 250 个字符,否则在存储时会被截断。
- delete_traces(experiment_id: str, max_timestamp_millis: Optional[int] = None, max_traces: Optional[int] = None, trace_ids: Optional[list[str]] = None) int[source]
根据指定条件删除跟踪。
必须指定 max_timestamp_millis 或 trace_ids 中的一个,但不能同时指定两者。
max_traces 在指定 trace_ids 时不能被指定。
- Parameters
experiment_id – 关联实验的 ID。
max_timestamp_millis – 用于删除跟踪的最大时间戳(以自 UNIX 纪元起的毫秒为单位)。早于或等于此时间戳的跟踪将被删除。
max_traces – 要删除的最大跟踪记录数。如果指定了 max_traces,且它小于基于 max_timestamp_millis 将被删除的跟踪记录数,则会先删除最旧的跟踪记录。
trace_ids – 要删除的一组 trace IDs。
- Returns
已删除的跟踪数。
示例:
import mlflow import time client = mlflow.MlflowClient() # Delete all traces in the experiment client.delete_traces( experiment_id="0", max_timestamp_millis=time.time_ns() // 1_000_000 ) # Delete traces based on max_timestamp_millis and max_traces # Older traces will be deleted first. some_timestamp = time.time_ns() // 1_000_000 client.delete_traces( experiment_id="0", max_timestamp_millis=some_timestamp, max_traces=2 ) # Delete traces based on trace_ids client.delete_traces(experiment_id="0", trace_ids=["id_1", "id_2"])
- delete_webhook(webhook_id: str) None[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
删除一个 webhook。
- Parameters
webhook_id – 要删除的 Webhook ID。
- Returns
无
- detach_prompt_from_run(run_id: str, prompt_uri: str) None[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
将注册在 MLflow Prompt Registry 中的提示从 MLflow Run 中分离。
- Parameters
run_id – 要将提示记录到的运行的 ID。
prompt_uri – 提示的 URI,格式为 “prompts:/name/version”。
- download_artifacts(run_id: str, path: str, dst_path: Optional[str] = None) str[source]
如果适用,将运行中的 artifact 文件或目录下载到本地目录,并返回其本地路径。
- Parameters
run_id – 要从中下载工件的运行。
path – 相对于所需 artifact 的源路径。
dst_path – 本地文件系统目标目录的绝对路径,用于下载指定的工件。该目录必须已存在。如果未指定,工件要么会被下载到本地文件系统中一个新建的、唯一命名的目录,要么在 LocalArtifactRepository 的情况下被直接返回。
- Returns
所需工件的本地路径。
import os import mlflow from mlflow import MlflowClient features = "rooms, zipcode, median_price, school_rating, transport" with open("features.txt", "w") as f: f.write(features) # Log artifacts with mlflow.start_run() as run: mlflow.log_artifact("features.txt", artifact_path="features") # Download artifacts client = MlflowClient() local_dir = "/tmp/artifact_downloads" if not os.path.exists(local_dir): os.mkdir(local_dir) local_path = client.download_artifacts(run.info.run_id, "features", local_dir) print(f"Artifacts downloaded in: {local_path}") print(f"Artifacts: {os.listdir(local_path)}")
- end_span(trace_id: str, span_id: str, outputs: Optional[Any] = None, attributes: dict[str, typing.Any] | None = None, status: SpanStatus | str = 'OK', end_time_ns: int | None = None)[source]
结束具有给定 trace ID 和 span ID 的 span。
- Parameters
trace_id – 要结束的跟踪的 ID。
span_id – 要结束的 span 的 ID。
outputs – 要在 span 上设置的输出。
attributes – 一个用于在 span 上设置属性的字典。如果该 span 已经有属性,新属性将与已有属性合并。如果存在相同的键,新值将覆盖旧值。
status – The status of the span. This can be a
SpanStatusobject or a string representing the status code defined inSpanStatusCodee.g."OK","ERROR". The default status is OK.end_time_ns – 跨度的结束时间,单位为自 UNIX 纪元以来的纳秒。 如果未提供,将使用当前时间。
- end_trace(trace_id: str, outputs: Optional[Any] = None, attributes: dict[str, typing.Any] | None = None, status: SpanStatus | str = 'OK', end_time_ns: int | None = None)[source]
使用给定的 trace ID 结束该 trace。 这将结束 trace 的 root span,并在已配置的情况下将 trace 记录到后端。
如果任何子 span 未结束,它们将被强制以状态
TRACE_STATUS_UNSPECIFIED结束。如果该跟踪已经结束,此方法将无效。- Parameters
trace_id – 要结束的跟踪记录的 ID。
outputs – 要在 trace 上设置的输出。
attributes – 用于在 trace 上设置属性的字典。如果 trace 已经有属性,新属性将与现有属性合并。如果相同的键已存在,新的值将覆盖旧的值。
status – The status of the trace. This can be a
SpanStatusobject or a string representing the status code defined inSpanStatusCodee.g."OK","ERROR". The default status is OK.end_time_ns – 跟踪的结束时间,自 UNIX 纪元起的纳秒。
- finalize_logged_model(model_id: str, status: Union[Literal['READY', 'FAILED'], LoggedModelStatus]) LoggedModel[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
通过更新模型的状态来完成模型的最终处理。
- Parameters
model_id – 要完成的模型的 ID。
status – 要在模型上设置的最终状态。
- Returns
更新后的模型。
- get_experiment(experiment_id: str) 实验[source]
通过 experiment_id 从后端存储检索实验
- Parameters
experiment_id – 从
create_experiment返回的实验 ID。- Returns
from mlflow import MlflowClient client = MlflowClient() exp_id = client.create_experiment("Experiment") experiment = client.get_experiment(exp_id) # Show experiment info print(f"Name: {experiment.name}") print(f"Experiment ID: {experiment.experiment_id}") print(f"Artifact Location: {experiment.artifact_location}") print(f"Lifecycle_stage: {experiment.lifecycle_stage}")
- get_experiment_by_name(name: str) 实验 | None[source]
通过实验名称从后端存储中检索实验
- Parameters
name – 实验名称,区分大小写。
- Returns
如果存在具有指定名称的实验,则返回一个
mlflow.entities.Experiment,否则返回 None。
from mlflow import MlflowClient # Case-sensitive name client = MlflowClient() experiment = client.get_experiment_by_name("Default") # Show experiment info print(f"Name: {experiment.name}") print(f"Experiment ID: {experiment.experiment_id}") print(f"Artifact Location: {experiment.artifact_location}") print(f"Lifecycle_stage: {experiment.lifecycle_stage}")
- get_latest_versions(name: str, stages: list[str] | None = None) list[ModelVersion][source]
警告
mlflow.tracking.client.MlflowClient.get_latest_versions自 2.9.0 起已弃用。模型注册阶段将在未来的主要版本中移除。要了解有关模型注册阶段弃用的更多信息,请参阅我们的迁移指南: https://mlflow.org/docs/latest/model-registry.html#migrating-from-stages每个请求阶段的最新版本模型。如果未提供
stages,则返回每个阶段的最新版本。- Parameters
name – 要从中获取最新版本的已注册模型的名称。
stages – 所需 stages 的列表。如果输入的列表为 None,则返回 ALL_STAGES 的最新版本。
- Returns
以下是
mlflow.entities.model_registry.ModelVersion对象的列表。
import mlflow.sklearn from mlflow import MlflowClient from mlflow.models import infer_signature from sklearn.datasets import make_regression from sklearn.ensemble import RandomForestRegressor def print_models_info(mv): for m in mv: print(f"name: {m.name}") print(f"latest version: {m.version}") print(f"run_id: {m.run_id}") print(f"current_stage: {m.current_stage}") mlflow.set_tracking_uri("sqlite:///mlruns.db") X, y = make_regression(n_features=4, n_informative=2, random_state=0, shuffle=False) # Create two runs Log MLflow entities with mlflow.start_run() as run1: params = {"n_estimators": 3, "random_state": 42} rfr = RandomForestRegressor(**params).fit(X, y) signature = infer_signature(X, rfr.predict(X)) mlflow.log_params(params) mlflow.sklearn.log_model(rfr, name="sklearn-model", signature=signature) with mlflow.start_run() as run2: params = {"n_estimators": 6, "random_state": 42} rfr = RandomForestRegressor(**params).fit(X, y) signature = infer_signature(X, rfr.predict(X)) mlflow.log_params(params) mlflow.sklearn.log_model(rfr, name="sklearn-model", signature=signature) # Register model name in the model registry name = "RandomForestRegression" client = MlflowClient() client.create_registered_model(name) # Create a two versions of the rfr model under the registered model name for run_id in [run1.info.run_id, run2.info.run_id]: model_uri = f"runs:/{run_id}/sklearn-model" mv = client.create_model_version(name, model_uri, run_id) print(f"model version {mv.version} created") # Fetch latest version; this will be version 2 print("--") print_models_info(client.get_latest_versions(name, stages=["None"]))
- get_logged_model(model_id: str) LoggedModel[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
获取具有指定 ID 的已记录模型。
- Parameters
model_id – 要获取的模型的 ID。
- Returns
获取的模型。
- get_metric_history(run_id: str, key: str) list[指标][source]
返回一个指标对象列表,包含为给定指标记录的所有值。
- Parameters
run_id – 用于运行的唯一标识符。
key – 运行中的指标名称。
- Returns
如果已记录,则返回
mlflow.entities.Metric实体的列表,否则为空列表。
from mlflow import MlflowClient def print_metric_info(history): for m in history: print(f"name: {m.key}") print(f"value: {m.value}") print(f"step: {m.step}") print(f"timestamp: {m.timestamp}") print("--") # Create a run under the default experiment (whose id is "0"). Since this is low-level # CRUD operation, the method will create a run. To end the run, you'll have # to explicitly end it. client = MlflowClient() experiment_id = "0" run = client.create_run(experiment_id) print(f"run_id: {run.info.run_id}") print("--") # Log couple of metrics, update their initial value, and fetch each # logged metrics' history. for k, v in [("m1", 1.5), ("m2", 2.5)]: client.log_metric(run.info.run_id, k, v, step=0) client.log_metric(run.info.run_id, k, v + 1, step=1) print_metric_info(client.get_metric_history(run.info.run_id, k)) client.set_terminated(run.info.run_id)
- get_model_version(name: str, version: str) ModelVersion[source]
将 docstring 的 args 和 returns 转换为 google 风格。
- Parameters
name – 包含的注册模型的名称。
version – 作为模型 version 的整数版本号。
- Returns
import mlflow.sklearn from mlflow import MlflowClient from mlflow.models import infer_signature from sklearn.datasets import make_regression from sklearn.ensemble import RandomForestRegressor X, y = make_regression(n_features=4, n_informative=2, random_state=0, shuffle=False) # Create two runs Log MLflow entities with mlflow.start_run() as run1: params = {"n_estimators": 3, "random_state": 42} rfr = RandomForestRegressor(**params).fit(X, y) signature = infer_signature(X, rfr.predict(X)) mlflow.log_params(params) mlflow.sklearn.log_model(rfr, name="sklearn-model", signature=signature) with mlflow.start_run() as run2: params = {"n_estimators": 6, "random_state": 42} rfr = RandomForestRegressor(**params).fit(X, y) signature = infer_signature(X, rfr.predict(X)) mlflow.log_params(params) mlflow.sklearn.log_model(rfr, name="sklearn-model", signature=signature) # Register model name in the model registry name = "RandomForestRegression" client = MlflowClient() client.create_registered_model(name) # Create a two versions of the rfr model under the registered model name for run_id in [run1.info.run_id, run2.info.run_id]: model_uri = f"runs:/{run_id}/sklearn-model" mv = client.create_model_version(name, model_uri, run_id) print(f"model version {mv.version} created") print("--") # Fetch the last version; this will be version 2 mv = client.get_model_version(name, mv.version) print(f"Name: {mv.name}") print(f"Version: {mv.version}")
- get_model_version_by_alias(name: str, alias: str) ModelVersion[source]
通过名称和别名获取模型版本实例。
- Parameters
name – 已注册模型名称。
alias – 别名的名称。
- Returns
A single
mlflow.entities.model_registry.ModelVersionobject.import mlflow from mlflow import MlflowClient from mlflow.models import infer_signature from sklearn.datasets import make_regression from sklearn.ensemble import RandomForestRegressor def print_model_info(rm): print("--Model--") print("name: {}".format(rm.name)) print("aliases: {}".format(rm.aliases)) def print_model_version_info(mv): print("--Model Version--") print("Name: {}".format(mv.name)) print("Version: {}".format(mv.version)) print("Aliases: {}".format(mv.aliases)) mlflow.set_tracking_uri("sqlite:///mlruns.db") params = {"n_estimators": 3, "random_state": 42} name = "RandomForestRegression" X, y = make_regression(n_features=4, n_informative=2, random_state=0, shuffle=False) rfr = RandomForestRegressor(**params).fit(X, y) signature = infer_signature(X, rfr.predict(X)) # Log MLflow entities with mlflow.start_run() as run: mlflow.log_params(params) mlflow.sklearn.log_model(rfr, artifact_path="sklearn-model", signature=signature) # Register model name in the model registry client = MlflowClient() client.create_registered_model(name) model = client.get_registered_model(name) print_model_info(model) # Create a new version of the rfr model under the registered model name model_uri = "runs:/{}/sklearn-model".format(run.info.run_id) mv = client.create_model_version(name, model_uri, run.info.run_id) print_model_version_info(mv) # Set registered model alias client.set_registered_model_alias(name, "test-alias", mv.version) print() print_model_info(model) print_model_version_info(mv) # Get model version by alias alias_mv = client.get_model_version_by_alias(name, "test-alias") print() print_model_version_info(alias_mv)
--Model-- name: RandomForestRegression aliases: {} --Model Version-- Name: RandomForestRegression Version: 1 Aliases: [] --Model-- name: RandomForestRegression aliases: {"test-alias": "1"} --Model Version-- Name: RandomForestRegression Version: 1 Aliases: ["test-alias"] --Model Version-- Name: RandomForestRegression Version: 1 Aliases: ["test-alias"]
- get_model_version_download_uri(name: str, version: str) str[source]
获取该模型版本在模型注册表中的下载位置。
- Parameters
name – 包含的注册模型的名称。
version – 模型版本的整数形式的版本号。
- Returns
一个单一的 URI 位置,允许读取以进行下载。
import mlflow.sklearn from mlflow import MlflowClient from mlflow.models import infer_signature from sklearn.datasets import make_regression from sklearn.ensemble import RandomForestRegressor mlflow.set_tracking_uri("sqlite:///mlruns.db") params = {"n_estimators": 3, "random_state": 42} name = "RandomForestRegression" X, y = make_regression(n_features=4, n_informative=2, random_state=0, shuffle=False) rfr = RandomForestRegressor(**params).fit(X, y) signature = infer_signature(X, rfr.predict(X)) # Log MLflow entities with mlflow.start_run() as run: mlflow.log_params(params) mlflow.sklearn.log_model(rfr, name="sklearn-model", signature=signature) # Register model name in the model registry client = MlflowClient() client.create_registered_model(name) # Create a new version of the rfr model under the registered model name model_uri = f"runs:/{run.info.run_id}/sklearn-model" mv = client.create_model_version(name, model_uri, run.info.run_id) artifact_uri = client.get_model_version_download_uri(name, mv.version) print(f"Download URI: {artifact_uri}")
Download URI: runs:/027d7bbe81924c5a82b3e4ce979fcab7/sklearn-model
- get_model_version_stages(name: str, version: str) list[str][source]
警告
mlflow.tracking.client.MlflowClient.get_model_version_stages自 2.9.0 起已弃用。模型注册阶段将在未来的主要版本中被移除。要了解有关模型注册阶段弃用的更多信息,请参阅我们的迁移指南: https://mlflow.org/docs/latest/model-registry.html#migrating-from-stages这是一个文档字符串。这里是信息。
- Returns
有效阶段列表。
import mlflow.sklearn from mlflow import MlflowClient from mlflow.models import infer_signature from sklearn.datasets import make_regression from sklearn.ensemble import RandomForestRegressor mlflow.set_tracking_uri("sqlite:///mlruns.db") params = {"n_estimators": 3, "random_state": 42} name = "RandomForestRegression" X, y = make_regression(n_features=4, n_informative=2, random_state=0, shuffle=False) rfr = RandomForestRegressor(**params).fit(X, y) signature = infer_signature(X, rfr.predict(X)) # Log MLflow entities with mlflow.start_run() as run: mlflow.log_params(params) mlflow.sklearn.log_model(rfr, name="sklearn-model", signature=signature) # Register model name in the model registry client = MlflowClient() client.create_registered_model(name) # Create a new version of the rfr model under the registered model name # fetch valid stages model_uri = f"runs:/{run.info.run_id}/models/sklearn-model" mv = client.create_model_version(name, model_uri, run.info.run_id) stages = client.get_model_version_stages(name, mv.version) print(f"Model list of valid stages: {stages}")
- get_parent_run(run_id: str) Run | None[source]
获取给定 run id 的父运行(如果存在)。
- Parameters
run_id – 子运行的唯一标识符。
- Returns
如果父运行存在,则返回单个
mlflow.entities.Run对象。否则,返回 None。
import mlflow from mlflow import MlflowClient # Create nested runs with mlflow.start_run(): with mlflow.start_run(nested=True) as child_run: child_run_id = child_run.info.run_id client = MlflowClient() parent_run = client.get_parent_run(child_run_id) print(f"child_run_id: {child_run_id}") print(f"parent_run_id: {parent_run.info.run_id}")
- get_prompt(name: str) Prompt | None[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
通过名称获取提示元数据。
- Parameters
name – 提示的名称。
- Returns
一个 Prompt 对象,包含提示元数据,或在未找到时为 None。
示例:
from mlflow import MlflowClient client = MlflowClient() prompt = client.get_prompt("my_prompt") if prompt: print(f"Prompt: {prompt.name}") print(f"Description: {prompt.description}")
- get_prompt_version(name: str, version: str | int) PromptVersion | None[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
获取特定的提示版本。
该方法直接委托给 store,在与 Unity Catalog registries 一起使用时提供完整的 Unity Catalog 支持。
- Parameters
name – 提示的名称。
version – 提示的版本(数字或别名)。
- Returns
一个包含特定版本内容的 PromptVersion 对象,如果未找到则为 None。
示例:
from mlflow import MlflowClient client = MlflowClient() prompt_version = client.get_prompt_version("my_prompt", "1") prompt_alias = client.get_prompt_version("my_prompt", "production")
- get_prompt_version_by_alias(name: str, alias: str) PromptVersion[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
通过别名获取提示版本。
该方法直接委托给 store,在与 Unity Catalog registries 一起使用时提供完整的 Unity Catalog 支持。
- Parameters
name – 提示的名称。
alias – 提示版本的别名。
- Returns
一个 PromptVersion 对象。
示例:
from mlflow import MlflowClient client = MlflowClient() prompt_version = client.get_prompt_version_by_alias("my_prompt", "production")
- get_registered_model(name: str) RegisteredModel[source]
获取已注册的模型。
- Parameters
name – 要获取的已注册模型的名称。
- Returns
import mlflow from mlflow import MlflowClient def print_model_info(rm): print("--") print(f"name: {rm.name}") print(f"tags: {rm.tags}") print(f"description: {rm.description}") name = "SocialMediaTextAnalyzer" tags = {"nlp.framework": "Spark NLP"} desc = "This sentiment analysis model classifies the tone-happy, sad, angry." mlflow.set_tracking_uri("sqlite:///mlruns.db") client = MlflowClient() # Create and fetch the registered model client.create_registered_model(name, tags, desc) model = client.get_registered_model(name) print_model_info(model)
- get_run(run_id: str) Run[source]
从后端存储中获取该
Run。结果包含一组运行元数据 –RunInfo,以及一组运行参数、标签和指标 –RunData。它还包含一组运行输入(实验性),包括有关运行所使用数据集的信息 –RunInputs。如果为该运行记录了多个具有相同键的指标,则RunData包含每个指标在最大 step 上最近记录的值。- Parameters
run_id – 运行的唯一标识符。
- Returns
如果运行存在,则返回单个
mlflow.entities.Run对象。否则,抛出异常。
import mlflow from mlflow import MlflowClient with mlflow.start_run() as run: mlflow.log_param("p", 0) # The run has finished since we have exited the with block # Fetch the run client = MlflowClient() run = client.get_run(run.info.run_id) print(f"run_id: {run.info.run_id}") print(f"params: {run.data.params}") print(f"status: {run.info.status}")
- get_trace(trace_id: str, display=True) Trace[source]
获取与指定
trace_id匹配的跟踪。- Parameters
trace_id – 要获取的跟踪的字符串 ID。
display – 如果
True,则在笔记本上显示跟踪。
- Returns
检索到的
Trace。
- get_webhook(webhook_id: str) Webhook[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
通过 ID 获取 webhook 实例。
- Parameters
webhook_id – Webhook 标识。
- Returns
一个
Webhook对象。
- link_prompt_version_to_model(name: str, version: str, model_id: str) None[source]
将提示版本链接到模型。
- Parameters
name – 提示的名称。
version – 提示的版本。
model_id – 要将提示版本链接到的模型的 ID。
- link_prompt_version_to_run(run_id: str, prompt: str | PromptVersion) None[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
将在 MLflow Prompt Registry 注册的提示与 MLflow 运行关联。
警告
此 API 不是线程安全的。如果你在多个线程中链接提示(prompts),考虑使用锁以确保一次只有一个线程将提示链接到某个运行(run)。
- Parameters
run_id – 要将提示链接到的运行的 ID。
prompt – 一个 Prompt 对象或以 “prompts:/name/version” 格式的 prompt URI。
- link_prompt_versions_to_trace(prompt_versions: list[PromptVersion], trace_id: str) None[source]
将多个提示版本链接到一个跟踪。
- Parameters
prompt_versions – 要链接的 PromptVersion 对象列表。
trace_id – Trace ID 用于将每个提示版本关联起来。
示例
import mlflow from mlflow import MlflowClient client = MlflowClient() # Get prompt versions and link to trace prompt_v1 = client.get_prompt_version("my_prompt", "1") prompt_v2 = client.get_prompt_version("another_prompt", "2") client.link_prompt_versions_to_trace( prompt_versions=[prompt_v1, prompt_v2], trace_id="trace_123", )
- link_traces_to_run(trace_ids: list[str], run_id: str) None[source]
通过创建实体关联,将多个跟踪链接到一个运行。
- Parameters
trace_ids – 要链接到运行的 trace ID 列表。最多允许 100 条 trace。
run_id – 要将跟踪数据链接到的运行 ID。
示例
import mlflow from mlflow import MlflowClient client = MlflowClient() # Link multiple traces to a run client.link_traces_to_run( trace_ids=["trace_123", "trace_456", "trace_789"], run_id="run_abc", )
- list_artifacts(run_id: str, path=None) list[FileInfo][source]
列出某次运行的工件。
- Parameters
run_id – 要从该运行中列出工件。
path – 要列出的 run 的相对 artifact 路径。默认设置为 None 或根 artifact 路径。
- Returns
以下是
mlflow.entities.FileInfo列表
from mlflow import MlflowClient def print_artifact_info(artifact): print(f"artifact: {artifact.path}") print(f"is_dir: {artifact.is_dir}") print(f"size: {artifact.file_size}") features = "rooms zipcode, median_price, school_rating, transport" labels = "price" # Create a run under the default experiment (whose id is '0'). client = MlflowClient() experiment_id = "0" run = client.create_run(experiment_id) # Create some artifacts and log under the above run for file, content in [("features", features), ("labels", labels)]: with open(f"{file}.txt", "w") as f: f.write(content) client.log_artifact(run.info.run_id, f"{file}.txt") # Fetch the logged artifacts artifacts = client.list_artifacts(run.info.run_id) for artifact in artifacts: print_artifact_info(artifact) client.set_terminated(run.info.run_id)
- list_logged_prompts(run_id: str) list[PromptVersion][source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
列出与 MLflow Run 关联的所有提示。
- Parameters
run_id – 要列出提示的运行 ID。
- Returns
与该运行关联的
Prompt对象列表。
- list_webhooks(max_results: Optional[int] = None, page_token: Optional[str] = None) PagedList[Webhook][source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
列出 webhooks。
- Parameters
max_results – 要返回的 webhook 数量上限。
page_token – 指定下一页结果的令牌。
- Returns
一个包含 Webhook 对象的
PagedList。
- load_prompt(name_or_uri: str, version: str | int | None = None, allow_missing: bool = False) PromptVersion | None[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
加载一个来自 MLflow Prompt 注册表的
Prompt。提示可以通过名称和版本指定,或通过 URI 指定。
示例:
from mlflow import MlflowClient client = MlflowClient(registry_uri="sqlite:///prompt_registry.db") # Load a specific version of the prompt by name and version prompt = client.load_prompt("my_prompt", version=1) # Load a specific version of the prompt by URI prompt = client.load_prompt("prompts:/my_prompt/1")
- Parameters
name_or_uri – 提示的名称,或格式为 “prompts:/name/version” 的 URI。
version – 提示的版本(在使用 name 时为必需,在使用 URI 时不允许)。
allow_missing – 如果 True,则在未找到指定的 prompt 时返回 None,而不是抛出 Exception。
- load_table(experiment_id: str, artifact_file: str, run_ids: list[str] | None = None, extra_columns: list[str] | None = None) pandas.DataFrame[source]
将表从 MLflow Tracking 加载为 pandas.DataFrame。该表从指定的 artifact_file 在指定的 run_ids 中加载。extra_columns 是不在表中但使用运行信息增强并添加到 DataFrame 的列。
- Parameters
experiment_id – 要从中加载表的实验 ID。
artifact_file – 要加载的表对应的、相对于运行的 artifact 文件路径,采用 posixpath 格式(例如 “dir/file.json”)。
run_ids – 可选的 run_ids 列表,用于从中加载表格。如果未指定任何 run_ids,表格将从当前实验中的所有运行中加载。
extra_columns – 可选的额外列列表,添加到返回的 DataFrame 中。例如,如果 extra_columns=[“run_id”],那么返回的 DataFrame 将有一个名为 run_id 的列。
- Returns
- pandas.DataFrame 包含已加载的表(如果工件存在)
否则抛出 MlflowException。
import mlflow import pandas as pd from mlflow import MlflowClient table_dict = { "inputs": ["What is MLflow?", "What is Databricks?"], "outputs": ["MLflow is ...", "Databricks is ..."], "toxicity": [0.0, 0.0], } df = pd.DataFrame.from_dict(table_dict) client = MlflowClient() run = client.create_run(experiment_id="0") client.log_table(run.info.run_id, data=df, artifact_file="qabot_eval_results.json") loaded_table = client.load_table( experiment_id="0", artifact_file="qabot_eval_results.json", run_ids=[ run.info.run_id, ], # 为每行附加包含关联 run ID 的列 extra_columns=["run_id"], )
# Loads the table with the specified name for all runs in the given # experiment and joins them together import mlflow import pandas as pd from mlflow import MlflowClient table_dict = { "inputs": ["What is MLflow?", "What is Databricks?"], "outputs": ["MLflow is ...", "Databricks is ..."], "toxicity": [0.0, 0.0], } df = pd.DataFrame.from_dict(table_dict) client = MlflowClient() run = client.create_run(experiment_id="0") client.log_table(run.info.run_id, data=df, artifact_file="qabot_eval_results.json") loaded_table = client.load_table( experiment_id="0", artifact_file="qabot_eval_results.json", # Append the run ID and the parent run ID to the table extra_columns=["run_id"], )
- log_artifact(run_id, local_path, artifact_path=None) None[source]
将本地文件或目录写入远程
artifact_uri。- Parameters
run_id – String 运行的 ID。
local_path – 要写入的文件或目录的路径。
artifact_path – 如果提供,则写入
artifact_uri中的目录。
import tempfile from pathlib import Path from mlflow import MlflowClient # Create a run under the default experiment (whose id is '0'). client = MlflowClient() experiment_id = "0" run = client.create_run(experiment_id) # log and fetch the artifact with tempfile.TemporaryDirectory() as tmp_dir: path = Path(tmp_dir, "features.txt") path.write_text(features) client.log_artifact(run.info.run_id, path) artifacts = client.list_artifacts(run.info.run_id) for artifact in artifacts: print(f"artifact: {artifact.path}") print(f"is_dir: {artifact.is_dir}") client.set_terminated(run.info.run_id)
- log_artifacts(run_id: str, local_dir: str, artifact_path: Optional[str] = None) None[source]
将一个文件目录写入远程
artifact_uri。- Parameters
run_id – 运行的字符串 ID。
local_dir – 要写入文件的目录路径。
artifact_path – 如果提供,则写入
artifact_uri中的目录。
import json import tempfile from pathlib import Path # Create some artifacts data to preserve features = "rooms, zipcode, median_price, school_rating, transport" data = {"state": "TX", "Available": 25, "Type": "Detached"} with tempfile.TemporaryDirectory() as tmp_dir: tmp_dir = Path(tmp_dir) with (tmp_dir / "data.json").open("w") as f: json.dump(data, f, indent=2) with (tmp_dir / "features.json").open("w") as f: f.write(features) # Create a run under the default experiment (whose id is '0'), and log # all files in "data" to root artifact_uri/states client = MlflowClient() experiment_id = "0" run = client.create_run(experiment_id) client.log_artifacts(run.info.run_id, tmp_dir, artifact_path="states") artifacts = client.list_artifacts(run.info.run_id) for artifact in artifacts: print(f"artifact: {artifact.path}") print(f"is_dir: {artifact.is_dir}") client.set_terminated(run.info.run_id)
- log_batch(run_id: str, metrics: Sequence[指标] = (), params: Sequence[Param] = (), tags: Sequence[RunTag] = (), synchronous: Optional[bool] = None) mlflow.utils.async_logging.run_operations.RunOperations | None[source]
记录多个指标、参数和/或标签。
- Parameters
run_id – 运行的字符串 ID
metrics – 如果提供,Metric(key, value, timestamp) 实例的列表。
params – 如果提供,Param(key, value) 实例的列表。
tags – 如果提供,RunTag(key, value) 实例的列表。
synchronous – 实验性 如果为 True,则会阻塞直到指标成功记录。 如果为 False,则异步记录该指标并返回一个表示记录操作的 future。 如果为 None,则从环境变量 MLFLOW_ENABLE_ASYNC_LOGGING 中读取,若未设置则默认为 False。
- Raises
mlflow.MlflowException – 如果发生任何错误。
- Returns
当 synchronous=True 或 None 时,返回 None。 当 synchronous=False 时,返回一个
mlflow.utils.async_logging.run_operations.RunOperations实例,表示用于日志记录操作的 future。
import time from mlflow import MlflowClient from mlflow.entities import Metric, Param, RunTag def print_run_info(r): print(f"run_id: {r.info.run_id}") print(f"params: {r.data.params}") print(f"metrics: {r.data.metrics}") print(f"tags: {r.data.tags}") print(f"status: {r.info.status}") # Create MLflow entities and a run under the default experiment (whose id is '0'). timestamp = int(time.time() * 1000) metrics = [Metric("m", 1.5, timestamp, 1)] params = [Param("p", "p")] tags = [RunTag("t", "t")] experiment_id = "0" client = MlflowClient() run = client.create_run(experiment_id) # Log entities, terminate the run, and fetch run status client.log_batch(run.info.run_id, metrics=metrics, params=params, tags=tags) client.set_terminated(run.info.run_id) run = client.get_run(run.info.run_id) print_run_info(run) # To log metric in async fashion client.log_metric(run.info.run_id, "m", 1.5, synchronous=False)
- log_dict(run_id: str, dictionary: dict[str, typing.Any], artifact_file: str) None[source]
将可被 JSON/YAML 序列化的对象(例如 dict)记录为 artifact。序列化格式(JSON 或 YAML)会根据 artifact_file 的扩展名自动推断。如果文件没有扩展名或扩展名不匹配 [“.json”, “.yml”, “.yaml”] 中的任一项,则使用 JSON 格式,并且会将无法进行 JSON 序列化的对象转换为字符串。
- Parameters
run_id – 运行的字符串 ID。
dictionary – 要记录的字典。
artifact_file – 以 posixpath 格式表示的、相对于运行的 artifact 文件路径,字典将保存到该路径(例如 “dir/data.json”)。
from mlflow import MlflowClient client = MlflowClient() run = client.create_run(experiment_id="0") run_id = run.info.run_id dictionary = {"k": "v"} # Log a dictionary as a JSON file under the run's root artifact directory client.log_dict(run_id, dictionary, "data.json") # Log a dictionary as a YAML file in a subdirectory of the run's root artifact directory client.log_dict(run_id, dictionary, "dir/data.yml") # If the file extension doesn't exist or match any of [".json", ".yaml", ".yml"], # JSON format is used. mlflow.log_dict(run_id, dictionary, "data") mlflow.log_dict(run_id, dictionary, "data.txt")
- log_figure(run_id: str, figure: Union[matplotlib.figure.Figure, plotly.graph_objects.Figure], artifact_file: str, *, save_kwargs: dict[str, typing.Any] | None = None) None[source]
将图形记录为工件。支持以下图形对象:
- Parameters
run_id – 运行的字符串 ID。
figure – 要记录的图形。
artifact_file – 图像保存到的、以 posixpath 格式表示的运行相对 artifact 文件路径(例如 “dir/file.png”)。
save_kwargs – 传递给用于保存图形的方法的额外关键字参数。
import mlflow import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([0, 1], [2, 3]) run = client.create_run(experiment_id="0") client.log_figure(run.info.run_id, fig, "figure.png")
- log_image(run_id: str, image: Union[numpy.ndarray, PIL.Image.Image, mlflow.Image], artifact_file: str | None = None, key: str | None = None, step: int | None = None, timestamp: int | None = None, synchronous: bool | None = None) None[source]
在 MLflow 中记录图像,支持两种用例:
- Time-stepped image logging:
非常适合在迭代过程中(例如模型训练阶段)跟踪变化或进展。
用法:
log_image(image, key=key, step=step, timestamp=timestamp)
- Artifact file image logging:
最适合用于静态图像的日志记录场景,其中图像被直接保存为文件工件。
用法:
log_image(image, artifact_file)
- The following image formats are supported:
-
mlflow.Image: MLflow 对 PIL 图像的封装,便于记录图像。
- Numpy array support
数据类型:
bool (对记录图像掩码很有用)
整数 [0, 255]
无符号整数 [0, 255]
float [0.0, 1.0]
警告
Out-of-range integer values will raise ValueError.
超出范围的浮点值会随 min/max 自动缩放并发出警告。
形状 (H: height, W: width):
H x W (灰度)
H x W x 1 (灰度)
H x W x 3 (假定为 RGB 通道顺序)
H x W x 4 (假定为 RGBA 通道顺序)
- Parameters
run_id – 运行的字符串 ID。
image – 要记录的 image 对象。
artifact_file – 指定以 POSIX 格式的路径,用于将图像作为 artifact 存储在相对于运行根目录的位置(例如,“dir/image.png”)。此参数为向后兼容保留,不应与 key、step 或 timestamp 一起使用。
key – 用于时间步图像记录的图像名称。该字符串只能包含字母数字字符、下划线 (_)、短横线 (-)、句点 (.)、空格 ( ) 和斜杠 (/)。
step – 保存图像时的整数训练步骤(迭代)。默认值为0。
timestamp – 保存此图像的时间。默认值为当前系统时间。
synchronous – 实验性 如果为 True,则会阻塞,直到指标被成功记录。 如果为 False,则以异步方式记录该指标,并返回一个表示该记录操作的 future。如果为 None,则从环境变量 MLFLOW_ENABLE_ASYNC_LOGGING读取,若未设置则默认为 False。
import mlflow import numpy as np image = np.random.randint(0, 256, size=(100, 100, 3), dtype=np.uint8) with mlflow.start_run() as run: client = mlflow.MlflowClient() client.log_image(run.info.run_id, image, key="dogs", step=3)
import mlflow from PIL import Image image = Image.new("RGB", (100, 100)) with mlflow.start_run() as run: client = mlflow.MlflowClient() client.log_image(run.info.run_id, image, key="dogs", step=3)
import mlflow from PIL import Image # Saving an image to retrieve later. Image.new("RGB", (100, 100)).save("image.png") image = mlflow.Image("image.png") with mlflow.start_run() as run: client = mlflow.MlflowClient() client.log_image(run.info.run_id, image, key="dogs", step=3)
import mlflow import numpy as np image = np.random.randint(0, 256, size=(100, 100, 3), dtype=np.uint8) with mlflow.start_run() as run: client = mlflow.MlflowClient() client.log_image(run.info.run_id, image, "image.png")
- log_inputs(run_id: str, datasets: Optional[Sequence[DatasetInput]] = None, models: Optional[Sequence[LoggedModelInput]] = None) None[source]
将一个或多个数据集输入记录到一次运行中。
- Parameters
run_id – 运行的字符串 ID。
datasets – 列表,包含要记录的
mlflow.entities.DatasetInput实例。models – 要记录的
mlflow.entities.LoggedModelInput实例的列表。
- Raises
mlflow.MlflowException – 如果发生任何错误。
- log_metric(run_id: str, key: str, value: float, timestamp: Optional[int] = None, step: Optional[int] = None, synchronous: Optional[bool] = None, dataset_name: Optional[str] = None, dataset_digest: Optional[str] = None, model_id: Optional[str] = None) mlflow.utils.async_logging.run_operations.RunOperations | None[source]
记录与 run ID 相关的指标。
- Parameters
run_id – 指定应将指标记录到的 run_id。
key – 指标名称。此字符串只能包含字母数字、下划线 (_)、连字符 (-)、句点 (.)、空格 ( ) 和斜杠 (/)。所有后端存储将支持长度最多为 250 的 keys,但有些可能支持更大的 keys。
value – 指标值。请注意,某些特殊值(例如 +/- Infinity)可能会根据存储而被替换为其他值。例如,SQLAlchemy 存储会将 +/- Inf 替换为浮点数的最大/最小值。所有后端存储将支持长度最多为 5000 的值,但有些可能支持更大的值。
timestamp – 表示计算此指标的时间。默认为当前系统时间。
step – 整数训练步骤(迭代),指标在该步骤计算。默认值为 0。
synchronous – 实验性 如果为 True,阻塞直到指标被成功记录。 如果为 False,异步记录该指标并返回一个表示记录操作的 future。 如果为 None,则从环境变量 MLFLOW_ENABLE_ASYNC_LOGGING读取,如果未设置,则默认为 False。
dataset_name – 与指标关联的数据集的名称。如果指定了,
dataset_digest也必须提供。dataset_digest – 与该指标相关的数据集的摘要。如果指定了,
dataset_name则必须同时提供。model_id – 与该指标关联的模型的 ID。如果未指定,使用由
mlflow.set_active_model()设置的当前活动模型 ID。
- Returns
当 synchronous=True 或 None 时,返回 None。当 synchronous=False 时,返回一个
mlflow.utils.async_logging.run_operations.RunOperations实例,表示用于日志记录操作的 Future 对象。
from mlflow import MlflowClient def print_run_info(r): print(f"run_id: {r.info.run_id}") print(f"metrics: {r.data.metrics}") print(f"status: {r.info.status}") # Create a run under the default experiment (whose id is '0'). # Since these are low-level CRUD operations, this method will create a run. # To end the run, you'll have to explicitly end it. client = MlflowClient() experiment_id = "0" run = client.create_run(experiment_id) print_run_info(run) print("--") # Log the metric. Unlike mlflow.log_metric this method # does not start a run if one does not exist. It will log # the metric for the run id in the backend store. client.log_metric(run.info.run_id, "m", 1.5) client.set_terminated(run.info.run_id) run = client.get_run(run.info.run_id) print_run_info(run) # To log metric in async fashion client.log_metric(run.info.run_id, "m", 1.5, synchronous=False)
- log_model_artifact(model_id: str, local_path: str) None[source]
将工件上传到指定的已记录模型。
- Parameters
model_id – 模型的 ID。
local_path – 要上传的工件的本地路径。
- Returns
无
- log_model_artifacts(model_id: str, local_dir: str) None[source]
将一组工件上传到指定的已记录模型。
- Parameters
model_id – 模型的 ID。
local_dir – 包含要上传的工件的本地目录。
- Returns
无
- log_model_params(model_id: str, params: dict[str, str]) None[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
为已记录的模型记录参数。
- Parameters
model_id – 要为其记录参数的模型的 ID。
params – 要记录的参数字典。
- Returns
无
- log_outputs(run_id: str, models: list[LoggedModelOutput])[source]
- log_param(run_id: str, key: str, value: Any, synchronous: Optional[bool] = None) Any[source]
将一个参数(例如模型超参数)记录到 run ID 上。
- Parameters
run_id – 要将该参数记录到的运行 ID。
key – 参数名。此字符串只能包含字母数字字符、下划线 (_)、连字符 (-)、句点 (.)、空格 ( ) 和斜杠 (/)。所有后端存储都支持 keys 最多长度为 250,但有些可能支持更长的 keys。
value – 参数值,但如果不是字符串会被字符串化。所有内置的后端存储支持长度最多为6000的值,但有些可能支持更大的值。
synchronous – 实验性 如果为 True,则阻塞直到指标成功记录。 如果为 False,则异步记录该指标并返回一个表示该日志操作的 future。 如果为 None,则从环境变量 MLFLOW_ENABLE_ASYNC_LOGGING 中读取,该环境变量未设置时默认为 False。
- Returns
当 synchronous=True 或 None 时,返回参数值。 当 synchronous=False 时,返回一个
mlflow.utils.async_logging.run_operations.RunOperations实例,表示用于日志记录操作的 future。
from mlflow import MlflowClient def print_run_info(r): print(f"run_id: {r.info.run_id}") print(f"params: {r.data.params}") print(f"status: {r.info.status}") # Create a run under the default experiment (whose id is '0'). # Since these are low-level CRUD operations, this method will create a run. # To end the run, you'll have to explicitly end it. client = MlflowClient() experiment_id = "0" run = client.create_run(experiment_id) print_run_info(run) print("--") # Log the parameter. Unlike mlflow.log_param this method # does not start a run if one does not exist. It will log # the parameter in the backend store p_value = client.log_param(run.info.run_id, "p", 1) assert p_value == 1 client.set_terminated(run.info.run_id) run = client.get_run(run.info.run_id) print_run_info(run)
- log_table(run_id: str, data: Union[dict[str, typing.Any], pandas.DataFrame], artifact_file: str) None[source]
将表以 JSON 工件的形式记录到 MLflow Tracking。如果 artifact_file 已经存在于运行中,数据将追加到现有的 artifact_file。
- Parameters
run_id – 运行的字符串 ID。
data – 要记录的字典或 pandas.DataFrame。
artifact_file – 以 run 为基准的 artifact 文件路径,采用 posixpath 格式,表格将保存到该路径(例如 “dir/file.json”)。
import mlflow from mlflow import MlflowClient table_dict = { "inputs": ["What is MLflow?", "What is Databricks?"], "outputs": ["MLflow is ...", "Databricks is ..."], "toxicity": [0.0, 0.0], } with mlflow.start_run() as run: client = MlflowClient() client.log_table( run.info.run_id, data=table_dict, artifact_file="qabot_eval_results.json" )
import mlflow import pandas as pd from mlflow import MlflowClient table_dict = { "inputs": ["What is MLflow?", "What is Databricks?"], "outputs": ["MLflow is ...", "Databricks is ..."], "toxicity": [0.0, 0.0], } df = pd.DataFrame.from_dict(table_dict) with mlflow.start_run() as run: client = MlflowClient() client.log_table(run.info.run_id, data=df, artifact_file="qabot_eval_results.json")
import mlflow import pandas as pd from mlflow import MlflowClient image = mlflow.Image([[1, 2, 3]]) table_dict = { "inputs": ["Show me a dog", "Show me a cat"], "outputs": [image, image], } df = pd.DataFrame.from_dict(table_dict) with mlflow.start_run() as run: client = MlflowClient() client.log_table(run.info.run_id, data=df, artifact_file="image_gen.json")
- log_text(run_id: str, text: str, artifact_file: str) None[source]
将文本记录为一个artifact。
- Parameters
run_id – 运行的字符串 ID。
text – String 包含要记录的文本。
artifact_file – 保存文本的相对于运行的 artifact 文件路径,采用 posixpath 格式(例如 “dir/file.txt”)。
from mlflow import MlflowClient client = MlflowClient() run = client.create_run(experiment_id="0") # Log text to a file under the run's root artifact directory client.log_text(run.info.run_id, "text1", "file1.txt") # Log text in a subdirectory of the run's root artifact directory client.log_text(run.info.run_id, "text2", "dir/file2.txt") # Log HTML text client.log_text(run.info.run_id, "<h1>header</h1>", "index.html")
- parse_prompt_uri(uri: str) tuple[str, str][source]
将 prompt URI 解析为 prompt 名称和 prompt 版本。 - 'prompts:/
/ ' -> (' ', ' ') - 'prompts:/ @ ' -> (' ', ' ') 此方法重用现有的模型 URI 解析逻辑,使用 prompts 前缀。
- register_prompt(name: str, template: str | list[dict[str, typing.Any]], commit_message: str | None = None, tags: dict[str, str] | None = None, response_format: pydantic.main.BaseModel | dict[str, typing.Any] | None = None) PromptVersion[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
在 MLflow Prompt 注册表中注册一个新的
Prompt。一个
Prompt至少由名称和模板内容组成。使用 MLflow Prompt Registry,您可以利用 MLflow 强大的模型跟踪框架来创建、管理并对提示进行版本控制。如果不存在具有给定名称的已注册提示,则会创建一个新的提示。否则,将创建现有提示的新版本。
示例:
from mlflow import MlflowClient from pydantic import BaseModel # Your prompt registry URI client = MlflowClient(registry_uri="sqlite:///prompt_registry.db") # Register a text prompt client.register_prompt( name="greeting_prompt", template="Respond to the user's message as a {{style}} AI.", response_format={"type": "string", "description": "A friendly response"}, ) # Register a chat prompt with multiple messages client.register_prompt( name="assistant_prompt", template=[ {"role": "system", "content": "You are a helpful {{style}} assistant."}, {"role": "user", "content": "{{question}}"}, ], response_format={"type": "object", "properties": {"answer": {"type": "string"}}}, ) # Load the prompt from the registry prompt = client.load_prompt("greeting_prompt") # Use the prompt in your application import openai openai_client = openai.OpenAI() openai_client.chat.completion.create( model="gpt-4o-mini", messages=[ {"role": "system", "content": prompt.format(style="friendly")}, {"role": "user", "content": "Hello, how are you?"}, ], ) # Update the prompt with a new version prompt = client.register_prompt( name="greeting_prompt", template="Respond to the user's message as a {{style}} AI. {{greeting}}", commit_message="Add a greeting to the prompt.", tags={"author": "Bob"}, )
- Parameters
name – 提示的名称。
template –
提示的模板内容。可以是以下任意一种:
一个包含文本的字符串,其中变量用双大括号括起,例如 {{variable}},这些变量将由 format 方法替换为实际值。
一个表示聊天消息的字典列表,其中每条消息都有 ‘role’ 和 ‘content’ 键(例如,[{“role”: “user”, “content”: “Hello {{name}}”}])
commit_message – 一个描述对提示所做更改的消息,类似于 Git 提交消息。可选。
tags – 与 prompt version 关联的标签字典。这对于存储特定版本的信息很有用,例如变更的作者。可选。
response_format – 可选的 Pydantic 类或字典,用于定义预期的响应结构。它可用于为来自 LLM 调用的结构化输出指定模式。
- Returns
已创建的
Prompt对象。
- rename_experiment(experiment_id: str, new_name: str) None[source]
更新实验的名称。新名称必须唯一。
- Parameters
experiment_id – 从
create_experiment返回的实验 ID。new_name – 该实验的新名称。
from mlflow import MlflowClient def print_experiment_info(experiment): print(f"Name: {experiment.name}") print(f"Experiment_id: {experiment.experiment_id}") print(f"Lifecycle_stage: {experiment.lifecycle_stage}") # Create an experiment with a name that is unique and case sensitive client = MlflowClient() experiment_id = client.create_experiment("Social NLP Experiments") # Fetch experiment metadata information experiment = client.get_experiment(experiment_id) print_experiment_info(experiment) print("--") # Rename and fetch experiment metadata information client.rename_experiment(experiment_id, "Social Media NLP Experiments") experiment = client.get_experiment(experiment_id) print_experiment_info(experiment)
- rename_registered_model(name: str, new_name: str) RegisteredModel[source]
更新已注册模型的名称。
- Parameters
name – 要更新的已注册模型的名称。
new_name – 已注册模型的新提议名称。
- Returns
import mlflow from mlflow import MlflowClient def print_registered_model_info(rm): print(f"name: {rm.name}") print(f"tags: {rm.tags}") print(f"description: {rm.description}") name = "SocialTextAnalyzer" tags = {"nlp.framework": "Spark NLP"} desc = "This sentiment analysis model classifies the tone-happy, sad, angry." # create a new registered model name mlflow.set_tracking_uri("sqlite:///mlruns.db") client = MlflowClient() client.create_registered_model(name, tags, desc) print_registered_model_info(client.get_registered_model(name)) print("--") # rename the model new_name = "SocialMediaTextAnalyzer" client.rename_registered_model(name, new_name) print_registered_model_info(client.get_registered_model(new_name))
name: SocialTextAnalyzer tags: {'nlp.framework': 'Spark NLP'} description: This sentiment analysis model classifies the tone-happy, sad, angry. -- name: SocialMediaTextAnalyzer tags: {'nlp.framework': 'Spark NLP'} description: This sentiment analysis model classifies the tone-happy, sad, angry.
- restore_experiment(experiment_id: str) None[source]
恢复已删除的实验,除非已被永久删除。
- Parameters
experiment_id – 从
create_experiment返回的实验 ID。
from mlflow import MlflowClient def print_experiment_info(experiment): print(f"Name: {experiment.name}") print(f"Experiment Id: {experiment.experiment_id}") print(f"Lifecycle_stage: {experiment.lifecycle_stage}") # Create and delete an experiment client = MlflowClient() experiment_id = client.create_experiment("New Experiment") client.delete_experiment(experiment_id) # Examine the deleted experiment details. experiment = client.get_experiment(experiment_id) print_experiment_info(experiment) print("--") # Restore the experiment and fetch its info client.restore_experiment(experiment_id) experiment = client.get_experiment(experiment_id) print_experiment_info(experiment)
- restore_run(run_id: str) None[source]
恢复具有给定 ID 的已删除运行。
- Parameters
run_id – 用于恢复的唯一运行 ID。
from mlflow import MlflowClient # Create a run under the default experiment (whose id is '0'). client = MlflowClient() experiment_id = "0" run = client.create_run(experiment_id) run_id = run.info.run_id print(f"run_id: {run_id}; lifecycle_stage: {run.info.lifecycle_stage}") client.delete_run(run_id) del_run = client.get_run(run_id) print(f"run_id: {run_id}; lifecycle_stage: {del_run.info.lifecycle_stage}") client.restore_run(run_id) rest_run = client.get_run(run_id) print(f"run_id: {run_id}; lifecycle_stage: {rest_run.info.lifecycle_stage}")
- search_experiments(view_type: int = 1, max_results: int | None = 1000, filter_string: Optional[str] = None, order_by: Optional[list[str]] = None, page_token=None) PagedList[实验][source]
搜索与指定搜索查询匹配的实验。
- Parameters
view_type – 枚举值之一
ACTIVE_ONLY、DELETED_ONLY或ALL,定义在mlflow.entities.ViewType。max_results – 所需的最大实验数。某些服务器后端可能会施加其自己的限制。
filter_string –
筛选查询字符串(例如,
"name = 'my_experiment'"),默认为搜索所有实验。支持以下标识符、比较运算符和逻辑运算符。- 标识符
name:实验名称creation_time:实验创建时间last_update_time:实验最后更新时间tags.<tag_key>:实验标签。如果tag_key包含空格,则必须用反引号包裹(例如,"tags.`extra key`")。
- 字符串属性和标签的比较运算符
=:等于!=:不等于LIKE:区分大小写的模式匹配ILIKE:不区分大小写的模式匹配
- 数字属性的比较运算符
=:等于!=:不等于<:小于<=:小于或等于>:大于>=:大于或等于
- 逻辑运算符
AND:将两个子查询组合,如果两者都为 True 则返回 True。
order_by –
要排序的列列表。
order_by列可以包含可选的DESC或ASC值(例如,"name DESC")。默认排序为ASC,因此"name"等同于"name ASC"。如果未指定,默认为["last_update_time DESC"],这会将最近更新的实验排在最前。以下字段受支持:experiment_id: 实验 IDname: 实验名称creation_time: 实验创建时间last_update_time: 实验最后更新时间
page_token – 指定下一页结果的令牌。它应该从一次
search_experiments调用中获得。
- Returns
一个
PagedList的Experiment对象。下一页的分页令牌可以通过对象的token属性获得。
import mlflow def assert_experiment_names_equal(experiments, expected_names): actual_names = [e.name for e in experiments if e.name != "Default"] assert actual_names == expected_names, (actual_names, expected_names) mlflow.set_tracking_uri("sqlite:///:memory:") client = mlflow.MlflowClient() # Create experiments for name, tags in [ ("a", None), ("b", None), ("ab", {"k": "v"}), ("bb", {"k": "V"}), ]: client.create_experiment(name, tags=tags) # Search for experiments with name "a" experiments = client.search_experiments(filter_string="name = 'a'") assert_experiment_names_equal(experiments, ["a"]) # Search for experiments with name starting with "a" experiments = client.search_experiments(filter_string="name LIKE 'a%'") assert_experiment_names_equal(experiments, ["ab", "a"]) # Search for experiments with tag key "k" and value ending with "v" or "V" experiments = client.search_experiments(filter_string="tags.k ILIKE '%v'") assert_experiment_names_equal(experiments, ["bb", "ab"]) # Search for experiments with name ending with "b" and tag {"k": "v"} experiments = client.search_experiments(filter_string="name LIKE '%b' AND tags.k = 'v'") assert_experiment_names_equal(experiments, ["ab"]) # Sort experiments by name in ascending order experiments = client.search_experiments(order_by=["name"]) assert_experiment_names_equal(experiments, ["a", "ab", "b", "bb"]) # Sort experiments by ID in descending order experiments = client.search_experiments(order_by=["experiment_id DESC"]) assert_experiment_names_equal(experiments, ["bb", "ab", "b", "a"])
- search_logged_models(experiment_ids: list[str], filter_string: Optional[str] = None, datasets: Optional[list[dict[str, typing.Any]]] = None, max_results: Optional[int] = None, order_by: Optional[list[dict[str, typing.Any]]] = None, page_token: Optional[str] = None) PagedList[LoggedModel][source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
搜索符合指定搜索条件的已记录模型。
- Parameters
experiment_ids – 用于限定搜索范围的实验 id 列表。
filter_string –
一个类似 SQL 的过滤字符串,用于解析。过滤字符串语法支持:
- 实体说明:
attributes: attribute_name(如果未指定前缀,默认)
metrics: metrics.metric_name
parameters: params.param_name
tags: tags.tag_name
- 比较运算符:
对于数值实体(metrics 和数值属性): <, <=, >, >=, =, !=
对于字符串实体(params、tags 与字符串属性): =, !=, IN, NOT IN
多个条件可以用 ‘AND’ 连接
字符串值必须用单引号括起来
- 示例过滤字符串:
creation_time > 100
metrics.rmse > 0.5 AND params.model_type = ‘rf’
tags.release IN (‘v1.0’, ‘v1.1’)
params.optimizer != ‘adam’ AND metrics.accuracy >= 0.9
datasets –
用于指定要在其上应用指标过滤器的数据集的字典列表。 例如,带有 metrics.accuracy > 0.9 的过滤字符串和名为 “test_dataset”的数据集表示我们将返回在 test_dataset 上 accuracy > 0.9 的所有已记录的模型。任何匹配条件的数据集的指标值都会被考虑。 如果未指定数据集,则筛选器将考虑所有数据集的指标。支持以下字段:
- dataset_name (str):
必填。数据集的名称。
- dataset_digest (str):
可选。数据集的摘要。
max_results – 希望得到的已记录模型的最大数量。
order_by –
用于指定搜索结果排序的字典列表。 支持以下字段:
- field_name (str):
必需。要排序的字段名称,例如 “metrics.accuracy”。
- ascending (bool):
可选。是否按升序排列。
- dataset_name (str):
可选。如果
field_name指的是一个指标,此字段指定与该指标关联的数据集名称。只有与指定数据集名称关联的指标才会被用于排序。只有在field_name指的是一个指标时,才可以设置此字段。- dataset_digest (str):
可选。如果
field_name指的是一个指标,此字段指定与该指标关联的数据集的摘要。只有同时匹配指定的数据集名称和摘要的指标才会被用于排序。仅当同时设置了dataset_name时,才可以设置此字段。
page_token – 指定下一页结果的令牌。
- Returns
一个
PagedList的LoggedModel对象。
- search_model_versions(filter_string: Optional[str] = None, max_results: int = 10000, order_by: Optional[list[str]] = None, page_token: Optional[str] = None) PagedList[ModelVersion][source]
在后端搜索满足筛选条件的模型版本。
- Parameters
filter_string –
过滤查询字符串 (e.g.,
"name = 'a_model_name' and tag.key = 'value1'"), 默认搜索所有模型版本。支持以下标识符、比较运算符和逻辑运算符。- 标识符
name: 模型名称。source_path: 模型版本源路径。run_id: 生成该模型版本的 mlflow 运行的 id。tags.: 模型版本标签。如果tag_key包含空格,必须用反引号包裹(例如,"tags.`extra key`")。
- 比较运算符
=: 等于。!=: 不等于。LIKE: 区分大小写的模式匹配。ILIKE: 不区分大小写的模式匹配。IN: 在一个值列表中。只有run_id标识符支持IN比较运算符。
- 逻辑运算符
AND: 将两个子查询组合,当两者都为 True 时返回 True。
max_results – 所需的最大模型版本数。
order_by – 带有 ASC|DESC 注解的列名列表,用于对匹配的搜索结果进行排序。
page_token – 指定下一页结果的令牌。它应当从
search_model_versions调用中获得。
- Returns
一个 PagedList,包含满足搜索表达式的
mlflow.entities.model_registry.ModelVersion对象。下一页的分页令牌可以通过该对象的token属性获取。
import mlflow from mlflow import MlflowClient client = MlflowClient() # Get all versions of the model filtered by name model_name = "CordobaWeatherForecastModel" filter_string = f"name='{model_name}'" results = client.search_model_versions(filter_string) print("-" * 80) for res in results: print(f"name={res.name}; run_id={res.run_id}; version={res.version}") # Get the version of the model filtered by run_id run_id = "e14afa2f47a040728060c1699968fd43" filter_string = f"run_id='{run_id}'" results = client.search_model_versions(filter_string) print("-" * 80) for res in results: print(f"name={res.name}; run_id={res.run_id}; version={res.version}")
------------------------------------------------------------------------------------ name=CordobaWeatherForecastModel; run_id=eaef868ee3d14d10b4299c4c81ba8814; version=1 name=CordobaWeatherForecastModel; run_id=e14afa2f47a040728060c1699968fd43; version=2 ------------------------------------------------------------------------------------ name=CordobaWeatherForecastModel; run_id=e14afa2f47a040728060c1699968fd43; version=2
- search_prompt_versions(name: str, max_results: int | None = None, page_token: str | None = None)[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
搜索给定提示名称的提示版本。
该方法直接委托给存储。仅在 Unity Catalog 注册表中受支持。
- Parameters
name – 用于搜索版本的提示名称。
max_results – 要返回的最大版本数。
page_token – 用于分页的令牌。
- Returns
SearchPromptVersionsResponse 包含版本列表。
示例:
from mlflow import MlflowClient client = MlflowClient() response = client.search_prompt_versions("my_prompt", max_results=10) for version in response.prompt_versions: print(f"Version {version.version}: {version.description}")
- search_prompts(filter_string: str | None = None, max_results: int = 1000, page_token: str | None = None) PagedList[Prompt][source]
在 MLflow Prompt Registry 中搜索提示。
此调用返回已被标记为提示的提示的元数据(即标记为 mlflow.prompt.is_prompt=true)。我们可以通过标准注册表过滤表达式进一步限制结果。
- Parameters
filter_string (Optional[str]) – 要应用的额外注册表搜索表达式(例如“name LIKE ‘my_prompt%’”)。对于 Unity Catalog 注册表,必须包含 catalog 和 schema: “catalog = ‘catalog_name’ AND schema = ‘schema_name’”.
max_results (int) – 一页中要返回的最大提示数量。默认值为 SEARCH_MAX_RESULTS_DEFAULT(通常为 1 000)。
page_token (可选[str]) – 来自先前search_prompts调用的分页令牌;使用此值检索下一页结果。 Defaults to None.
- Returns
name: 提示名称
description: 提示描述
tags: 提示级别标签
creation_timestamp: 提示创建时间
要获取实际的提示模板内容,请使用 get_prompt() 并指定特定版本:
# 搜索提示 prompts = client.search_prompts(filter_string="name LIKE 'greeting%'") # 获取特定版本的内容 for prompt in prompts: prompt_version = client.get_prompt_version(prompt.name, version="1") print(f"Template: {prompt.template}")
检查返回对象的 .token 属性以获取后续页面。
- Return type
一个可分页的 Prompt 对象列表,表示提示元数据
- search_registered_models(filter_string: Optional[str] = None, max_results: int = 100, order_by: Optional[list[str]] = None, page_token: Optional[str] = None) PagedList[RegisteredModel][source]
在后端搜索满足筛选条件的已注册模型。
- Parameters
filter_string –
过滤查询字符串(例如 “name = ‘a_model_name’ and tag.key = ‘value1’”),默认搜索所有已注册模型。支持以下标识符、比较符和逻辑运算符。
- 标识符
name: 已注册模型名称。tags.: 已注册模型标签。如果tag_key包含空格,则必须用反引号包裹(例如 “tags.`extra key`”)。
- 比较符
=: 等于。!=: 不等于。LIKE: 区分大小写的模式匹配。ILIKE: 不区分大小写的模式匹配。
- 逻辑运算符
AND: 将两个子查询组合,只有当两者都为 True 时返回 True。
max_results – 所需的最大注册模型数量。
order_by – 带有 ASC|DESC 注解的列名列表,用于对匹配的搜索结果进行排序。
page_token – 指定下一页结果的令牌。应从
search_registered_models调用中获得。
- Returns
包含满足搜索表达式的
mlflow.entities.model_registry.RegisteredModel对象的 PagedList。下一页的分页令牌可以通过对象的token属性获取。
import mlflow from mlflow import MlflowClient client = MlflowClient() # Get search results filtered by the registered model name model_name = "CordobaWeatherForecastModel" filter_string = f"name='{model_name}'" results = client.search_registered_models(filter_string=filter_string) print("-" * 80) for res in results: for mv in res.latest_versions: print(f"name={mv.name}; run_id={mv.run_id}; version={mv.version}") # Get search results filtered by the registered model name that matches # prefix pattern filter_string = "name LIKE 'Boston%'" results = client.search_registered_models(filter_string=filter_string) print("-" * 80) for res in results: for mv in res.latest_versions: print(f"name={mv.name}; run_id={mv.run_id}; version={mv.version}") # Get all registered models and order them by ascending order of the names results = client.search_registered_models(order_by=["name ASC"]) print("-" * 80) for res in results: for mv in res.latest_versions: print(f"name={mv.name}; run_id={mv.run_id}; version={mv.version}")
------------------------------------------------------------------------------------ name=CordobaWeatherForecastModel; run_id=eaef868ee3d14d10b4299c4c81ba8814; version=1 name=CordobaWeatherForecastModel; run_id=e14afa2f47a040728060c1699968fd43; version=2 ------------------------------------------------------------------------------------ name=BostonWeatherForecastModel; run_id=ddc51b9407a54b2bb795c8d680e63ff6; version=1 name=BostonWeatherForecastModel; run_id=48ac94350fba40639a993e1b3d4c185d; version=2 ----------------------------------------------------------------------------------- name=AzureWeatherForecastModel; run_id=5fcec6c4f1c947fc9295fef3fa21e52d; version=1 name=AzureWeatherForecastModel; run_id=8198cb997692417abcdeb62e99052260; version=3 name=BostonWeatherForecastModel; run_id=ddc51b9407a54b2bb795c8d680e63ff6; version=1 name=BostonWeatherForecastModel; run_id=48ac94350fba40639a993e1b3d4c185d; version=2 name=CordobaWeatherForecastModel; run_id=eaef868ee3d14d10b4299c4c81ba8814; version=1 name=CordobaWeatherForecastModel; run_id=e14afa2f47a040728060c1699968fd43; version=2
- search_runs(experiment_ids: list[str], filter_string: str = '', run_view_type: int = 1, max_results: int = 1000, order_by: Optional[list[str]] = None, page_token: Optional[str] = None) PagedList[Run][source]
搜索符合指定条件的运行。
- Parameters
experiment_ids – 实验 ID 的列表,或单个 int 或 string id。
filter_string – 过滤查询字符串,默认搜索所有运行。
run_view_type – 在
mlflow.entities.ViewType中定义的枚举值之一:ACTIVE_ONLY、DELETED_ONLY 或 ALL。max_results – 所需的最大运行数。
order_by – 要排序的列列表(例如,“metrics.rmse”)。
order_by列可以包含可选的DESC或ASC值。默认是ASC。默认排序是先按start_time DESC排序,然后按run_id。page_token – 用于指定下一页结果的令牌。应从
search_runs调用中获取。
- Returns
一个
PagedList,包含满足搜索表达式的Run对象。如果底层跟踪存储支持分页,则可以通过返回对象的token属性获取下一页的令牌。
import mlflow from mlflow import MlflowClient from mlflow.entities import ViewType def print_run_info(runs): for r in runs: print(f"run_id: {r.info.run_id}") print(f"lifecycle_stage: {r.info.lifecycle_stage}") print(f"metrics: {r.data.metrics}") # Exclude mlflow system tags tags = {k: v for k, v in r.data.tags.items() if not k.startswith("mlflow.")} print(f"tags: {tags}") # Create an experiment and log two runs with metrics and tags under the experiment experiment_id = mlflow.create_experiment("Social NLP Experiments") with mlflow.start_run(experiment_id=experiment_id) as run: mlflow.log_metric("m", 1.55) mlflow.set_tag("s.release", "1.1.0-RC") with mlflow.start_run(experiment_id=experiment_id): mlflow.log_metric("m", 2.50) mlflow.set_tag("s.release", "1.2.0-GA") # Search all runs under experiment id and order them by # descending value of the metric 'm' client = MlflowClient() runs = client.search_runs(experiment_id, order_by=["metrics.m DESC"]) print_run_info(runs) print("--") # Delete the first run client.delete_run(run_id=run.info.run_id) # Search only deleted runs under the experiment id and use a case insensitive pattern # in the filter_string for the tag. filter_string = "tags.s.release ILIKE '%rc%'" runs = client.search_runs( experiment_id, run_view_type=ViewType.DELETED_ONLY, filter_string=filter_string ) print_run_info(runs)
run_id: 0efb2a68833d4ee7860a964fad31cb3f lifecycle_stage: active metrics: {'m': 2.5} tags: {'s.release': '1.2.0-GA'} run_id: 7ab027fd72ee4527a5ec5eafebb923b8 lifecycle_stage: active metrics: {'m': 1.55} tags: {'s.release': '1.1.0-RC'} -- run_id: 7ab027fd72ee4527a5ec5eafebb923b8 lifecycle_stage: deleted metrics: {'m': 1.55} tags: {'s.release': '1.1.0-RC'}
- search_traces(experiment_ids: list[str], filter_string: Optional[str] = None, max_results: int = 100, order_by: Optional[list[str]] = None, page_token: Optional[str] = None, run_id: Optional[str] = None, include_spans: bool = True, model_id: Optional[str] = None, sql_warehouse_id: Optional[str] = None) PagedList[Trace][source]
返回在实验中与给定的搜索表达式列表匹配的跟踪。
- Parameters
experiment_ids – 用于限定搜索范围的实验 id 列表。
filter_string – 一个搜索过滤字符串。
max_results – 所需的最大跟踪数。
order_by – order_by 子句的列表。
page_token – 指定下一页结果的令牌。它应从
search_traces调用中获取。run_id – 用于限定搜索范围。当在一个 active run 下创建 trace 时,它会与该 run 关联,您可以根据 run_id 筛选以检索该 trace。
include_spans – 如果
True,则在返回的 traces 中包含 spans。否则,仅返回 trace 元数据,例如 trace ID、开始时间、结束时间等,不包含任何 spans。model_id – 如果指定,返回与该模型 ID 关联的跟踪记录。
sql_warehouse_id – 仅在 Databricks 中使用。用于在推理表中搜索跟踪记录的 SQL 仓库的 ID。
- Returns
一个
PagedList,包含满足搜索表达式的Trace对象。如果底层跟踪存储支持分页,则可以通过返回对象的token属性获取下一页的令牌;但是,一些存储实现可能不支持分页,因此在这种情况下返回的 token 将没有意义。
- set_experiment_tag(experiment_id: str, key: str, value: Any) None[source]
在具有指定 ID 的实验上设置一个标签。值会被转换为字符串。
- Parameters
experiment_id – 实验的字符串 ID。
key – 标签的名称。
value – 标签值(已转换为字符串)。
from mlflow import MlflowClient # Create an experiment and set its tag client = MlflowClient() experiment_id = client.create_experiment("Social Media NLP Experiments") client.set_experiment_tag(experiment_id, "nlp.framework", "Spark NLP") # Fetch experiment metadata information experiment = client.get_experiment(experiment_id) print(f"Name: {experiment.name}") print(f"Tags: {experiment.tags}")
Name: Social Media NLP Experiments Tags: {'nlp.framework': 'Spark NLP'}
- set_logged_model_tags(model_id: str, tags: dict[str, typing.Any]) None[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
在指定的已记录模型上设置标签。
- Parameters
model_id – 模型的 ID。
tags – 在模型上设置的标签。
- Returns
无
- set_model_version_tag(name: str, version: Optional[str] = None, key: Optional[str] = None, value: Optional[Any] = None, stage: Optional[str] = None) None[source]
为模型版本设置标签。当设置了 stage 时,标签将被设置为该 stage 的最新模型版本。同时设置 version 和 stage 参数会导致错误。
- Parameters
name – 已注册模型名称。
version – 注册的模型版本。
key – 要记录的标签键。key 是必需的。
value – 要记录的标签值。 value 是必需的。
stage – 注册模型阶段。
import mlflow.sklearn from mlflow import MlflowClient from mlflow.models import infer_signature from sklearn.datasets import make_regression from sklearn.ensemble import RandomForestRegressor def print_model_version_info(mv): print(f"Name: {mv.name}") print(f"Version: {mv.version}") print(f"Tags: {mv.tags}") mlflow.set_tracking_uri("sqlite:///mlruns.db") params = {"n_estimators": 3, "random_state": 42} name = "RandomForestRegression" X, y = make_regression(n_features=4, n_informative=2, random_state=0, shuffle=False) rfr = RandomForestRegressor(**params).fit(X, y) signature = infer_signature(X, rfr.predict(X)) # Log MLflow entities with mlflow.start_run() as run: mlflow.log_params(params) mlflow.sklearn.log_model(rfr, name="sklearn-model", signature=signature) # Register model name in the model registry client = MlflowClient() client.create_registered_model(name) # Create a new version of the rfr model under the registered model name # and set a tag model_uri = f"runs:/{run.info.run_id}/sklearn-model" mv = client.create_model_version(name, model_uri, run.info.run_id) print_model_version_info(mv) print("--") # Tag using model version client.set_model_version_tag(name, mv.version, "t", "1") # Tag using model stage client.set_model_version_tag(name, key="t1", value="1", stage=mv.current_stage) mv = client.get_model_version(name, mv.version) print_model_version_info(mv)
- set_prompt_alias(name: str, alias: str, version: int) None[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
为
Prompt设置别名。- Parameters
name – 提示的名称。
alias – 要为提示设置的别名。
version – 提示的版本。
- set_prompt_tag(name: str, key: str, value: str) None[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
在提示上设置一个标签。
该方法直接委托给 store,在与 Unity Catalog registries 一起使用时提供完整的 Unity Catalog 支持。
- Parameters
name – 提示的名称。
key – 标签键。
value – 标签值。
示例:
from mlflow import MlflowClient client = MlflowClient() client.set_prompt_tag("my_prompt", "environment", "production")
- set_prompt_version_tag(name: str, version: str | int, key: str, value: str) None[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
在特定提示版本上设置标签。
- Parameters
name – 提示的名称。
version – 提示的版本号。
key – 标签键。
value – 标签值。
- set_registered_model_alias(name: str, alias: str, version: str) None[source]
将已注册模型的别名指向某个模型版本。
- Parameters
name – 已注册模型名称。
alias – 别名的名称。请注意,格式为
v的别名,例如v9和v42,是保留的,不能设置。version – 已注册模型的版本号。
import mlflow from mlflow import MlflowClient from mlflow.models import infer_signature from sklearn.datasets import make_regression from sklearn.ensemble import RandomForestRegressor def print_model_info(rm): print("--Model--") print("name: {}".format(rm.name)) print("aliases: {}".format(rm.aliases)) def print_model_version_info(mv): print("--Model Version--") print("Name: {}".format(mv.name)) print("Version: {}".format(mv.version)) print("Aliases: {}".format(mv.aliases)) mlflow.set_tracking_uri("sqlite:///mlruns.db") params = {"n_estimators": 3, "random_state": 42} name = "RandomForestRegression" X, y = make_regression(n_features=4, n_informative=2, random_state=0, shuffle=False) rfr = RandomForestRegressor(**params).fit(X, y) signature = infer_signature(X, rfr.predict(X)) # Log MLflow entities with mlflow.start_run() as run: mlflow.log_params(params) mlflow.sklearn.log_model(rfr, artifact_path="sklearn-model", signature=signature) # Register model name in the model registry client = MlflowClient() client.create_registered_model(name) model = client.get_registered_model(name) print_model_info(model) # Create a new version of the rfr model under the registered model name model_uri = "runs:/{}/sklearn-model".format(run.info.run_id) mv = client.create_model_version(name, model_uri, run.info.run_id) print_model_version_info(mv) # Set registered model alias client.set_registered_model_alias(name, "test-alias", mv.version) print() print_model_info(model) print_model_version_info(mv)
- set_registered_model_tag(name, key, value) None[source]
为已注册的模型设置标签。
- Parameters
name – 已注册模型名称。
key – 要记录的标签键。
value – 标签值日志。
import mlflow from mlflow import MlflowClient def print_model_info(rm): print("--") print("name: {}".format(rm.name)) print("tags: {}".format(rm.tags)) name = "SocialMediaTextAnalyzer" tags = {"nlp.framework1": "Spark NLP"} mlflow.set_tracking_uri("sqlite:///mlruns.db") client = MlflowClient() # Create registered model, set an additional tag, and fetch # update model info client.create_registered_model(name, tags, desc) model = client.get_registered_model(name) print_model_info(model) client.set_registered_model_tag(name, "nlp.framework2", "VADER") model = client.get_registered_model(name) print_model_info(model)
- set_tag(run_id: str, key: str, value: Any, synchronous: Optional[bool] = None) mlflow.utils.async_logging.run_operations.RunOperations | None[source]
在具有指定 ID 的运行上设置一个标签。值会被转换为字符串。
- Parameters
run_id – 运行的字符串 ID。
key – 标签名称。该字符串只能包含字母数字字符、下划线 (_)、连字符 (-)、句点 (.)、空格 ( ) 和斜杠 (/)。所有后端存储将支持长度不超过 250 的 keys,但有些可能支持更长的 keys。
value – 标签值,如果不是字符串将被转换为字符串。所有后端存储将支持长度最多为5000的值,但有些可能支持更大的值。
synchronous – 实验性 如果为 True,则阻塞直到指标成功记录。 如果为 False,则异步记录该指标并返回一个表示该日志操作的 future。 如果为 None,则从环境变量 MLFLOW_ENABLE_ASYNC_LOGGING 中读取,该环境变量未设置时默认为 False。
- Returns
当 synchronous=True 或 None 时,返回 None。当 synchronous=False 时,返回一个 mlflow.utils.async_logging.run_operations.RunOperations 实例,表示用于记录操作的 future 对象。
from mlflow import MlflowClient def print_run_info(run): print(f"run_id: {run.info.run_id}") print(f"Tags: {run.data.tags}") # Create a run under the default experiment (whose id is '0'). client = MlflowClient() experiment_id = "0" run = client.create_run(experiment_id) print_run_info(run) print("--") # Set a tag and fetch updated run info client.set_tag(run.info.run_id, "nlp.framework", "Spark NLP") run = client.get_run(run.info.run_id) print_run_info(run)
- set_terminated(run_id: str, status: Optional[str] = None, end_time: Optional[int] = None) None[source]
将 run 的状态设置为 terminated.
- Parameters
run_id – 要终止的运行的 ID。
status – 一个字符串值,属于
mlflow.entities.RunStatus。默认为 “FINISHED”。end_time – 如果未提供,则默认为当前时间。
from mlflow import MlflowClient def print_run_info(r): print(f"run_id: {r.info.run_id}") print(f"status: {r.info.status}") # Create a run under the default experiment (whose id is '0'). # Since this is low-level CRUD operation, this method will create a run. # To end the run, you'll have to explicitly terminate it. client = MlflowClient() experiment_id = "0" run = client.create_run(experiment_id) print_run_info(run) print("--") # Terminate the run and fetch updated status. By default, # the status is set to "FINISHED". Other values you can # set are "KILLED", "FAILED", "RUNNING", or "SCHEDULED". client.set_terminated(run.info.run_id, status="KILLED") run = client.get_run(run.info.run_id) print_run_info(run)
run_id: 575fb62af83f469e84806aee24945973 status: RUNNING -- run_id: 575fb62af83f469e84806aee24945973 status: KILLED
- set_trace_tag(trace_id: str, key: str, value: str)[source]
在具有给定 trace ID 的跟踪上设置一个标签。
跟踪可以是正在进行的,也可以是已经结束并记录在后端的。下面是为正在进行的跟踪设置标签的示例。您可以替换
trace_id参数,以在已结束的跟踪上设置标签。from mlflow import MlflowClient client = MlflowClient() root_span = client.start_trace("my_trace") client.set_trace_tag(root_span.trace_id, "key", "value") client.end_trace(root_span.trace_id)
- Parameters
trace_id – 要设置标签的 trace 的 ID。
key – 标签的字符串键。必须最多为 250 个字符,否则在存储时会被截断。
value – 标签的字符串值。长度最多为250个字符,否则存储时会被截断。
- start_span(name: str, trace_id: str, parent_id: str, span_type: str = 'UNKNOWN', inputs: Optional[Any] = None, attributes: dict[str, typing.Any] | None = None, start_time_ns: int | None = None) Span[source]
创建一个新的 span,并在不将其附加到全局跟踪上下文的情况下启动它。
这是一个命令式 API,用于手动在特定的 trace id 和父 span 下创建一个新的 span,不同于更高级别的 API,如
@mlflow.trace装饰器和with mlflow.start_span()上下文管理器,它们会自动管理 span 的生命周期和父子关系。当自动上下文管理不足以满足需求时,此 API 会很有用,例如在基于回调的检测中,span 的开始和结束不在同一调用栈中,或在多线程应用中上下文不会被自动传播的情况。
此 API 需要显式提供父 span ID。如果你还没有开始任何 span,请使用
start_trace()方法来启动一个新的追踪和一个根 span。警告
通过此方法创建的 span 需要显式调用
end_span()方法来结束。否则该 span 的结束时间和状态会被记录为不正确的TRACE_STATUS_UNSPECIFIED。提示
与其使用
start_trace()方法创建根 span,你也可以在由类似@mlflow.trace和with mlflow.start_span()这样的 fluent APIs 创建的父 span 的上下文中使用此方法,通过将其 span ids 传递给父级。此灵活性允许你像下面这样将命令式 API 与 fluent API 结合使用:import mlflow from mlflow import MlflowClient client = MlflowClient() with mlflow.start_span("parent_span") as parent_span: child_span = client.start_span( name="child_span", trace_id=parent_span.trace_id, parent_id=parent_span.span_id, ) # Do something... client.end_span( trace_id=parent_span.trace_id, span_id=child_span.span_id, )
然而,相反的做法不起作用。你不能在由这个 MlflowClient API 创建的 span 中使用 fluent APIs。这是因为 fluent APIs 会从托管上下文中获取当前的 span,而该上下文并没有被 MLflow Client APIs 设置。一旦你使用 MLflow Client APIs 创建了一个 span,所有的子 span 都必须用 MLflow Client APIs 创建。在使用这种混合方法时请小心,因为如果使用不当可能导致意外行为。
- Parameters
name – 该 span 的名称。
trace_id – 要将 span 附加到的 trace 的 ID。这是 OpenTelemetry 中 trace_id` 的同义词。
parent_id – 父 span 的 ID。父 span 可以是由流式 API(例如 with mlflow.start_span())以及像这样的命令式 API 创建的 span。
span_type – span 的类型。可以是字符串或
SpanType枚举值。inputs – 要在 span 上设置的输入。
attributes – 一个字典,用于在 span 上设置属性。
start_time_ns – span 的开始时间(自 UNIX 纪元起,单位为纳秒)。如果未提供,则使用当前时间。
- Returns
一个
mlflow.entities.Span对象,表示该 span。
示例:
from mlflow import MlflowClient client = MlflowClient() span = client.start_trace("my_trace") x = 2 # Create a child span child_span = client.start_span( "child_span", trace_id=span.trace_id, parent_id=span.span_id, inputs={"x": x}, ) y = x**2 client.end_span( trace_id=child_span.trace_id, span_id=child_span.span_id, attributes={"factor": 2}, outputs={"y": y}, ) client.end_trace(span.trace_id)
- start_trace(name: str, span_type: str = 'UNKNOWN', inputs: Optional[Any] = None, attributes: Optional[dict[str, str]] = None, tags: Optional[dict[str, str]] = None, experiment_id: Optional[str] = None, start_time_ns: Optional[int] = None) Span[source]
创建一个新的 trace 对象并在其下启动一个根 span。
这是一个命令式 API,用于在特定的跟踪 ID 和父 span 下手动创建一个新的 span,不同于像
@mlflow.trace和with mlflow.start_span()这样的高级 API,它们会自动管理 span 的生命周期和父子关系。只有在使用start_span()方法的 MlflowClient 来创建 spans 时才需要调用此方法。注意
使用此方法启动的跟踪必须通过调用
MlflowClient().end_trace(trace_id)来结束。否则该跟踪将不会被记录。- Parameters
name – 跟踪的名称(以及根 span)。
span_type – span 的类型。
inputs – 要在跟踪的根 span 上设置的输入。
attributes – 一个字典,用于在追踪的根 span 上设置属性。
tags – 一个用于在跟踪上设置标签的字典。
experiment_id – 要在其中创建跟踪的实验的 ID。如果未提供,MLflow 将按以下顺序查找有效的实验:通过
mlflow.set_experiment()激活,MLFLOW_EXPERIMENT_NAME环境变量,MLFLOW_EXPERIMENT_ID环境变量,或者由跟踪服务器定义的默认实验。start_time_ns – 跟踪的开始时间,以自 UNIX 纪元起的纳秒为单位。
- Returns
一个
Span对象,表示该跟踪的根 span。
示例:
from mlflow import MlflowClient client = MlflowClient() root_span = client.start_trace("my_trace") trace_id = root_span.trace_id # Create a child span child_span = client.start_span( "child_span", trace_id=trace_id, parent_id=root_span.span_id ) # Do something... client.end_span(trace_id=trace_id, span_id=child_span.span_id) client.end_trace(trace_id)
- test_webhook(webhook_id: str, event: Optional[Union[Literal['registered_model.created', 'model_version.created', 'model_version_tag.set', 'model_version_tag.deleted', 'model_version_alias.created', 'model_version_alias.deleted'], WebhookEvent]] = None) WebhookTestResult[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
通过发送测试有效负载来测试 webhook。
- Parameters
webhook_id – 要测试的 Webhook ID。
event – 可选的要测试的事件类型。可以是一个 WebhookEvent 对象或一个“entity.action”格式的字符串(例如,“model_version.created”)。如果未指定,则使用 webhook 中的第一个事件。
- Returns
WebhookTestResult 表示成功/失败及响应详情。
- transition_model_version_stage(name: str, version: str, stage: str, archive_existing_versions: bool = False) ModelVersion[source]
警告
mlflow.tracking.client.MlflowClient.transition_model_version_stage自 2.9.0 起已弃用。模型注册阶段将在未来的主要版本中移除。有关模型注册阶段弃用的更多信息,请参阅我们的迁移指南:https://mlflow.org/docs/latest/model-registry.html#migrating-from-stages更新模型版本的阶段。
- Parameters
name – 已注册模型名称。
version – 注册的模型版本。
stage – 此模型版本的新期望阶段。
archive_existing_versions – 如果将此标志设置为
True,该阶段中所有现有的模型版本将被自动移动到“archived”阶段。仅当stage为"staging"或"production"时有效,否则将引发错误。
- Returns
A single
mlflow.entities.model_registry.ModelVersionobject.import mlflow.sklearn from mlflow import MlflowClient from mlflow.models import infer_signature from sklearn.datasets import make_regression from sklearn.ensemble import RandomForestRegressor def print_model_version_info(mv): print(f"Name: {mv.name}") print(f"Version: {mv.version}") print(f"Description: {mv.description}") print(f"Stage: {mv.current_stage}") mlflow.set_tracking_uri("sqlite:///mlruns.db") params = {"n_estimators": 3, "random_state": 42} name = "RandomForestRegression" desc = "A new version of the model using ensemble trees" X, y = make_regression(n_features=4, n_informative=2, random_state=0, shuffle=False) rfr = RandomForestRegressor(**params).fit(X, y) signature = infer_signature(X, rfr.predict(X)) # Log MLflow entities with mlflow.start_run() as run: mlflow.log_params(params) mlflow.sklearn.log_model(rfr, name="sklearn-model", signature=signature) # Register model name in the model registry client = MlflowClient() client.create_registered_model(name) # Create a new version of the rfr model under the registered model name model_uri = f"runs:/{run.info.run_id}/sklearn-model" mv = client.create_model_version(name, model_uri, run.info.run_id, description=desc) print_model_version_info(mv) print("--") # transition model version from None -> staging mv = client.transition_model_version_stage(name, mv.version, "staging") print_model_version_info(mv)
- update_model_version(name: str, version: str, description: Optional[str] = None) ModelVersion[source]
在后端更新与模型版本关联的元数据。
- Parameters
name – 包含的注册模型的名称。
version – 模型版本的版本号。
description – 新的描述。
- Returns
A single
mlflow.entities.model_registry.ModelVersionobject.import mlflow.sklearn from mlflow import MlflowClient from mlflow.models import infer_signature from sklearn.datasets import make_regression from sklearn.ensemble import RandomForestRegressor def print_model_version_info(mv): print(f"Name: {mv.name}") print(f"Version: {mv.version}") print(f"Description: {mv.description}") mlflow.set_tracking_uri("sqlite:///mlruns.db") params = {"n_estimators": 3, "random_state": 42} name = "RandomForestRegression" X, y = make_regression(n_features=4, n_informative=2, random_state=0, shuffle=False) rfr = RandomForestRegressor(**params).fit(X, y) signature = infer_signature(X, rfr.predict(X)) # Log MLflow entities with mlflow.start_run() as run: mlflow.log_params(params) mlflow.sklearn.log_model(rfr, name="sklearn-model", signature=signature) # Register model name in the model registry client = MlflowClient() client.create_registered_model(name) # Create a new version of the rfr model under the registered model name model_uri = f"runs:/{run.info.run_id}/sklearn-model" mv = client.create_model_version(name, model_uri, run.info.run_id) print_model_version_info(mv) print("--") # Update model version's description desc = "A new version of the model using ensemble trees" mv = client.update_model_version(name, mv.version, desc) print_model_version_info(mv)
- update_registered_model(name: str, description: Optional[str] = None, deployment_job_id: Optional[str] = None) RegisteredModel[source]
为 RegisteredModel 实体更新元数据。输入字段
description应为非 None。后端在不存在具有给定名称的注册模型时会引发异常。- Parameters
name – 要更新的已注册模型的名称。
description – (可选)新的描述。
deployment_job_id – 可选的部署作业 ID。
- Returns
def print_registered_model_info(rm): print(f"name: {rm.name}") print(f"tags: {rm.tags}") print(f"description: {rm.description}") name = "SocialMediaTextAnalyzer" tags = {"nlp.framework": "Spark NLP"} desc = "This sentiment analysis model classifies the tone-happy, sad, angry." mlflow.set_tracking_uri("sqlite:///mlruns.db") client = MlflowClient() client.create_registered_model(name, tags, desc) print_registered_model_info(client.get_registered_model(name)) print("--") # Update the model's description desc = "This sentiment analysis model classifies tweets' tone: happy, sad, angry." client.update_registered_model(name, desc) print_registered_model_info(client.get_registered_model(name))
name: SocialMediaTextAnalyzer tags: {'nlp.framework': 'Spark NLP'} description: This sentiment analysis model classifies the tone-happy, sad, angry. -- name: SocialMediaTextAnalyzer tags: {'nlp.framework': 'Spark NLP'} description: This sentiment analysis model classifies tweets' tone: happy, sad, angry.
- update_run(run_id: str, status: Optional[str] = None, name: Optional[str] = None) None[source]
将具有指定 ID 的运行更新为新的状态或名称。
- Parameters
run_id – 要更新的 Run 的 ID。
status – 要设置的运行的新状态(如果指定)。至少应指定
status或name之一。name – 要设置的运行的新名称(如果指定)。应至少指定
name或status之一。
from mlflow import MlflowClient def print_run_info(run): print(f"run_id: {run.info.run_id}") print(f"run_name: {run.info.run_name}") print(f"status: {run.info.status}") # Create a run under the default experiment (whose id is '0'). client = MlflowClient() experiment_id = "0" run = client.create_run(experiment_id) print_run_info(run) print("--") # Update run and fetch info client.update_run(run.info.run_id, "FINISHED", "new_name") run = client.get_run(run.info.run_id) print_run_info(run)
- update_webhook(webhook_id: str, name: Optional[str] = None, description: Optional[str] = None, url: Optional[str] = None, events: Optional[list[typing.Union[typing.Literal['registered_model.created', 'model_version.created', 'model_version_tag.set', 'model_version_tag.deleted', 'model_version_alias.created', 'model_version_alias.deleted'], WebhookEvent]]] = None, secret: Optional[str] = None, status: Optional[Union[str, WebhookStatus]] = None) Webhook[source]
注意
实验性:此功能可能在将来的发布中更改或在不另行通知的情况下被移除。
更新现有的 webhook。
- Parameters
webhook_id – Webhook 标识。
name – 新 webhook 名称。
description – 新的 webhook 描述。
url – 新的 webhook URL。
events – 新的事件列表。可以是字符串或 WebhookEvent 对象。
secret – 新的 webhook secret.
status – 新的 webhook 状态。可以是字符串或 WebhookStatus 枚举。有效状态: “ACTIVE”, “DISABLED”
- Returns
表示已更新的
Webhook对象。