mlflow.lightgbm

mlflow.lightgbm 模块提供用于记录和加载 LightGBM 模型的 API。该模块以以下格式导出 LightGBM 模型:

LightGBM (native) format

这是可以重新加载到 LightGBM 的主要 flavor。

mlflow.pyfunc

用于通用的基于 pyfunc 的部署工具和批量推理。

mlflow.lightgbm.autolog(log_input_examples=False, log_model_signatures=True, log_models=True, log_datasets=True, disable=False, exclusive=False, disable_for_unsupported_versions=False, silent=False, registered_model_name=None, extra_tags=None)[source]

注意

Autologging 已知与以下软件包版本兼容: 4.1.0 <= lightgbm <= 4.6.0. Autologging 可能在与该范围之外的包版本一起使用时无法成功。

启用(或禁用)并配置从 LightGBM 到 MLflow 的自动记录。记录以下内容:

  • lightgbm.train 中指定的参数。

  • 每次迭代的指标(如果指定了valid_sets)。

  • 在最佳迭代处的指标(如果指定了 early_stopping_rounds 或设置了 early_stopping 回调)。

  • 特征重要性(包括 “split” 和 “gain”)以 JSON 文件和图表的形式。

  • trained model, including:
    • 一个有效输入的示例。

    • 模型的输入和输出的推断签名。

请注意,scikit-learn API 现在已受支持。

Parameters
  • log_input_examples – 如果 True,则会从训练数据集中收集输入示例,并在训练期间与 LightGBM 模型工件一起记录。如果 False,则不会记录输入示例。注意:输入示例是 MLflow 模型属性,只有在 log_models 也为 True 时才会被收集。

  • log_model_signatures – 如果 TrueModelSignatures 描述模型的输入和输出,将在训练期间与 LightGBM 模型工件一起收集并记录。如果 False,则不会记录签名。注意:模型签名是 MLflow 模型属性,仅当 log_models 也为 True 时才会被收集。

  • log_models – 如果 True,训练好的模型将作为 MLflow 模型工件被记录。 如果 False,训练好的模型不会被记录。 输入示例和模型签名(它们是 MLflow 模型的属性)在 log_modelsFalse 时也会被省略。

  • log_datasets – 如果 True,则会将训练和验证数据集信息记录到 MLflow Tracking(如果适用)。如果 False,则不记录数据集信息。

  • disable – 如果 True,则禁用 LightGBM 的 autologging 集成。如果 False,则启用 LightGBM 的 autologging 集成。

  • exclusive – 如果 True,自动记录的内容不会记录到用户创建的 fluent 运行。 如果 False,自动记录的内容会记录到活动的 fluent 运行,该运行可能是用户创建的。

  • disable_for_unsupported_versions – 如果 True,则为尚未针对此版本的 MLflow 客户端进行测试或与之不兼容的 lightgbm 版本禁用 autologging。

  • silent – 如果 True,在 LightGBM autologging 期间抑制来自 MLflow 的所有事件日志和警告。如果 False,则在 LightGBM autologging 期间显示所有事件和警告。

  • registered_model_name – 如果提供,每次训练模型时,会将模型注册为具有此名称的注册模型的新版本。如果该注册模型尚不存在,则会创建它。

  • extra_tags – 一个字典,用于在 autologging 创建的每个托管运行上设置额外标签。

Example
import mlflow
from lightgbm import LGBMClassifier
from sklearn import datasets


def print_auto_logged_info(run):
    tags = {k: v for k, v in run.data.tags.items() if not k.startswith("mlflow.")}
    artifacts = [
        f.path for f in mlflow.MlflowClient().list_artifacts(run.info.run_id, "model")
    ]
    feature_importances = [
        f.path
        for f in mlflow.MlflowClient().list_artifacts(run.info.run_id)
        if f.path != "model"
    ]
    print(f"run_id: {run.info.run_id}")
    print(f"artifacts: {artifacts}")
    print(f"feature_importances: {feature_importances}")
    print(f"params: {run.data.params}")
    print(f"metrics: {run.data.metrics}")
    print(f"tags: {tags}")


# Load iris dataset
X, y = datasets.load_iris(return_X_y=True, as_frame=True)

# Initialize our model
model = LGBMClassifier(objective="multiclass", random_state=42)

# Auto log all MLflow entities
mlflow.lightgbm.autolog()

# Train the model
with mlflow.start_run() as run:
    model.fit(X, y)

# fetch the auto logged parameters and metrics
print_auto_logged_info(mlflow.get_run(run_id=run.info.run_id))
Output
run_id: e08dd59d57a74971b68cf78a724dfaf6
artifacts: ['model/MLmodel',
            'model/conda.yaml',
            'model/model.pkl',
            'model/python_env.yaml',
            'model/requirements.txt']
feature_importances: ['feature_importance_gain.json',
                      'feature_importance_gain.png',
                      'feature_importance_split.json',
                      'feature_importance_split.png']
params: {'boosting_type': 'gbdt',
         'categorical_feature': 'auto',
         'colsample_bytree': '1.0',
         ...
         'verbose_eval': 'warn'}
metrics: {}
tags: {}
mlflow.lightgbm.get_default_conda_env(include_cloudpickle=False)[source]
Returns

默认的 Conda 环境,用于由调用 save_model()log_model() 生成的 MLflow 模型。

mlflow.lightgbm.get_default_pip_requirements(include_cloudpickle=False)[source]
Returns

该列表列出了由此 flavor 生成的 MLflow Models 的默认 pip 依赖项。 对 save_model()log_model() 的调用会生成一个 pip 环境,该环境至少包含这些依赖项。

mlflow.lightgbm.load_model(model_uri, dst_path=None)[source]

从本地文件或一次运行加载 LightGBM 模型。

Parameters
  • model_uri

    MLflow 模型的 URI 格式的位置。例如:

    • /Users/me/path/to/local/model

    • relative/path/to/local/model

    • s3://my_bucket/path/to/model

    • runs:/<mlflow_run_id>/run-relative/path/to/model

    有关受支持的 URI 方案的更多信息,请参见 Referencing Artifacts

  • dst_path – 要将模型工件下载到的本地文件系统路径。该目录必须已存在。如果未指定,将创建一个本地输出路径。

Returns

一个 LightGBM 模型(lightgbm.Booster 的一个实例)或一个 LightGBM scikit-learn 模型,取决于已保存模型类的规范。

Example
from lightgbm import LGBMClassifier
from sklearn import datasets
import mlflow

# Auto log all MLflow entities
mlflow.lightgbm.autolog()

# Load iris dataset
X, y = datasets.load_iris(return_X_y=True, as_frame=True)

# Initialize our model
model = LGBMClassifier(objective="multiclass", random_state=42)

# Train the model
model.fit(X, y)

# Load model for inference
model_uri = f"runs:/{mlflow.last_active_run().info.run_id}/model"
loaded_model = mlflow.lightgbm.load_model(model_uri)
print(loaded_model.predict(X[:5]))
Output
[0 0 0 0 0]
mlflow.lightgbm.log_model(lgb_model, artifact_path: str | None = None, conda_env=None, code_paths=None, registered_model_name=None, signature: mlflow.models.signature.ModelSignature = None, input_example: Union[pandas.core.frame.DataFrame, numpy.ndarray, dict, list, csr_matrix, csc_matrix, str, bytes, tuple] = None, await_registration_for=300, pip_requirements=None, extra_pip_requirements=None, metadata=None, name: str | None = None, params: dict[str, typing.Any] | None = None, tags: dict[str, typing.Any] | None = None, model_type: str | None = None, step: int = 0, model_id: str | None = None, **kwargs)[source]

将 LightGBM 模型作为当前运行的 MLflow 工件记录。

Parameters
  • lgb_model – LightGBM 模型 (lightgbm.Booster 的一个实例) 或实现 scikit-learn API 的模型,待保存。

  • artifact_path – 已弃用。请改用 name

  • conda_env

    可以是 Conda 环境的字典表示形式,或者指向 conda 环境 yaml 文件的路径。如果提供,该项描述了应在其中运行此模型的环境。至少,它应当指定 get_default_conda_env() 中包含的依赖项。如果 None,则会将一个包含由 mlflow.models.infer_pip_requirements() 推断出的 pip 依赖项的 conda 环境添加到模型中。如果依赖推断失败,则回退使用 get_default_pip_requirements。来自 conda_env 的 pip 依赖项将被写入到 pip requirements.txt 文件,而完整的 conda 环境将被写入到 conda.yaml。下面是一个 示例 的 conda 环境的字典表示:

    {
        "name": "mlflow-env",
        "channels": ["conda-forge"],
        "dependencies": [
            "python=3.8.15",
            {
                "pip": [
                    "lightgbm==x.y.z"
                ],
            },
        ],
    }
    

  • code_paths

    本地文件系统中指向 Python 文件依赖(或包含文件依赖的目录)路径的列表。这些文件在模型加载时会被预先添加到系统路径中。如果为某个模型声明了依赖文件且多个文件之间存在导入依赖关系,那么这些文件应从一个共同的根路径声明相对导入,以避免在加载模型时发生导入错误。

    有关 code_paths 功能、推荐的使用模式和限制的详细说明,请参阅 code_paths usage guide

  • registered_model_name – 如果提供,将在 registered_model_name 下创建一个模型版本,并在不存在同名的注册模型时创建该注册模型。

  • signature

    一个 ModelSignature 类的实例,用于描述模型的输入和输出。如果未指定但提供了 input_example,则会根据提供的输入示例和模型自动推断签名。要在提供输入示例时禁用自动签名推断,请将 signature 设置为 False。要手动推断模型签名,请在具有有效模型输入,例如省略了目标列的训练数据集,以及有效模型输出,例如在训练数据集上生成的模型预测的数据集上调用 infer_signature(),例如:

    from mlflow.models import infer_signature
    
    train = df.drop_column("target_label")
    predictions = ...  # 计算模型预测
    signature = infer_signature(train, predictions)
    

  • input_example – 一个或多个有效模型输入实例。输入示例用于提示应向模型提供何种数据。它将被转换为一个 Pandas DataFrame,然后使用 Pandas 的 split-oriented 格式序列化为 json,或者转换为一个 numpy array,其中示例将通过将其转换为列表的方式序列化为 json。字节使用 base64 编码。当 signature 参数为 None 时,输入示例用于推断模型签名。

  • await_registration_for – 等待模型版本完成创建并处于 READY 状态的秒数。默认情况下,函数等待五分钟。指定 0 或 None 可跳过等待。

  • pip_requirements – 要么是一个可迭代的 pip 依赖字符串(例如 ["lightgbm", "-r requirements.txt", "-c constraints.txt"])或本地文件系统上 pip 依赖文件的字符串路径(例如 "requirements.txt")。如果提供,它描述了运行此模型所需的环境。如果 None,则会由 mlflow.models.infer_pip_requirements() 从当前软件环境推断出默认的依赖列表。如果依赖推断失败,则回退到使用 get_default_pip_requirements。依赖和约束会被自动解析并分别写入 requirements.txtconstraints.txt 文件中,并作为模型的一部分存储。依赖也会写入模型的 conda 环境(conda.yaml)文件的 pip 部分。

  • extra_pip_requirements

    要么是一个 pip 需求字符串的可迭代对象(例如 ["pandas", "-r requirements.txt", "-c constraints.txt"]),要么是本地文件系统上 pip requirements 文件的字符串路径(例如 "requirements.txt")。如果提供,该参数描述了附加的 pip 依赖,这些依赖会被追加到基于用户当前软件环境自动生成的默认 pip 依赖集合中。requirements 和 constraints 会被自动解析并分别写入 requirements.txtconstraints.txt 文件,并作为模型的一部分存储。依赖项也会被写入模型的 conda 环境(conda.yaml)文件的 pip 部分。

    警告

    以下参数不能同时指定:

    • conda_env

    • pip_requirements

    • extra_pip_requirements

    This example 演示了如何使用 pip_requirementsextra_pip_requirements 指定 pip 依赖。

  • metadata – 传递给模型并存储在 MLmodel 文件中的自定义元数据字典。

  • name – 模型名称。

  • params – 一个用于与模型一同记录的参数字典。

  • tags – 一个要与模型一起记录的标签字典。

  • model_type – 模型的类型。

  • step – 在该步记录模型输出和指标

  • model_id – 模型的 ID。

  • kwargs – 传递给 lightgbm.Booster.save_model 方法的 kwargs。

Returns

一个 ModelInfo 实例,包含已记录模型的元数据。

Example
from lightgbm import LGBMClassifier
from sklearn import datasets
import mlflow
from mlflow.models import infer_signature

# Load iris dataset
X, y = datasets.load_iris(return_X_y=True, as_frame=True)

# Initialize our model
model = LGBMClassifier(objective="multiclass", random_state=42)

# Train the model
model.fit(X, y)

# Create model signature
predictions = model.predict(X)
signature = infer_signature(X, predictions)

# Log the model
artifact_path = "model"
with mlflow.start_run():
    model_info = mlflow.lightgbm.log_model(
        model, name=artifact_path, signature=signature
    )

# Fetch the logged model artifacts
print(f"run_id: {run.info.run_id}")
client = mlflow.MlflowClient()
artifacts = [f.path for f in client.list_artifacts(run.info.run_id, artifact_path)]
print(f"artifacts: {artifacts}")
Output
artifacts: ['model/MLmodel',
            'model/conda.yaml',
            'model/model.pkl',
            'model/python_env.yaml',
            'model/requirements.txt']
mlflow.lightgbm.save_model(lgb_model, path, conda_env=None, code_paths=None, mlflow_model=None, signature: mlflow.models.signature.ModelSignature = None, input_example: Union[pandas.core.frame.DataFrame, numpy.ndarray, dict, list, csr_matrix, csc_matrix, str, bytes, tuple] = None, pip_requirements=None, extra_pip_requirements=None, metadata=None)[source]

将 LightGBM 模型保存到本地文件系统的路径中。

Parameters
  • lgb_model – LightGBM 模型(一个 lightgbm.Booster 实例)或实现了 scikit-learn API 的模型,待保存。

  • path – 模型要保存的本地路径。

  • conda_env

    可以是 Conda 环境的字典表示,也可以是指向 conda 环境 yaml 文件的路径。如果提供,它描述了运行此模型所需的环境。至少,它应指定 get_default_conda_env() 中包含的依赖项。如果 None,会将由 mlflow.models.infer_pip_requirements() 推断出的 pip 依赖项加入到模型的 conda 环境中。如果依赖推断失败,则回退到使用 get_default_pip_requirements。来自 conda_env 的 pip 要求会写入 pip requirements.txt 文件,完整的 conda 环境会写入 conda.yaml。下面是一个 example 字典表示的 conda 环境:

    {
        "name": "mlflow-env",
        "channels": ["conda-forge"],
        "dependencies": [
            "python=3.8.15",
            {
                "pip": [
                    "lightgbm==x.y.z"
                ],
            },
        ],
    }
    

  • code_paths

    本地文件系统中指向 Python 文件依赖(或包含文件依赖的目录)路径的列表。这些文件在模型加载时会被预先添加到系统路径中。如果为某个模型声明了依赖文件且多个文件之间存在导入依赖关系,那么这些文件应从一个共同的根路径声明相对导入,以避免在加载模型时发生导入错误。

    有关 code_paths 功能、推荐的使用模式和限制的详细说明,请参阅 code_paths usage guide

  • mlflow_modelmlflow.models.Model 此 flavor 正在被添加到。

  • signature

    一个 ModelSignature 类的实例,用于描述模型的输入和输出。如果未指定但提供了 input_example,则会根据提供的输入示例和模型自动推断签名。要在提供输入示例时禁用自动签名推断,请将 signature 设置为 False。要手动推断模型签名,请在具有有效模型输入,例如省略了目标列的训练数据集,以及有效模型输出,例如在训练数据集上生成的模型预测的数据集上调用 infer_signature(),例如:

    from mlflow.models import infer_signature
    
    train = df.drop_column("target_label")
    predictions = ...  # 计算模型预测
    signature = infer_signature(train, predictions)
    

  • input_example – 一个或多个有效模型输入实例。输入示例用于提示应向模型提供何种数据。它将被转换为一个 Pandas DataFrame,然后使用 Pandas 的 split-oriented 格式序列化为 json,或者转换为一个 numpy array,其中示例将通过将其转换为列表的方式序列化为 json。字节使用 base64 编码。当 signature 参数为 None 时,输入示例用于推断模型签名。

  • pip_requirements – 要么是一个 pip 依赖字符串的可迭代对象 (e.g. ["lightgbm", "-r requirements.txt", "-c constraints.txt"]),要么是本地文件系统上 pip requirements 文件的字符串路径(e.g. "requirements.txt")。如果提供,它描述了应该在其中运行该模型的环境。如果 None,则由 mlflow.models.infer_pip_requirements() 从当前软件环境推断出默认的依赖列表。如果依赖推断失败,则回退到使用 get_default_pip_requirements。依赖项和约束会分别被自动解析并写入到 requirements.txtconstraints.txt 文件中,并作为模型的一部分进行存储。依赖项也会被写入模型的 conda 环境(conda.yaml)文件的 pip 部分。

  • extra_pip_requirements

    要么是一个 pip 需求字符串的可迭代对象(例如 ["pandas", "-r requirements.txt", "-c constraints.txt"]),要么是本地文件系统上 pip requirements 文件的字符串路径(例如 "requirements.txt")。如果提供,该参数描述了附加的 pip 依赖,这些依赖会被追加到基于用户当前软件环境自动生成的默认 pip 依赖集合中。requirements 和 constraints 会被自动解析并分别写入 requirements.txtconstraints.txt 文件,并作为模型的一部分存储。依赖项也会被写入模型的 conda 环境(conda.yaml)文件的 pip 部分。

    警告

    以下参数不能同时指定:

    • conda_env

    • pip_requirements

    • extra_pip_requirements

    This example 演示了如何使用 pip_requirementsextra_pip_requirements 指定 pip 依赖。

  • metadata – 传递给模型并存储在 MLmodel 文件中的自定义元数据字典。

Example
from pathlib import Path
from lightgbm import LGBMClassifier
from sklearn import datasets
import mlflow

# Load iris dataset
X, y = datasets.load_iris(return_X_y=True, as_frame=True)

# Initialize our model
model = LGBMClassifier(objective="multiclass", random_state=42)

# Train the model
model.fit(X, y)

# Save the model
path = "model"
mlflow.lightgbm.save_model(model, path)

# Load model for inference
loaded_model = mlflow.lightgbm.load_model(Path.cwd() / path)
print(loaded_model.predict(X[:5]))
Output
[0 0 0 0 0]