mlflow.models
The mlflow.models 模块提供一个 API,用于以“flavors”的形式保存机器学习模型,这些模型可以被不同的下游工具理解。
内置的 flavors 有:
详情请参见 MLflow Models guide.
- class mlflow.models.EvaluationArtifact(uri, content=None)[source]
基类:
object包含工件 URI 和内容的模型评估工件。
- class mlflow.models.EvaluationResult(metrics, artifacts, run_id=None)[source]
基类:
object表示一次 mlflow.evaluate() API 调用的模型评估输出,包含标量指标以及诸如性能图之类的输出工件。
- property artifacts: dict[str, 'mlflow.models.EvaluationArtifact']
一个字典,将标准化的工件名称(例如 “roc_data”)映射到工件的内容和位置信息
- classmethod load(path)[source]
从指定的本地文件系统路径加载评估结果
- save(path)[source]
将评估结果写入指定的本地文件系统路径
- class mlflow.models.FlavorBackend(config, **kwargs)[source]
基类:
objectFlavor Backend 的抽象类。该类定义了 MLflow 模型 flavor 在本地部署的 API 接口。
- abstract build_image(model_uri, image_name, install_mlflow, mlflow_home, enable_mlserver, base_image=None)[source]
- can_build_image()[source]
- Returns
如果此 flavor 定义了用于构建能够提供模型服务的 docker 容器的 build_image 方法,则为 True;否则为 False。
- abstract can_score_model()[source]
检查该 flavor 后端是否可以在当前环境中部署。
- Returns
如果该 flavor 后端可以在当前环境中应用,则为 True。
- abstract generate_dockerfile(model_uri, output_path, install_mlflow, mlflow_home, enable_mlserver, base_image=None)[source]
- abstract predict(model_uri, input_path, output_path, content_type)[source]
使用给定 URI 引用的已保存 MLflow 模型生成预测。输入和输出从文件或 stdin / stdout 读取和写入。
- Parameters
model_uri – 指向用于评分的 MLflow 模型的 URI。
input_path – 存放输入数据的文件路径。如果未指定,则从 stdin 读取数据。
output_path – 指向包含输出预测的文件的路径。如果未指定,数据将写入标准输出(stdout)。
content_type – 指定输入格式。可以是 {
json,csv}
- prepare_env(model_uri, capture_output=False)[source]
执行任何预测或部署模型所需的准备工作,例如下载依赖项或初始化 conda 环境。准备完成后,调用 predict 或 serve 应该很快。
- abstract serve(model_uri, port, host, timeout, enable_mlserver, synchronous=True, stdout=None, stderr=None)[source]
在本地服务指定的 MLflow 模型。
- Parameters
model_uri – 指向要用于评分的 MLflow 模型的 URI。
port – 用于模型部署的端口。
host – 用于模型部署的主机。默认是
localhost。timeout – 以秒为单位的超时,用于处理请求。默认为 60。
enable_mlserver – 是否使用 MLServer 或 本地评分服务器。
synchronous – 如果为 True,等待服务器进程退出并返回 0;如果进程以非零返回码退出,则抛出异常。 如果为 False,立即返回服务器进程 Popen 实例。
stdout – 重定向服务器的 stdout
stderr – 重定向服务器 stderr
- class mlflow.models.MetricThreshold(threshold=None, min_absolute_change=None, min_relative_change=None, greater_is_better=None)[source]
基类:
object此类允许您为模型验证定义指标阈值。允许的阈值有:threshold, min_absolute_change, min_relative_change.
- Parameters
threshold –
(可选) 一个数字,表示该指标的阈值。
如果对于该指标来说,值越大越好,则指标值必须 >= threshold 才能通过验证。
否则,指标值必须 <= threshold 才能通过验证。
min_absolute_change –
(可选) 一个正数,表示候选模型通过与基线模型验证所需的最小绝对变化。
如果该指标越大越好,则指标值必须 >= 基线模型指标值 + min_absolute_change 才能通过验证。
否则,指标值必须 <= 基线模型指标值 - min_absolute_change 才能通过验证。
min_relative_change –
(可选) 一个介于 0 和 1 之间的浮点数,表示候选模型在与基线模型比较时通过比较所需的最小相对变化(占基线模型指标值的百分比)。
如果该指标越大越好,指标值必须 >= 基线模型指标值 * (1 + min_relative_change)
否则,指标值必须 <= 基线模型指标值 * (1 - min_relative_change)
注意,如果基线模型的指标值等于 0,则阈值退化为执行一个简单的验证,即验证候选模型的指标值是否优于基线模型的指标值,即如果越大越好则指标值 >= 基线模型指标值 + 1e-10;如果越小越好则指标值 <= 基线模型指标值 - 1e-10。
greater_is_better – 必需的布尔值,表示对于该指标是否值越大越好。
- class mlflow.models.Model(artifact_path=None, run_id=None, utc_time_created=None, flavors=None, signature=None, saved_input_example_info: Optional[dict[str, typing.Any]] = None, model_uuid: Optional[Union[str, Callable[[], str]]] = <function Model.<lambda>>, mlflow_version: str | None = '3.3.0rc0', metadata: Optional[dict[str, typing.Any]] = None, model_size_bytes: Optional[int] = None, resources: Optional[Union[str, list[mlflow.models.resources.Resource]]] = None, env_vars: Optional[list[str]] = None, auth_policy: Optional[mlflow.models.auth_policy.AuthPolicy] = None, model_id: Optional[str] = None, prompts: Optional[list[str]] = None, **kwargs)[source]
基类:
object一个可以支持多种模型风格的 MLflow Model。提供用于实现 新 Model 风格的 APIs。
- add_flavor(name, **params) mlflow.models.model.Model[source]
为如何以给定格式提供模型添加一条条目。
- property auth_policy: dict[str, dict[str, typing.Any]]
一个可选的字典,包含为提供该模型服务所需的身份验证策略。
- Getter
获取为提供模型服务所需的 auth_policy
- Setter
设置提供模型服务所需的 auth_policy
- Type
Dict[str, dict]
注意
实验性:此属性可能在将来的版本中更改或被移除,且不另行通知。
- classmethod from_dict(model_dict) mlflow.models.model.Model[source]
从其 YAML 表示中加载模型。
- get_input_schema()[source]
当且仅当 Model 已使用 schema 定义保存时,才检索其输入 schema。
- get_model_info(logged_model: Optional[LoggedModel] = None) mlflow.models.model.ModelInfo[source]
创建一个
ModelInfo实例,包含模型元数据。
- get_output_schema()[source]
当且仅当 Model 已用模式定义保存时,检索其输出模式。
- get_params_schema()[source]
仅当且仅当模型使用架构定义保存时,才会检索该模型的参数架构。
- get_serving_input(path: str) str | None[source]
从模型目录加载服务输入示例。如果没有服务输入示例,则返回 None。
- Parameters
path – 模型目录的路径。
- Returns
用于服务的输入示例;如果模型没有服务输入示例,则为 None。
- get_tags_dict() dict[str, typing.Any][source]
- classmethod load(path) mlflow.models.model.Model[source]
从其 YAML 表示中加载模型。
- Parameters
path – 本地文件系统路径或 URI,指向 Model 对象的 MLmodel YAML 文件表示,或指向包含 MLmodel YAML 文件表示的目录。
- Returns
Model 的一个实例。
- load_input_example(path: Optional[str] = None) str | None[source]
Load the input example saved along a model. Returns None if there is no example metadata (i.e. the model was saved without example). Raises FileNotFoundError if there is model metadata but the example file is missing.
- Parameters
path – 模型或运行 URI,或指向 model 目录的路径。 例如 models://
/ , runs:/ / 或 /path/to/model - Returns
输入示例(NumPy ndarray, SciPy csc_matrix, SciPy csr_matrix, pandas DataFrame, dict)或 None(如果模型没有示例)。
- load_input_example_params(path: str)[source]
加载与模型一起保存的 input_example 的 params。如果 input_example 中没有 params,则返回 None。
- Parameters
path – 指向模型目录的路径。
- Returns
params (dict) 或 None,如果模型没有 params。
- classmethod log(artifact_path, flavor, registered_model_name=None, await_registration_for=300, metadata=None, run_id=None, resources=None, auth_policy=None, prompts=None, name: Optional[str] = None, model_type: Optional[str] = None, params: Optional[dict[str, typing.Any]] = None, tags: Optional[dict[str, typing.Any]] = None, step: int = 0, model_id: Optional[str] = None, **kwargs) mlflow.models.model.ModelInfo[source]
使用提供的 flavor 模块记录模型。如果没有处于活动状态的运行,此方法将创建一个新的活动运行。
- Parameters
artifact_path – 已弃用。请改用 name。
flavor – 用于保存模型的 flavor 模块。该模块必须具有
save_model函数,该函数会将模型持久化为有效的 MLflow 模型。registered_model_name – 如果提供,则在
registered_model_name下创建一个模型版本;如果不存在具有该名称的已注册模型,则同时创建一个已注册模型。await_registration_for – 等待模型版本完成创建并处于
READY状态的秒数。默认情况下,该函数等待五分钟。指定 0 或 None 可跳过等待。metadata – {{ metadata }}
run_id – 与此模型关联的 run ID。
resources – {{ resources }}
auth_policy – {{ auth_policy }}
prompts – {{ prompts }}
name – 模型的名称。
model_type – {{ model_type }}
params – {{ params }}
标签 – {{ tags }}
step – {{ step }}
model_id – {{ model_id }}
kwargs – 传递给模型 flavor 的额外参数。
- Returns
一个
ModelInfo实例,包含已记录模型的元数据。
- property metadata: dict[str, typing.Any] | None
传递给模型并存储在 MLmodel 文件中的自定义元数据字典。
- Getter
检索已应用于模型实例的自定义元数据。
- Setter
设置一个包含自定义键和值的字典,该字典将随模型实例一并包含
- Type
Optional[Dict[str, Any]]
- Returns
如果已定义,则为用户定义的元数据字典。
# Create and log a model with metadata to the Model Registry from sklearn import datasets from sklearn.ensemble import RandomForestClassifier import mlflow from mlflow.models import infer_signature with mlflow.start_run(): iris = datasets.load_iris() clf = RandomForestClassifier() clf.fit(iris.data, iris.target) signature = infer_signature(iris.data, iris.target) mlflow.sklearn.log_model( clf, name="iris_rf", signature=signature, registered_model_name="model-with-metadata", metadata={"metadata_key": "metadata_value"}, ) # model uri for the above model model_uri = "models:/model-with-metadata/1" # Load the model and access the custom metadata model = mlflow.pyfunc.load_model(model_uri=model_uri) assert model.metadata.metadata["metadata_key"] == "metadata_value"
- property model_size_bytes: int | None
一个可选的整数,表示模型大小(以字节为单位)
- Getter
如果在保存模型时已计算模型大小,则检索该模型大小
- Setter
将模型大小设置为模型实例
- Type
Optional[int]
- property resources: dict[str, dict[mlflow.models.resources.ResourceType, list[dict[str, typing.Any]]]]
一个可选的字典,包含用于为模型提供服务所需的资源。
- Getter
检索提供模型服务所需的资源
- Setter
设置为模型提供服务所需的资源
- Type
Dict[str, Dict[ResourceType, List[Dict]]]
- save(path) None[source]
将模型写入本地 YAML 文件。
- property saved_input_example_info: dict[str, typing.Any] | None
一个字典,包含已保存输入示例的元数据,例如,
{"artifact_path": "input_example.json", "type": "dataframe", "pandas_orient": "split"}.
- property signature
对模型对象的预期输入和输出的可选定义,使用字段名和数据类型来描述。签名既支持基于列的输入和输出,也支持基于张量的输入和输出。
- Getter
仅当模型在保存时带有签名定义时,才检索模型实例的签名。
- Setter
为模型实例设置签名。
- Type
可选[ModelSignature]
- to_dict() dict[str, typing.Any][source]
将模型序列化为字典。
- to_json() str[source]
将模型写为 json。
- to_yaml(stream=None) str[source]
将模型写成 yaml 字符串。
- class mlflow.models.ModelConfig(*, development_config: Optional[Union[str, dict[str, typing.Any]]] = None)[source]
基类:
objectModelConfig 在代码中用于读取 YAML 配置文件或字典。
- Parameters
development_config – 指向 YAML 配置文件的路径或包含配置的字典。如果未提供该配置,则会引发错误
from mlflow.models import ModelConfig # Load the configuration from a dictionary config = ModelConfig(development_config={"key1": "value1"}) print(config.get("key1"))
from mlflow.models import ModelConfig # Load the configuration from a file config = ModelConfig(development_config="config.yaml") print(config.get("key1"))
当在模型文件中本地调用 ModelConfig 时,可以传入 development_config,该配置将用作模型的配置。
import mlflow from mlflow.models import ModelConfig config = ModelConfig(development_config={"key1": "value1"}) class TestModel(mlflow.pyfunc.PythonModel): def predict(self, context, model_input, params=None): return config.get("key1") mlflow.models.set_model(TestModel())
但是在记录模型时,这个 development_config 配置文件将被覆盖。 当在记录模型时没有传入 model_config,会在尝试使用 ModelConfig 加载模型时引发错误。 注意:在记录模型时不使用 development_config。
model_config = {"key1": "value2"} with mlflow.start_run(): model_info = mlflow.pyfunc.log_model( name="model", python_model="agent.py", model_config=model_config ) loaded_model = mlflow.pyfunc.load_model(model_info.model_uri) # This will print "value2" as the model_config passed in while logging the model print(loaded_model.predict(None))
- get(key)[source]
获取配置中顶层参数的值。
- to_dict()[source]
以字典形式返回配置。
- class mlflow.models.ModelSignature(inputs: Optional[Union[mlflow.types.schema.Schema, Any]] = None, outputs: Optional[Union[mlflow.types.schema.Schema, Any]] = None, params: Optional[mlflow.types.schema.ParamSchema] = None)[source]
基类:
objectModelSignature 指定模型的输入、输出和参数的模式。
ModelSignature 可以被
inferred从训练数据集、用于推断的模型预测和参数中推断得到,或者通过传入输入和输出Schema以及参数ParamSchema手工构造。- classmethod from_dict(signature_dict: dict[str, typing.Any])[source]
从字典表示中反序列化。
- Parameters
signature_dict – 模型签名的字典表示。期望的字典格式: {‘inputs’:
, ‘outputs’: , ‘params’: ” } - Returns
ModelSignature 已用字典中的数据填充。
- to_dict() dict[str, typing.Any][source]
序列化为“jsonable”字典。
输入和输出模式以 json 字符串表示。这样在嵌入 MLmodel yaml 文件时,表示会更紧凑。
- Returns
字典表示,输入和输出模式表示为 JSON 字符串。
- class mlflow.models.Resource[source]
基类:
abc.ABC用于定义服务模型所需资源的基类。
- Parameters
type (ResourceType) – 资源类型。
target_uri (str) – 这些资源托管的目标 URI。
- abstract classmethod from_dict(data: dict[str, str])[source]
将字典转换为 Resource。子类必须实现此方法。
- abstract to_dict()[source]
将资源转换为字典。子类必须实现此方法。
- abstract property type: mlflow.models.resources.ResourceType
资源类型(必须由子类定义)。
- class mlflow.models.ResourceType(value)[source]
基类:
enum.Enum枚举,用于定义为服务模型所需的不同类型的资源。
- mlflow.models.add_libraries_to_model(model_uri, run_id=None, registered_model_name=None)[source]
给定一个已注册的 model_uri(例如 models:/
/ ),该实用工具会将模型及其所有所需的模型库重新记录回模型注册表。所需的模型库作为模型工件与模型一起存储。此外,模型的支持文件(例如 conda.yaml、requirements.txt)会被修改以使用添加的库。 默认情况下,此实用程序在由
model_uri指定的相同注册模型下创建一个新的模型版本。可以通过指定registered_model_name参数来覆盖此行为。- Parameters
model_uri – 在模型注册表中注册的 model uri,格式为 models:/
/ run_id – 用于记录包含库的模型的运行的 ID。如果 None,则包含库的模型会记录到对应于由
model_uri指定的模型版本的源运行;如果该模型版本没有源运行,则会创建一个新的运行。registered_model_name – 新的模型版本(包含其库的模型)将以输入的 registered_model_name 注册。如果 None,则会将新版本记录到模型注册表中现有的模型上。
注意
此实用程序仅对已注册到 Model Registry 的模型进行操作。
注意
这些库仅与它们被添加的那个平台兼容。不支持跨平台库。
# Create and log a model to the Model Registry import pandas as pd from sklearn import datasets from sklearn.ensemble import RandomForestClassifier import mlflow import mlflow.sklearn from mlflow.models import infer_signature with mlflow.start_run(): iris = datasets.load_iris() iris_train = pd.DataFrame(iris.data, columns=iris.feature_names) clf = RandomForestClassifier(max_depth=7, random_state=0) clf.fit(iris_train, iris.target) signature = infer_signature(iris_train, clf.predict(iris_train)) mlflow.sklearn.log_model( clf, name="iris_rf", signature=signature, registered_model_name="model-with-libs", ) # model uri for the above model model_uri = "models:/model-with-libs/1" # Import utility from mlflow.models.utils import add_libraries_to_model # Log libraries to the original run of the model add_libraries_to_model(model_uri) # Log libraries to some run_id existing_run_id = "21df94e6bdef4631a9d9cb56f211767f" add_libraries_to_model(model_uri, run_id=existing_run_id) # Log libraries to a new run with mlflow.start_run(): add_libraries_to_model(model_uri) # Log libraries to a new registered model named 'new-model' with mlflow.start_run(): add_libraries_to_model(model_uri, registered_model_name="new-model")
- mlflow.models.build_docker(model_uri=None, name='mlflow-pyfunc', env_manager='virtualenv', mlflow_home=None, install_java=False, install_mlflow=False, enable_mlserver=False, base_image=None)[source]
构建一个 Docker 镜像,其默认入口点使用 python_function flavor 在端口 8080 提供 MLflow 模型服务。容器会提供由
model_uri引用的模型(如果已指定)。如果未指定model_uri,则必须将一个 MLflow Model 目录作为卷挂载到容器内的 /opt/ml/model 目录中。重要
自 MLflow 2.10.1 起,通过
--model-uri构建的 Docker 镜像为提高性能 不会安装 Java,除非模型 flavor 是以下之一["johnsnowlabs", "h2o" "spark"]。如果需要为其他 flavors 安装 Java,例如使用 SparkML 的自定义 Python 模型,请指定install-java=True以强制安装 Java。对于早期版本,Java 始终会安装到镜像中。警告
如果
model_uri未指定,生成的镜像不支持使用 RFunc 服务器为模型提供服务。注意:默认情况下,容器会启动 nginx 和 uvicorn 进程。如果你不需要启动 nginx 进程(例如将容器部署到 Google Cloud Run 时),可以通过 DISABLE_NGINX 环境变量将其禁用:
docker run -p 5001:8080 -e DISABLE_NGINX=true "my-image-name"
有关 ‘python_function’ flavor 的更多信息,请参见 https://www.mlflow.org/docs/latest/python_api/mlflow.pyfunc.html。
- Parameters
model_uri – 指向模型的 URI。可以是本地路径、‘runs:/’ URI,或远程存储 URI(例如,‘s3://’ URI)。有关模型工件支持的远程 URI 的更多信息,请参见 https://mlflow.org/docs/latest/tracking.html#artifact-stores
name – 要构建的 Docker 镜像的名称。默认值为 ‘mlflow-pyfunc’。
env_manager – 如果指定,使用指定的环境管理器为 MLmodel 创建环境。支持以下值:(1) virtualenv(默认):使用 virtualenv 和 pyenv 管理 Python 版本;(2) conda:使用 conda;(3) local:使用本地环境,不创建新的环境。
mlflow_home – 本地克隆的 MLflow 项目的路径。仅用于开发。
install_java – 如果指定,则在镜像中安装 Java。默认值为 False,以减小镜像大小和构建时间。需要 Java 的模型 flavor 会自动启用此设置,例如 Spark flavor。(该参数仅在 MLflow 2.10.1 及更高版本中可用。在早期版本中,Java 始终安装到镜像中。)
install_mlflow – 如果指定并且存在需要被激活的 conda 或 virtualenv 环境,mlflow 将在该环境被激活后安装到该环境中。安装的 mlflow 版本将与用于调用此命令的版本相同。
enable_mlserver – 如果指定,镜像将使用 Seldon MLserver 作为后端进行构建。
base_image – Docker 镜像的基础镜像。如果未指定,默认镜像为 UBUNTU_BASE_IMAGE = “ubuntu:20.04” 或 PYTHON_SLIM_BASE_IMAGE = “python:{version}-slim”。注意:如果使用自定义镜像,则无法保证该镜像能正常工作。通过在 ubuntu 镜像之上构建镜像可能会获得更好的兼容性。此外,您必须安装 Java 和 virtualenv 才能使镜像正常工作。
- mlflow.models.convert_input_example_to_serving_input(input_example) str | None[source]
辅助函数,用于将模型的输入示例转换为可在评分服务器中用于模型推理的服务输入示例。
- Parameters
input_example – 模型输入示例。支持的类型为 pandas.DataFrame、numpy.ndarray、(name -> numpy.ndarray) 的字典、列表、标量以及具有 json 可序列化值的字典。
- Returns
将 serving 输入示例作为 JSON 字符串
- mlflow.models.evaluate(model=None, data=None, *, model_type=None, targets=None, predictions=None, dataset_path=None, feature_names=None, evaluators=None, evaluator_config=None, extra_metrics=None, custom_artifacts=None, env_manager='local', model_config=None, inference_params=None, model_id=None, _called_from_genai_evaluate=False)[source]
在给定数据和所选指标上评估模型性能。
此函数使用指定的
evaluators在指定的数据集上评估 PyFunc 模型或自定义可调用对象,并将产生的指标 & 工件记录到 MLflow 跟踪服务器。用户也可以跳过设置model,直接将模型输出放入data中进行评估。有关详细信息,请阅读 the Model Evaluation documentation。- Default Evaluator behavior:
默认评估器,可通过
evaluators="default"或evaluators=None调用,支持下面列出的模型类型。对于每种预定义的模型类型,默认评估器会对您的模型在所选的一组指标上进行评估并生成诸如图表之类的工件。详情如下。对于
"regressor"和"classifier"两种模型类型,默认评估器使用 SHAP 生成模型摘要图和特征重要性图。- For regressor models, the default evaluator additionally logs:
metrics: example_count, mean_absolute_error, mean_squared_error, root_mean_squared_error, sum_on_target, mean_on_target, r2_score, max_error, mean_absolute_percentage_error.
- For binary classifiers, the default evaluator additionally logs:
metrics: true_negatives, false_positives, false_negatives, true_positives, recall, precision, f1_score, accuracy_score, example_count, log_loss, roc_auc, precision_recall_auc.
工件:提升曲线图、精确率-召回率曲线图、ROC 曲线图。
- For multiclass classifiers, the default evaluator additionally logs:
指标: accuracy_score, example_count, f1_score_micro, f1_score_macro, log_loss
artifacts: 一个用于“per_class_metrics”的CSV文件(每类指标包括 true_negatives/false_positives/false_negatives/true_positives/recall/precision/roc_auc, precision_recall_auc),精确率-召回率合并曲线图,ROC合并曲线图。
- For question-answering models, the default evaluator logs:
指标:
exact_match,token_count, toxicity(需要 evaluate、torch、flesch_kincaid_grade_level(需要 textstat)和 ari_grade_level。artifacts: 一个 JSON 文件,包含以表格格式表示的模型的输入、输出、targets(如果提供了
targets参数)以及每行指标。
- For text-summarization models, the default evaluator logs:
指标:
token_count, ROUGE (需要安装 evaluate, nltk, 和 rouge_score), toxicity (需要安装 evaluate, torch, transformers), ari_grade_level (需要安装 textstat), flesch_kincaid_grade_level (需要安装 textstat).artifacts: 一个 JSON 文件,包含模型在表格格式中的输入、输出、targets(如果提供了
targets参数)以及每行指标。
- For text models, the default evaluator logs:
指标:
token_count, toxicity (需要 evaluate, torch, transformers), ari_grade_level (需要 textstat), flesch_kincaid_grade_level (需要 textstat).artifacts: 一个 JSON 文件,包含 inputs、outputs、targets(如果提供了
targets参数),以及以表格格式表示的模型每行指标。
- For retriever models, the default evaluator logs:
指标:
precision_at_k(k),recall_at_k(k)和ndcg_at_k(k)- 默认值均为retriever_k= 3.artifacts: 一个 JSON 文件,包含模型的输入、输出、目标以及按行的指标,以表格格式呈现。
对于 sklearn 模型,默认评估器还会记录模型的评估准则(例如分类器的平均准确率),该准则由 model.score 方法计算。
上面列出的指标/工件会记录到活动的 MLflow 运行中。如果不存在活动的运行,将为记录这些指标和工件创建一个新的 MLflow 运行。
此外,有关指定数据集的信息——哈希、名称(如果已指定)、路径(如果已指定)以及评估它的模型的 UUID——会被记录到
mlflow.datasets标签中。- The available
evaluator_configoptions for the default evaluator include: log_model_explainability: 一个布尔值,指定是否记录模型可解释性洞见,默认值为 True。
- log_explainer: 如果为 True,则记录用于计算模型可解释性见解的解释器
作为模型。默认值为 False.
explainability_algorithm: 一个字符串,用于指定用于模型可解释性的 SHAP Explainer 算法。支持的算法包括: ‘exact’, ‘permutation’, ‘partition’, ‘kernel’。如果未设置,
shap.Explainer会使用 “auto” 算法,auto 会根据模型选择最佳 Explainer。explainability_nsamples: 用于计算模型可解释性洞察的样本行数。默认值为2000。
explainability_kernel_link: shap kernel explainer 使用的 kernel link 函数。可用值为 “identity” 和 “logit”。默认值是 “identity”。
max_classes_for_multiclass_roc_pr: 对于多类分类任务,记录每个类别的 ROC 曲线和精确率-召回率(Precision-Recall)曲线的最大类别数。如果类别数大于配置的最大值,则不会记录这些曲线。
metric_prefix: 一个可选的前缀,用于添加到评估期间生成的每个指标和工件的名称前。
log_metrics_with_dataset_info: 一个布尔值,指定是否在评估期间将关于评估数据集的信息包含在记录到 MLflow Tracking 的每个指标名称中,默认值为 True。
pos_label: 如果指定,用于在计算二分类模型的分类指标(例如 precision、recall、f1 等)时作为正类标签。对于多类分类和回归模型,将忽略此参数。
average:在计算多类分类模型的分类指标(例如 precision、recall、f1 等)时使用的平均方法(默认:
'weighted')。对于二元分类和回归模型,将忽略此参数。sample_weights: 在计算模型性能指标时应用于每个样本的权重。
col_mapping: 一个字典,将输入数据集或输出预测中的列名映射为在调用评估函数时使用的列名。
retriever_k: 当
model_type="retriever"时使用的参数,表示在计算内置指标precision_at_k(k)、recall_at_k(k)和ndcg_at_k(k)时要使用的排名靠前的检索文档数量。默认值为 3。对于所有其他模型类型,此参数将被忽略。
- The available
- Limitations of evaluation dataset:
对于分类任务,使用数据集标签来推断总类别数。
对于二分类任务,负标签值必须为 0、-1 或 False,正标签值必须为 1 或 True。
- Limitations of metrics/artifacts computation:
对于分类任务,某些指标和工件的计算要求模型输出类别概率。目前,对于 scikit-learn 模型,默认评估器会调用底层模型的
predict_proba方法以获取概率。对于其他模型类型,默认评估器不会计算那些需要概率输出的指标/工件。
- Limitations of default evaluator logging model explainability insights:
shap.Explainerauto算法对线性模型使用Linear解释器, 对树模型使用Tree解释器。因为 SHAP 的Linear和Tree解释器不支持多类分类, 默认评估器会在多类分类任务中回退使用Exact或Permutation解释器。目前不支持为 PySpark 模型记录可解释性洞见。
评估数据集的标签值必须为数值或布尔值,所有特征值必须为数值,并且每个特征列只能包含标量值。
- Limitations when environment restoration is enabled:
当为被评估模型启用环境还原时(即指定了一个非本地的
env_manager),该模型将作为客户端加载,在一个独立的 Python 环境中调用 MLflow Model Scoring Server 进程,并在该环境中安装模型训练时的依赖。因此,模型的诸如predict_proba(用于概率输出)或score(为 sklearn 模型计算评估准则)等方法将变得不可访问,默认评估器不会计算那些依赖这些方法的指标或工件。因为该模型是一个 MLflow Model Server 进程,计算 SHAP 解释会更慢。因此,当指定了非本地的
env_manager时,模型可解释性会被禁用,除非在evaluator_config选项中明确将 log_model_explainability 设置为True。
- Parameters
model –
可选。若指定,应为下列之一:
一个 pyfunc 模型实例
指向 pyfunc 模型的 URI
指向 MLflow Deployments 端点的 URI,例如
"endpoints:/my-chat"一个可调用函数:该函数应能接受模型输入并返回预测结果。它应遵循
predict方法的签名。下面是一个有效函数的示例:model = mlflow.pyfunc.load_model(model_uri) def fn(model_input): return model.predict(model_input)
如果省略,则表示将使用静态数据集进行评估而不是模型。在这种情况下,
data参数必须是包含模型输出的 Pandas DataFrame 或 mlflow PandasDataset,且predictions参数必须是data中包含模型输出的列名。data –
以下之一:
一个 numpy 数组或包含评估特征的列表,不含标签。
- 一个 Pandas DataFrame,包含评估特征、标签,且可选地包含模型输出
当未指定 model 时,必须提供模型输出。 如果未指定
feature_names参数,除标签列和预测列外的所有列都视为特征列。否则,仅将出现在feature_names中的列名视为特征列。
- 一个 Spark DataFrame,包含评估特征和标签。若
未指定
feature_names参数,除标签列外的所有列都视为特征列。否则,仅将出现在feature_names中的列名视为特征列。Spark DataFrame 中仅使用前 10000 行作为评估数据。
- 一个
mlflow.data.dataset.Dataset实例,包含评估 特征、标签,且可选地包含模型输出。模型输出仅在 PandasDataset 中受支持。当未指定 model 时,必须提供模型输出,并且应通过 PandasDataset 的
predictions属性来指定。
- 一个
model_type –
(可选) 描述模型类型的字符串。默认评估器支持以下模型类型:
'classifier''regressor''question-answering''text-summarization''text''retriever'
如果未指定
model_type,则必须通过extra_metrics参数提供要计算的指标列表。注意
'question-answering','text-summarization','text', and'retriever'是实验性的,可能在将来版本中更改或移除。targets – 如果
data是 numpy 数组或列表,则为评估标签的 numpy 数组或列表。如果data是 DataFrame,则为data中包含评估标签的列的字符串名称。对于分类和回归模型这是必需的,但对于问答、文本摘要和文本模型是可选的。如果data是定义了 targets 的mlflow.data.dataset.Dataset,则targets可选。predictions –
可选。包含模型输出的列名。
当
model被指定并输出多列时,predictions可用于指定用于存储评估时模型输出的列名。当
model未被指定且data是一个 pandas dataframe 时,predictions可用于指定data中包含模型输出的列名。
# 评估输出多列的模型 data = pd.DataFrame({"question": ["foo"]}) def model(inputs): return pd.DataFrame({"answer": ["bar"], "source": ["baz"]}) results = evaluate( model=model, data=data, predictions="answer", # 如有需要可传入其他参数 ) # 评估静态数据集 data = pd.DataFrame({"question": ["foo"], "answer": ["bar"], "source": ["baz"]}) results = evaluate( data=data, predictions="answer", # 如有需要可传入其他参数 )
dataset_path – (可选) 数据存放路径。不得包含双引号 (
")。如果指定,该路径会被记录到mlflow.datasets标签中,以用于血缘追踪。feature_names – (可选)一个列表。如果
data参数是一个 numpy 数组或列表,feature_names是各个特征名称的列表。如果feature_names=None,则会使用格式feature_{feature_index}生成feature_names。如果data参数是一个 Pandas DataFrame 或 Spark DataFrame,feature_names是 DataFrame 中特征列名称的列表。如果feature_names=None,则除标签列和预测列以外的所有列都被视为特征列。evaluators – 用于模型评估的评估器名称,或评估器名称列表。如果未指定,则使用所有能够在指定数据集上评估指定模型的评估器。默认评估器可以通过名称
"default"引用。要查看所有可用的评估器,请调用mlflow.models.list_evaluators()。evaluator_config – 一个提供给评估器的附加配置字典。 如果指定了多个评估器,每个配置都应作为一个嵌套字典提供,其键为评估器名称。
extra_metrics –
(Optional) A list of
EvaluationMetricobjects. These metrics are computed in addition to the default metrics associated with pre-defined model_type, and setting model_type=None will only compute the metrics specified in extra_metrics. See the mlflow.metrics module for more information about the builtin metrics and how to define extra metrics.import mlflow import numpy as np def root_mean_squared_error(eval_df, _builtin_metrics): return np.sqrt((np.abs(eval_df["prediction"] - eval_df["target"]) ** 2).mean()) rmse_metric = mlflow.models.make_metric( eval_fn=root_mean_squared_error, greater_is_better=False, ) mlflow.evaluate(..., extra_metrics=[rmse_metric])
custom_artifacts –
(Optional) A list of custom artifact functions with the following signature:
def custom_artifact( eval_df: Union[pandas.Dataframe, pyspark.sql.DataFrame], builtin_metrics: Dict[str, float], artifacts_dir: str, ) -> Dict[str, Any]: """ Args: eval_df: A Pandas or Spark DataFrame containing ``prediction`` and ``target`` column. The ``prediction`` column contains the predictions made by the model. The ``target`` column contains the corresponding labels to the predictions made on that row. builtin_metrics: A dictionary containing the metrics calculated by the default evaluator. The keys are the names of the metrics and the values are the scalar values of the metrics. Refer to the DefaultEvaluator behavior section for what metrics will be returned based on the type of model (i.e. classifier or regressor). artifacts_dir: A temporary directory path that can be used by the custom artifacts function to temporarily store produced artifacts. The directory will be deleted after the artifacts are logged. Returns: A dictionary that maps artifact names to artifact objects (e.g. a Matplotlib Figure) or to artifact paths within ``artifacts_dir``. """ ...
Object types that artifacts can be represented as:
A string uri representing the file path to the artifact. MLflow will infer the type of the artifact based on the file extension.
A string representation of a JSON object. This will be saved as a .json artifact.
Pandas DataFrame. This will be resolved as a CSV artifact.
Numpy array. This will be saved as a .npy artifact.
Matplotlib Figure. This will be saved as an image artifact. Note that
matplotlib.pyplot.savefigis called behind the scene with default configurations. To customize, either save the figure with the desired configurations and return its file path or define customizations through environment variables inmatplotlib.rcParams.Other objects will be attempted to be pickled with the default protocol.
import mlflow import matplotlib.pyplot as plt def scatter_plot(eval_df, builtin_metrics, artifacts_dir): plt.scatter(eval_df["prediction"], eval_df["target"]) plt.xlabel("Targets") plt.ylabel("Predictions") plt.title("Targets vs. Predictions") plt.savefig(os.path.join(artifacts_dir, "example.png")) plt.close() return {"pred_target_scatter": os.path.join(artifacts_dir, "example.png")} def pred_sample(eval_df, _builtin_metrics, _artifacts_dir): return {"pred_sample": pred_sample.head(10)} mlflow.evaluate(..., custom_artifacts=[scatter_plot, pred_sample])
env_manager –
指定用于在隔离的 Python 环境中加载候选
model并恢复其依赖项的环境管理器。默认值为local,并且支持以下值:virtualenv:(推荐)使用 virtualenv 恢复用于训练该模型的 Python 环境。conda: 使用 Conda 恢复用于训练该模型的软件环境。local: 使用当前的 Python 环境进行模型推断,这可能与用于训练模型的环境不同,可能导致错误或无效的预测。
model_config – 用于通过 pyfunc 加载模型的模型配置。检查模型的 pyfunc flavor 以了解哪些键受您的特定模型支持。如果未指定,则使用模型中的默认模型配置(如果有)。
inference_params – (可选)一个字典,包含在对模型进行预测时传递的推理参数,例如
{"max_tokens": 100}。仅当model是 MLflow Deployments 的 endpoint URI,例如"endpoints:/my-chat"时使用。model_id – (可选) 将用于关联评估结果(例如指标和跟踪)的 MLflow LoggedModel 或 Model Version 的 ID。如果 model_id 未指定但指定了 model,则将使用 model 中的 ID。
_called_from_genai_evaluate –(可选)仅供内部使用。
- Returns
一个
mlflow.models.EvaluationResult实例,包含使用给定数据集评估模型的指标。
- mlflow.models.get_model_info(model_uri: str) mlflow.models.model.ModelInfo[source]
获取指定模型的元数据,例如其输入/输出签名。
- Parameters
model_uri –
MLflow 模型的位置,URI 格式。例如:
/Users/me/path/to/local/modelrelative/path/to/local/models3://my_bucket/path/to/modelruns://run-relative/path/to/model models:// models:// mlflow-artifacts:/path/to/model
有关受支持的 URI 方案的更多信息,请参阅 Referencing Artifacts。
- Returns
一个
ModelInfo实例,包含已记录模型的元数据。
import mlflow.models import mlflow.sklearn from sklearn.ensemble import RandomForestRegressor with mlflow.start_run() as run: params = {"n_estimators": 3, "random_state": 42} X = [[0, 1]] y = [1] signature = mlflow.models.infer_signature(X, y) rfr = RandomForestRegressor(**params).fit(X, y) mlflow.log_params(params) mlflow.sklearn.log_model(rfr, name="sklearn-model", signature=signature) model_uri = f"runs:/{run.info.run_id}/sklearn-model" # Get model info with model_uri model_info = mlflow.models.get_model_info(model_uri) # Get model signature directly model_signature = model_info.signature assert model_signature == signature
- mlflow.models.infer_pip_requirements(model_uri, flavor, fallback=None, timeout=None, extra_env_vars=None)[source]
通过创建子进程并在其中加载指定模型来推断该模型的 pip 依赖,以确定导入了哪些包。
- Parameters
model_uri – 模型的 URI。
flavor – 模型的 flavor 名称。
fallback – 如果提供,推理过程中出现的意外错误将被吞并,并返回
fallback的值。否则,错误将被抛出。timeout – 如果指定,推理操作受该超时(以秒为单位)的约束。
extra_env_vars – 传递给子进程的额外环境变量字典。默认值为 None。
- Returns
一份推断出的 pip 依赖项列表(例如
["scikit-learn==0.24.2", ...])。
- mlflow.models.infer_signature(model_input: Any = None, model_output: MlflowInferableDataset = None, params: dict[str, typing.Any] | None = None) mlflow.models.signature.ModelSignature[source]
从训练数据(input)、模型预测(output)和参数(用于推理)推断 MLflow 模型签名。
签名将模型的输入和输出表示为具有(可选)命名列的数据帧,并且数据类型被指定为在
mlflow.types.DataType中定义的类型之一。它还包括用于推理的参数 schema。若用户数据包含不兼容的类型或未以下面列出的支持格式之一传入,则此方法将引发异常。- The input should be one of these:
pandas.DataFrame
pandas.Series
字典,{ name -> numpy.ndarray}
numpy.ndarray
pyspark.sql.DataFrame
scipy.sparse.csr_matrix
scipy.sparse.csc_matrix
字典 / 可转换为 JSON 类型的字典列表
元素类型应可映射到以下之一
mlflow.types.DataType。对于 pyspark.sql.DataFrame 输入,类型为 DateType 和 TimestampType 的列都被推断为类型
datetime,在推断时会被强制转换为 TimestampType。- Parameters
model_input – 模型的有效输入。例如(训练数据集的一个子集)。
model_output – 有效的模型输出。例如:训练数据集(或其子集)的模型预测。
params –
用于推理的有效参数。它应该是一个参数字典,通过将 params 传递给 pyfunc 的 predict 方法,可以在推理期间在模型上设置这些参数。
有效参数示例:
from mlflow.models import infer_signature from mlflow.transformers import generate_signature_output # 定义推理参数 params = { "num_beams": 5, "max_length": 30, "do_sample": True, "remove_invalid_values": True, } # 推断包含参数的签名 signature = infer_signature( data, generate_signature_output(model, data), params=params, ) # 使用模型签名保存模型 mlflow.transformers.save_model( model, path=model_path, signature=signature, ) pyfunc_loaded = mlflow.pyfunc.load_model(model_path) # 直接将 params 传递给 `predict` 函数 result = pyfunc_loaded.predict(data, params=params)
- Returns
ModelSignature
- mlflow.models.list_evaluators()[source]
返回所有可用 Evaluators 的名称列表。
- mlflow.models.make_metric(*, eval_fn, greater_is_better, name=None, long_name=None, version=None, metric_details=None, metric_metadata=None, genai_metric_args=None)[source]
用于创建一个
EvaluationMetric对象的工厂函数。- Parameters
eval_fn –
一个计算指标的函数,具有以下签名:
def eval_fn( predictions: pandas.Series, targets: pandas.Series, metrics: Dict[str, MetricValue], **kwargs, ) -> Union[float, MetricValue]: """ Args: predictions: A pandas Series containing the predictions made by the model. targets: (Optional) A pandas Series containing the corresponding labels for the predictions made on that input. metrics: (Optional) A dictionary containing the metrics calculated by the default evaluator. The keys are the names of the metrics and the values are the metric values. To access the MetricValue for the metrics calculated by the system, make sure to specify the type hint for this parameter as Dict[str, MetricValue]. Refer to the DefaultEvaluator behavior section for what metrics will be returned based on the type of model (i.e. classifier or regressor). kwargs: Includes a list of args that are used to compute the metric. These args could information coming from input data, model outputs or parameters specified in the `evaluator_config` argument of the `mlflow.evaluate` API. kwargs: Includes a list of args that are used to compute the metric. These args could be information coming from input data, model outputs, other metrics, or parameters specified in the `evaluator_config` argument of the `mlflow.evaluate` API. Returns: MetricValue with per-row scores, per-row justifications, and aggregate results. """ ...
greater_is_better – 指标的值越大是否更好。
name – 指标的名称。如果
eval_fn是一个 lambda 函数 或者eval_fn.__name__属性不可用,则必须指定此参数。long_name – (Optional) The long name of the metric. For example,
"mean_squared_error"for"mse".version – (可选)指标的版本。例如
v1.metric_details – (可选) 对该度量的描述以及其计算方式。
metric_metadata – (可选) 一个包含该指标元数据的字典。
genai_metric_args – (可选)一个字典,包含用户在调用 make_genai_metric 或 make_genai_metric_from_prompt 时指定的参数。这些参数会被持久化,以便我们以后能够反序列化出相同的 metric 对象。
另请参见
mlflow.models.EvaluationMetric
- mlflow.models.predict(model_uri, input_data=None, input_path=None, content_type='json', output_path=None, env_manager='virtualenv', install_mlflow=False, pip_requirements_override=None, extra_envs=None)[source]
使用已保存的 MLflow 模型以 json 格式生成预测。有关该函数接受的输入数据格式的信息,请参阅以下文档:https://www.mlflow.org/docs/latest/models.html#built-in-deployment-tools.
注意
为了在调试时增加输出的详细程度(以便在处理瞬态依赖时检查完整的依赖解析器操作),可以考虑设置以下环境变量:
# For virtualenv export PIP_VERBOSE=1 # For uv export RUST_LOG=uv=debug
另请参见:
- Parameters
model_uri – 模型的 URI。本地路径、本地或远程的 URI,例如 runs:/、s3://。
input_data –
用于预测的输入数据。必须是 PyFunc 模型的有效输入。有关支持的输入类型,请参阅
mlflow.pyfunc.PyFuncModel.predict()。注意
如果此 API 因 input_data 中的错误而失败,请使用 mlflow.models.convert_input_example_to_serving_input 手动验证您的输入数据。
input_path – 指向包含输入数据的文件的路径。如果提供,则 ‘input_data’ 必须为 None。
content_type – 输入数据的内容类型。可以是 {‘json’, ‘csv’} 中的一个。
output_path – 将结果以 json 输出到文件。如果未提供,则输出到 stdout。
env_manager –
指定用于 MLmodel 推理的环境创建方式:
”virtualenv” (默认): 使用 virtualenv (并使用 pyenv 管理 Python 版本)
”uv”: 使用 uv
”local”: 使用本地环境
”conda”: 使用 conda
install_mlflow – 如果指定并且有要激活的 conda 或 virtualenv 环境,mlflow 将在该环境被激活后安装到该环境中。所安装的 mlflow 的版本将与用于调用此命令的版本相同。
pip_requirements_override –
如果指定,将在模型推理环境中安装指定的 Python 依赖项。这在您想添加额外依赖项或尝试已记录模型中定义的依赖项的不同版本时尤其有用。
提示
在验证 pip_requirements_override 按预期工作之后,您可以使用 mlflow.models.update_model_requirements API 更新已记录模型的依赖,而无需重新记录它。注意,已注册的模型是不可变的,因此您需要用更新后的模型注册一个新的模型版本。
extra_envs –
如果指定,将会把一个额外环境变量的字典传递到模型推理环境中。这对于测试模型运行所需的环境变量很有用。默认情况下,会传递当前 os.environ 中存在的环境变量,可以使用此参数来覆盖它们。
注意
如果你的模型依赖包括预发布版本,例如 mlflow==3.2.0rc0 并且你使用 uv 作为环境管理器,请在 extra_envs 中将 UV_PRERELEASE 环境变量设置为 “allow” 以允许安装预发布版本。 e.g. extra_envs={“UV_PRERELEASE”: “allow”}.
注意
仅当 env_manager 设置为 “virtualenv”、 “conda” 或 “uv” 时支持此参数。
代码示例:
import mlflow run_id = "..." mlflow.models.predict( model_uri=f"runs:/{run_id}/model", input_data={"x": 1, "y": 2}, content_type="json", ) # Run prediction with "uv" as the environment manager mlflow.models.predict( model_uri=f"runs:/{run_id}/model", input_data={"x": 1, "y": 2}, env_manager="uv", ) # Run prediction with additional pip dependencies and extra environment variables mlflow.models.predict( model_uri=f"runs:/{run_id}/model", input_data={"x": 1, "y": 2}, content_type="json", pip_requirements_override=["scikit-learn==0.23.2"], extra_envs={"OPENAI_API_KEY": "some_value"}, ) # Run prediction with output_path mlflow.models.predict( model_uri=f"runs:/{run_id}/model", input_data={"x": 1, "y": 2}, env_manager="uv", output_path="output.json", ) # Run prediction with pre-release versions mlflow.models.predict( model_uri=f"runs:/{run_id}/model", input_data={"x": 1, "y": 2}, env_manager="uv", extra_envs={"UV_PRERELEASE": "allow"}, )
- mlflow.models.set_model(model) None[source]
当以代码方式记录模型时,可使用此函数来设置要记录的模型对象。
- Parameters
model –
要记录的模型对象。支持的模型类型包括:
一个 Python 函数或可调用对象。
一个 Langchain 模型或指向 Langchain 模型的路径。
一个 Llama Index 模型或指向 Llama Index 模型的路径。
- mlflow.models.set_retriever_schema(*, primary_key: str, text_column: str, doc_uri: Optional[str] = None, other_columns: Optional[list[str]] = None, name: str | None = 'retriever')[source]
在你的智能体或生成式 AI 应用代码中,指定检索器跨度的返回模式。
注意:MLflow 建议你的检索器返回在 https://mlflow.org/docs/latest/tracing/tracing-schema#retriever-spans 中描述的默认 MLflow 检索器输出模式,在这种情况下你无需调用 set_retriever_schema。读取 MLflow 跟踪并查找检索器 span 的 API(例如 MLflow evaluation)将自动检测匹配 MLflow 默认检索器模式的检索器 span。
如果您的检索器未返回默认的 MLflow 检索器输出模式,请调用此 API 来指定每个检索到的文档中哪些字段对应页面内容、文档 URI、文档 ID 等。这样下游功能(例如 MLflow 评估)才能正确识别这些字段。请注意,set_retriever_schema 假定您的检索器 span 返回一个对象列表。
- Parameters
primary_key – 检索器或向量索引的主键。
text_column – 用于嵌入的文本列的名称。
doc_uri – 包含文档 URI 的列的名称。
other_columns – 一个包含需要在跟踪日志记录期间检索的、属于向量索引的其他列的列表。
name – 检索器工具或向量存储索引的名称。
from mlflow.models import set_retriever_schema # The following call sets the schema for a custom retriever that retrieves content from # MLflow documentation, with an output schema like: # [ # { # 'document_id': '9a8292da3a9d4005a988bf0bfdd0024c', # 'chunk_text': 'MLflow is an open-source platform, purpose-built to assist...', # 'doc_uri': 'https://mlflow.org/docs/latest/index.html', # 'title': 'MLflow: A Tool for Managing the Machine Learning Lifecycle' # }, # { # 'document_id': '7537fe93c97f4fdb9867412e9c1f9e5b', # 'chunk_text': 'A great way to get started with MLflow is...', # 'doc_uri': 'https://mlflow.org/docs/latest/getting-started/', # 'title': 'Getting Started with MLflow' # }, # ... # ] set_retriever_schema( primary_key="chunk_id", text_column="chunk_text", doc_uri="doc_uri", other_columns=["title"], name="my_custom_retriever", )
- mlflow.models.set_signature(model_uri: str, signature: mlflow.models.signature.ModelSignature)[source]
为指定的模型工件设置模型签名。
该过程涉及在模型工件中下载 MLmodel 文件(如果它是非本地的)、更新其模型签名,然后覆盖现有的 MLmodel 文件。如果与模型工件关联的工件存储库不允许覆盖,则该函数将失败。
此外,由于模型注册表的工件是只读的,位于模型注册表中并以
models:/URI 方案表示的模型工件与此 API 不兼容。要在某个模型版本上设置签名,首先需要在源模型工件上设置签名。随后,使用更新后的模型工件生成一个新的模型版本。有关在模型版本上设置签名的更多信息,请参见 this doc section。- Parameters
model_uri –
MLflow 模型在 URI 格式下的位置。例如:
/Users/me/path/to/local/modelrelative/path/to/local/models3://my_bucket/path/to/modelruns://run-relative/path/to/model mlflow-artifacts:/path/to/modelmodels:/
有关受支持的 URI 方案的更多信息,请参阅 Referencing Artifacts。
请注意,使用
models:/方案的模型 URI 不受支持。/ signature – 要在模型上设置的 ModelSignature。
import mlflow from mlflow.models import set_signature, infer_signature # load model from run artifacts run_id = "96771d893a5e46159d9f3b49bf9013e2" artifact_path = "models" model_uri = f"runs:/{run_id}/{artifact_path}" model = mlflow.pyfunc.load_model(model_uri) # determine model signature test_df = ... predictions = model.predict(test_df) signature = infer_signature(test_df, predictions) # set the signature for the logged model set_signature(model_uri, signature)
- mlflow.models.update_model_requirements(model_uri: str, operation: Literal['add', 'remove'], requirement_list: list[str]) None[source]
从模型的 conda.yaml 和 requirements.txt 文件中添加或删除依赖项。
该过程涉及从模型工件下载这两个文件(如果它们不是本地的)、用指定的要求更新它们,然后覆盖现有文件。如果与模型工件关联的工件存储库不允许覆盖,该函数将失败。
注意,模型注册表的 URI(即形式为
models:/的 URI)不受支持,因为模型注册表中的工件是只读的。如果添加 requirements,函数会覆盖任何重叠的已存在 requirements,或者将新的 requirements 附加到现有列表中。
如果移除 requirements,函数将忽略任何版本说明符,并移除所有指定的包名。任何在现有文件中未找到的 requirements 将被忽略。
- Parameters
model_uri –
MLflow 模型的 URI 格式位置。例如:
/Users/me/path/to/local/modelrelative/path/to/local/models3://my_bucket/path/to/modelruns:/<mlflow_run_id>/run-relative/path/to/modelmlflow-artifacts:/path/to/model
有关受支持的 URI 方案的更多信息,请参见 Referencing Artifacts.
operation – 要执行的操作。必须是 “add” 或 “remove” 之一。
requirement_list – 要添加到模型或从模型中移除的依赖项列表。 例如: [“numpy==1.20.3”, “pandas>=1.3.3”]
- mlflow.models.validate_schema(data: Union[pandas.core.frame.DataFrame, pandas.core.series.Series, numpy.ndarray, scipy.sparse._csc.csc_matrix, scipy.sparse._csr.csr_matrix, List[Any], Dict[str, Any], datetime.datetime, bool, bytes, float, int, str, pyspark.sql.dataframe.DataFrame], expected_schema: mlflow.types.schema.Schema) None[source]
验证输入数据是否具有预期的模式。
- Parameters
data –
要验证的输入数据。支持的类型有:
pandas.DataFrame
pandas.Series
numpy.ndarray
scipy.sparse.csc_matrix
scipy.sparse.csr_matrix
List[Any]
Dict[str, Any]
str
expected_schema – 输入数据的预期模式。
- Raises
mlflow.exceptions.MlflowException – 当输入数据与架构不匹配时。
import mlflow.models # Suppose you've already got a model_uri model_info = mlflow.models.get_model_info(model_uri) # Get model signature directly model_signature = model_info.signature # validate schema mlflow.models.validate_schema(input_data, model_signature.inputs)
- mlflow.models.validate_serving_input(model_uri: str, serving_input: str | dict[str, typing.Any])[source]
辅助函数,用于在部署模型之前验证模型是否可以提供服务并且所提供的输入是否有效。
- Parameters
model_uri – 要服务的模型的 URI。
serving_input – 要验证的输入数据。应该是一个字典或 JSON 字符串。
- Returns
模型的预测结果。
- class mlflow.models.model.ModelInfo(artifact_path: str, flavors: dict[str, typing.Any], model_uri: str, model_uuid: str, run_id: str, saved_input_example_info: dict[str, typing.Any] | None, signature, utc_time_created: str, mlflow_version: str, metadata: Optional[dict[str, typing.Any]] = None, registered_model_version: Optional[int] = None, env_vars: Optional[list[str]] = None, prompts: Optional[list[str]] = None, logged_model: Optional[LoggedModel] = None)[source]
已记录的 MLflow Model 的元数据。
- property env_vars: list[str] | None
模型记录过程中使用的环境变量。
- Getter
获取在模型记录过程中使用的环境变量。
- Type
Optional[List[str]]
- property flavors: dict[str, typing.Any]
一个字典,将 flavor 名称映射到如何以该 flavor 的方式提供模型。
- Getter
获取已记录模型的 flavor 的映射,该映射定义了用于模型服务的参数
- Type
Dict[str, str]
{ "python_function": { "model_path": "model.pkl", "loader_module": "mlflow.sklearn", "python_version": "3.8.10", "env": "conda.yaml", }, "sklearn": { "pickled_model": "model.pkl", "sklearn_version": "0.24.1", "serialization_format": "cloudpickle", }, }
- property metadata: dict[str, typing.Any] | None
添加到模型中的用户定义元数据。
- Getter
获取有关模型的用户定义的元数据
- Type
Optional[Dict[str, Any]]
# Create and log a model with metadata to the Model Registry from sklearn import datasets from sklearn.ensemble import RandomForestClassifier import mlflow from mlflow.models import infer_signature with mlflow.start_run(): iris = datasets.load_iris() clf = RandomForestClassifier() clf.fit(iris.data, iris.target) signature = infer_signature(iris.data, iris.target) mlflow.sklearn.log_model( clf, name="iris_rf", signature=signature, registered_model_name="model-with-metadata", metadata={"metadata_key": "metadata_value"}, ) # model uri for the above model model_uri = "models:/model-with-metadata/1" # Load the model and access the custom metadata from its ModelInfo object model = mlflow.pyfunc.load_model(model_uri=model_uri) assert model.metadata.get_model_info().metadata["metadata_key"] == "metadata_value" # Load the ModelInfo and access the custom metadata model_info = mlflow.models.get_model_info(model_uri=model_uri) assert model_info.metadata["metadata_key"] == "metadata_value"
- property metrics: list[指标] | None
返回已记录模型的指标。
- Getter
检索已记录的模型的指标
- property model_uri: str
已记录模型的
model_uri,格式为'runs:/。/ ' - Getter
从 uri runs:/
的路径封装中获取已记录模型的 uri 路径 - Type
str
- property model_uuid: str
已记录模型的
model_uuid,例如,'39ca11813cfc46b09ab83972740b80ca'。- Getter
[遗留] 获取已记录模型的 model_uuid (run_id)
- Type
str
- property registered_model_version: int | None
如果模型已注册,则为已注册模型的版本。
- Getter
获取已注册的模型版本(如果该模型已在 Model Registry 中注册)。
- Setter
设置已注册的模型版本。
- Type
Optional[int]
- property run_id: str
与已记录模型关联的
run_id,例如'8ede7df408dd42ed9fc39019ef7df309'- Getter
获取已记录模型的 run_id 标识符
- Type
str
- property saved_input_example_info: dict[str, typing.Any] | None
一个字典,包含已保存输入示例的元数据,例如,
{"artifact_path": "input_example.json", "type": "dataframe", "pandas_orient": "split"}.- Getter
如果在模型记录期间指定了输入示例,则获取该输入示例
- Type
Optional[Dict[str, str]]
- property signature
一个
ModelSignature,用于描述模型的输入和输出。- Getter
如果已定义,则获取模型签名
- Type
可选[ModelSignature]