hscredit.core.models.boosting.lightgbm_model 源代码

"""LightGBM风控模型.

基于LightGBM实现的风控模型,支持自定义损失函数和评估指标。

**依赖**
pip install lightgbm

**参考样例**
>>> from hscredit.core.models import LightGBM
>>> model = LightGBM(
...     num_leaves=31,
...     learning_rate=0.1,
...     n_estimators=100,
...     eval_metric=['auc', 'ks']
... )
>>> model.fit(X_train, y_train)
>>> proba = model.predict_proba(X_test)
"""

from importlib import util
import inspect
from typing import Any, Dict, List, Optional, Tuple, Union

from .._lifecycle import record_training

import numpy as np
import pandas as pd
from packaging.version import Version
from scipy.special import expit
from sklearn.metrics import roc_curve

from ...._compat import (
    install_lightgbm_sklearn_compat,
    install_lightgbm_verbosity_compat,
    installed_version,
    prepare_dependency,
)
from ..base import BaseRiskModel, resolve_custom_objective
from ..losses.base import BaseLoss, BaseMetric

prepare_dependency("lightgbm")
LIGHTGBM_VERSION = installed_version("lightgbm")

if util.find_spec("lightgbm") is not None:
    import lightgbm as lgb

    LIGHTGBM_AVAILABLE = True
    install_lightgbm_verbosity_compat(lgb, LIGHTGBM_VERSION)
    install_lightgbm_sklearn_compat(
        lgb,
        LIGHTGBM_VERSION,
        installed_version("sklearn", "scikit-learn"),
    )
else:
    LIGHTGBM_AVAILABLE = False
    lgb = None


def _lightgbm_fit_api(version: Optional[Version]) -> str:
    """按 LightGBM 版本返回稳定的 sklearn fit 调用策略。

    LightGBM 3.3.0 起提供 ``early_stopping`` / ``log_evaluation`` 回调,同时
    ``fit`` 的 ``verbose`` / ``early_stopping_rounds`` 参数被弃用(4.0 起移除);
    因此 3.3.0 及以上走 callbacks 路径以消除弃用告警,更早版本回退到 fit 参数。

    :param version: LightGBM 版本
    :return: ``'legacy'`` (< 3.3.0,用 fit 参数)或 ``'callbacks'`` (≥ 3.3.0,用回调)
    :raises ImportError: LightGBM 未安装时
    """
    if version is None:
        raise ImportError("LightGBM未安装,请使用 pip install lightgbm 安装")
    return "legacy" if version < Version("3.3.0") else "callbacks"


def _lightgbm_ks_metric(y_true, y_pred):
    """LightGBM sklearn 接口使用的 KS 评估函数。"""
    y_true = np.asarray(y_true)
    if np.unique(y_true).size < 2:
        return "ks", 0.0, True
    fpr, tpr, _ = roc_curve(y_true, np.asarray(y_pred), pos_label=1)
    return "ks", float(np.max(np.abs(tpr - fpr))), True


class _SelectedMetricEarlyStopping:
    """先排列指定的早停指标,支持同时记录原生指标和自定义指标。"""

    order = 30
    before_iteration = False

    def __init__(self, callback, metric):
        self.callback = callback
        self.metric = metric

    def __call__(self, env):
        results = env.evaluation_result_list
        if not any(item[1] == self.metric for item in results):
            raise ValueError(f"验证结果中不存在早停指标 {self.metric!r}")
        ordered = sorted(results, key=lambda item: item[1] != self.metric)
        if hasattr(env, "_replace"):
            selected_env = env._replace(evaluation_result_list=ordered)
        else:
            from copy import copy

            selected_env = copy(env)
            selected_env.evaluation_result_list = ordered
        return self.callback(selected_env)


[文档] class LightGBM(BaseRiskModel): """LightGBM风控模型. 基于LightGBM的二分类模型,针对风控场景优化。 LightGBM相比XGBoost训练更快,内存占用更少。 **参数** :param num_leaves: 叶子节点数,默认31 :type num_leaves: int :param max_depth: 树最大深度,默认-1(无限制) :type max_depth: int :param learning_rate: 学习率,默认0.1 :type learning_rate: float :param n_estimators: 树的数量,默认100 :type n_estimators: int :param min_child_samples: 叶子节点最小样本数,默认20 :type min_child_samples: int :param min_child_weight: 叶子节点最小权重和,默认1e-3 :type min_child_weight: float :param subsample: 样本采样比例,默认1.0 :type subsample: float :param colsample_bytree: 特征采样比例,默认1.0 :type colsample_bytree: float :param reg_alpha: L1正则化系数,默认0 :type reg_alpha: float :param reg_lambda: L2正则化系数,默认0 :type reg_lambda: float :param scale_pos_weight: 正负样本权重比,默认1 :type scale_pos_weight: float :param min_split_gain: 节点分裂所需的最小增益,默认0 :type min_split_gain: float :param boosting_type: 提升类型,默认'gbdt' - 'gbdt': 传统梯度提升树 - 'dart': Dropouts meet Multiple Additive Regression Trees - 'goss': Gradient-based One-Side Sampling - 'rf': 随机森林 :type boosting_type: str :param objective: 目标函数,默认'binary' :type objective: str :param eval_metric: 评估指标,可选名称、BaseMetric 对象或列表;自定义损失默认使用其配套指标 - 多个指标时,默认使用第一个指标进行早停 :type eval_metric: Union[str, BaseMetric, List[Union[str, BaseMetric]], None] :param early_stopping_rounds: 早停轮数,默认None :type early_stopping_rounds: Optional[int] :param early_stopping_metric: 用于早停的评估指标名称,默认None(使用第一个指标) - 当eval_metric有多个时,可通过此参数指定用哪个指标进行早停判断 :type early_stopping_metric: Optional[str] :param first_metric_only: 是否只用第一个评估指标进行早停,默认True - 当eval_metric为列表时,True表示只用第一个指标早停,False表示监控所有指标 :type first_metric_only: bool :param validation_fraction: 验证集比例,默认0.2 :type validation_fraction: float :param random_state: 随机种子,默认None :type random_state: Optional[int] :param n_jobs: 并行任务数,默认-1 :type n_jobs: int :param verbose: 是否输出详细信息,默认False :type verbose: bool :param params: LightGBM原生参数字典,默认None - 如果传入,将覆盖其他参数设置 - 可直接使用LightGBM原生参数名 :type params: Optional[Dict[str, Any]] :param kwargs: 其他LightGBM参数 **属性** :ivar feature_importances_: 特征重要性 :ivar evals_result_: 训练过程评估结果 :ivar best_iteration_: 最佳迭代次数 :ivar best_score_: 最佳得分 :ivar booster_: 底层LightGBM模型 **参考样例** >>> # 基础使用 >>> model = LightGBM(num_leaves=31, learning_rate=0.1) >>> model.fit(X_train, y_train) >>> # 使用原生LightGBM参数 >>> params = {'num_leaves': 31, 'learning_rate': 0.05, 'subsample': 0.8} >>> model = LightGBM(params=params) >>> model.fit(X_train, y_train) **引用** 基于 LightGBM 梯度提升框架(leaf-wise 生长 + 直方图算法),见 Ke, G. et al. (2017). *LightGBM: A Highly Efficient Gradient Boosting Decision Tree.* NeurIPS;文档 https://lightgbm.readthedocs.io/ 。 **参数补充** :param scorecard_params: 默认值为 ``None`` 。概率评分刻度的覆盖参数,如 pdo、base_score、lower、upper、base_bad_rate;只影响 predict_score,不修改 predict_proba :type scorecard_params: Optional[Dict[str, Any]] """ _preserve_dataframe = True _parameter_aliases = { "n_estimators": ("num_iterations", "num_iteration", "num_boost_round", "num_trees"), "learning_rate": ("eta", "shrinkage_rate"), "num_leaves": ("num_leaf", "max_leaves", "max_leaf_nodes"), "n_jobs": ("num_threads", "num_thread", "nthread"), "random_state": ("seed", "random_seed"), "subsample": ("bagging_fraction",), "colsample_bytree": ("feature_fraction",), "min_child_samples": ("min_data_in_leaf", "min_data"), "reg_alpha": ("lambda_l1",), "reg_lambda": ("lambda_l2",), } def __init__( self, num_leaves: int = 31, max_depth: int = -1, learning_rate: float = 0.1, n_estimators: int = 100, min_child_samples: int = 20, min_child_weight: float = 1e-3, subsample: float = 1.0, colsample_bytree: float = 1.0, reg_alpha: float = 0, reg_lambda: float = 0, scale_pos_weight: float = 1, min_split_gain: float = 0, boosting_type: str = "gbdt", objective: str = "binary", eval_metric: Union[str, BaseMetric, List[Union[str, BaseMetric]], None] = None, early_stopping_rounds: Optional[int] = None, early_stopping_metric: Optional[str] = None, first_metric_only: bool = True, validation_fraction: float = 0.2, random_state: Optional[int] = None, n_jobs: int = -1, verbose: bool = False, params: Optional[Dict[str, Any]] = None, scorecard_params: Optional[Dict[str, Any]] = None, **kwargs, ): if not LIGHTGBM_AVAILABLE: raise ImportError("LightGBM未安装,请使用 pip install lightgbm 安装") # sklearn clone 必须能够原样往返构造输入,原生覆盖值只用于实际训练。 self._constructor_params = {name: value for name, value in locals().items() if name not in {"self", "kwargs", "__class__"}} self._constructor_kwargs = dict(kwargs) # 保存原生params参数 self.params = params # 用于sklearn get_params兼容性 self._native_params = dict(params or {}) # 从params中提取参数(如果提供了原生参数) num_leaves = self._native_params.get("num_leaves", num_leaves) max_depth = self._native_params.get("max_depth", max_depth) learning_rate = self._native_params.get("learning_rate", learning_rate) n_estimators = self._native_params.get("n_estimators", n_estimators) min_child_samples = self._native_params.get("min_child_samples", min_child_samples) min_child_weight = self._native_params.get("min_child_weight", min_child_weight) subsample = self._native_params.get("subsample", subsample) colsample_bytree = self._native_params.get("colsample_bytree", colsample_bytree) reg_alpha = self._native_params.get("reg_alpha", reg_alpha) reg_lambda = self._native_params.get("reg_lambda", reg_lambda) scale_pos_weight = self._native_params.get("scale_pos_weight", scale_pos_weight) min_split_gain = self._native_params.get("min_split_gain", min_split_gain) boosting_type = self._native_params.get("boosting_type", boosting_type) objective = self._native_params.get("objective", objective) random_state = self._native_params.get("random_state", random_state) n_jobs = self._native_params.get("n_jobs", n_jobs) super().__init__( objective=objective, eval_metric=eval_metric, early_stopping_rounds=early_stopping_rounds, validation_fraction=validation_fraction, random_state=random_state, n_jobs=n_jobs, verbose=verbose, scorecard_params=scorecard_params, **kwargs, ) # 早停相关参数 self.early_stopping_metric = early_stopping_metric self.first_metric_only = first_metric_only # LightGBM特有参数 self.num_leaves = num_leaves self.max_depth = max_depth self.learning_rate = learning_rate self.n_estimators = n_estimators self.min_child_samples = min_child_samples self.min_child_weight = min_child_weight self.subsample = subsample self.colsample_bytree = colsample_bytree self.reg_alpha = reg_alpha self.reg_lambda = reg_lambda self.scale_pos_weight = scale_pos_weight self.min_split_gain = min_split_gain self.boosting_type = boosting_type
[文档] @record_training def fit( self, X: Union[np.ndarray, pd.DataFrame], y: Optional[Union[np.ndarray, pd.Series]] = None, sample_weight: Optional[np.ndarray] = None, eval_set: Optional[List[Tuple]] = None, init_model=None, continue_training: bool = False, **fit_params, ) -> "LightGBM": """训练LightGBM模型. 支持两种调用方式: 1. 常规方式: fit(X, y) 2. scorecardpipeline风格: fit(X) 在init中指定target :param X: 特征矩阵 :type X: Union[np.ndarray, pd.DataFrame] :param y: 默认值为 ``None`` 。目标变量,可选 :type y: Optional[Union[np.ndarray, pd.Series]] :param sample_weight: 默认值为 ``None`` 。样本权重 :type sample_weight: Optional[np.ndarray] :param eval_set: 默认值为 ``None`` 。[(X_valid, y_valid)]、具名字典、DataFrame列表或单个数据集 同 ModelReport.datasets 的容器规则,含标签的 DataFrame 通过 target 提取标签。 :type eval_set: Optional[List[Tuple]] :param init_model: 已训练的同类 HSCredit/原生模型或后端支持的模型文件。 :param continue_training: True 基于当前已拟合模型追加训练;默认 False 重新训练。 n_estimators/iterations 表示本次追加轮数;不能与 init_model 同时使用。 :param fit_params: 其他fit参数 :return: self **参考样例** >>> from hscredit import get_metric >>> metric = get_metric('classification_cost', fn_cost=5, fp_cost=1) >>> _ = model.fit(X_train, y_train, eval_set={'验证': (X_valid, y_valid)}, eval_metric=metric) >>> final_values = model.get_eval_results() """ from ._continuation import prepare_continuation X, y, continuation = prepare_continuation(self, X, y, init_model, continue_training, fit_params, "init_model") fit_kwargs = dict(fit_params) self._validate_custom_loss_options() eval_metric = fit_kwargs.pop("eval_metric", self._native_params.get("eval_metric", self.eval_metric)) objective = self._native_params.get("objective", self.kwargs.get("objective", self.objective)) from ..losses._sample_params import bound_sample_params, slice_sample_loss, has_bound_sample_params original_objective = objective auto_loss_metric = eval_metric is None and isinstance(objective, BaseLoss) if auto_loss_metric and eval_set is not None and bound_sample_params(objective): raise ValueError("绑定逐行金融参数的损失使用外部 eval_set 时,请显式提供该数据集的 eval_metric;不能复用训练金额") if eval_metric is None and isinstance(objective, BaseLoss): eval_metric = objective.metric() early_stopping_rounds = fit_kwargs.pop("early_stopping_rounds", self._native_params.get("early_stopping_rounds", self.early_stopping_rounds)) fit_verbose = fit_kwargs.pop("verbose", self.verbose) # 准备数据(支持从X中提取target) X, y, sample_weight = self._prepare_data(X, y, sample_weight, extract_target=True, training=True) scorecard_sample_weight = sample_weight self._validate_probability_scorecard_labels(y) eval_set = self._prepare_eval_set(eval_set) if eval_set and len(eval_set) > 1 and has_bound_sample_params(eval_metric): raise ValueError("绑定逐行金融参数的 eval_metric 只能对应一个 eval_set,多个数据集不能共用同一金额数组") # 保存特征信息 self.n_features_in_ = X.shape[1] self.classes_ = np.unique(y) # 创建验证集 auto_eval_split = eval_set is None and self.validation_fraction > 0 and early_stopping_rounds is not None sw_val = None if auto_eval_split: X_train, X_val, y_train, y_val, sw_train, sw_val = self._create_eval_set(X, y, sample_weight) eval_set = [(X_val, y_val)] sample_weight = sw_train else: X_train, y_train = X, y if auto_eval_split: objective = slice_sample_loss(objective, self._eval_train_indices_, len(y)) eval_metric = slice_sample_loss(eval_metric, self._eval_val_indices_, len(y)) if objective is not original_objective: self.loss_sample_sizes_ = {"原始样本": len(y), "训练样本": len(y_train), "验证样本": len(y_val)} # 构建参数 params = { "num_leaves": self.num_leaves, "max_depth": self.max_depth, "learning_rate": self.learning_rate, "n_estimators": self.n_estimators, "min_child_samples": self.min_child_samples, "min_child_weight": self.min_child_weight, "subsample": self.subsample, "colsample_bytree": self.colsample_bytree, "reg_alpha": self.reg_alpha, "reg_lambda": self.reg_lambda, "scale_pos_weight": self.scale_pos_weight, "min_split_gain": self.min_split_gain, "boosting_type": self.boosting_type, "objective": self.objective, "n_jobs": self.n_jobs, "random_state": self.random_state, "verbose": -1 if not self.verbose else 1, } # 处理评估指标 requested = [] if eval_metric is None else ([eval_metric] if isinstance(eval_metric, str) or callable(eval_metric) else list(eval_metric)) if self.early_stopping_metric is not None: selected = self.early_stopping_metric matches = [item for item in requested if item == selected or isinstance(item, BaseMetric) and item.name == selected] if not matches and not any(callable(item) for item in requested): raise ValueError("early_stopping_metric 必须包含在 eval_metric 中") selected_item = matches[0] if matches else selected requested = [selected_item] + [item for item in requested if item is not selected_item and item != selected_item] native_metrics = [self._convert_metrics(item) for item in requested if isinstance(item, str) and item.lower() != "ks"] custom_metrics = [(item.to_lightgbm(api="sklearn", raw_score=callable(objective)) if isinstance(item, BaseMetric) else (_lightgbm_ks_metric if isinstance(item, str) and item.lower() == "ks" else item)) for item in requested if callable(item) or str(item).lower() == "ks"] if native_metrics or custom_metrics: params["metric"] = native_metrics or "None" if custom_metrics: fit_kwargs["eval_metric"] = custom_metrics[0] if len(custom_metrics) == 1 else custom_metrics # 更新kwargs参数 params.update(self.kwargs) # 最后更新原生params(优先级最高) params.update({key: value for key, value in self._native_params.items() if key not in {"eval_metric", "early_stopping_rounds", "callbacks"}}) init_callbacks = params.pop("callbacks", self._native_params.get("callbacks", None)) if init_callbacks: fit_kwargs["callbacks"] = list(init_callbacks) + list(fit_kwargs.get("callbacks", []) or []) params = self._resolve_native_aliases(params, self._parameter_aliases) # 解析自定义损失(BaseLoss 实例 -> sklearn 包装器可用的目标函数) params["objective"] = resolve_custom_objective(objective if objective is not original_objective else params.get("objective")) if LIGHTGBM_VERSION < Version("4.0") and callable(params["objective"]): custom_objective = params["objective"] if "sample_weight" in inspect.signature(custom_objective).parameters: # 3.x 将第三个参数解释为 group,并在回调后再乘权重; # 统一为当前 sample_weight 契约,并抵消原生的第二次加权。 objective_weights = None if sample_weight is None else np.asarray(sample_weight, dtype=float) def legacy_objective(labels, margin): gradient, hessian = custom_objective(labels, margin, sample_weight=objective_weights) if objective_weights is not None: gradient = np.divide( gradient, objective_weights, out=np.zeros_like(gradient, dtype=float), where=objective_weights != 0, ) hessian = np.divide( hessian, objective_weights, out=np.zeros_like(hessian, dtype=float), where=objective_weights != 0, ) return gradient, hessian params["objective"] = legacy_objective # 创建模型 self.native_params_ = dict(params) self._model = lgb.LGBMClassifier(**params) self._native_margin_output_ = False # 训练 if auto_eval_split: self._split_row_aligned_fit_param(fit_kwargs, "init_score", "eval_init_score") if sw_val is not None: fit_kwargs.setdefault("eval_sample_weight", [sw_val]) if eval_set: if "eval_X" in inspect.signature(self._model.fit).parameters: if fit_kwargs.get("eval_X") is not None or fit_kwargs.get("eval_y") is not None: raise ValueError("eval_set 与 eval_X、eval_y 不能同时传入") fit_kwargs["eval_X"], fit_kwargs["eval_y"] = zip(*eval_set) else: fit_kwargs["eval_set"] = eval_set if sample_weight is not None: fit_kwargs["sample_weight"] = sample_weight fit_api = _lightgbm_fit_api(LIGHTGBM_VERSION) if fit_api == "legacy": # LightGBM < 3.3.0:无回调 API,使用 fit 的 verbose / early_stopping_rounds 参数 fit_kwargs["verbose"] = fit_verbose if early_stopping_rounds is not None and eval_set: fit_kwargs["early_stopping_rounds"] = early_stopping_rounds else: # LightGBM >= 3.3.0:用 callbacks API,避免 verbose / early_stopping_rounds 弃用告警 user_callbacks = fit_kwargs.pop("callbacks", None) if user_callbacks is None: callbacks: List[Any] = [] elif isinstance(user_callbacks, (list, tuple)): callbacks = list(user_callbacks) else: callbacks = [user_callbacks] if early_stopping_rounds is not None and eval_set: stopping_callback = lgb.early_stopping( stopping_rounds=early_stopping_rounds, first_metric_only=self.first_metric_only or self.early_stopping_metric is not None, verbose=fit_verbose, ) selected_metric = self.early_stopping_metric if selected_metric is None and self.first_metric_only and requested: first_metric = requested[0] if isinstance(first_metric, BaseMetric): selected_metric = first_metric.name elif isinstance(first_metric, str): selected_metric = first_metric if selected_metric is not None: stopping_callback = _SelectedMetricEarlyStopping(stopping_callback, self._convert_metrics(selected_metric)) callbacks.append(stopping_callback) if fit_verbose: callbacks.append(lgb.log_evaluation(period=1)) if callbacks: fit_kwargs["callbacks"] = callbacks if continuation is not None: fit_kwargs["init_model"] = continuation self._model.fit(X_train, y_train, **fit_kwargs) # 保存结果 self._best_iteration = getattr(self._model, "best_iteration_", None) self._best_score = getattr(self._model, "best_score_", None) self._evals_result = getattr(self._model, "evals_result_", None) or {} self._is_fitted = True self._fit_probability_scorecard(X, y, sample_weight=scorecard_sample_weight) from .._workflow import record_boosting_evaluation record_boosting_evaluation(self, eval_set, eval_metric=eval_metric, weights=fit_kwargs.get("eval_sample_weight")) return self
[文档] def predict(self, X: Union[np.ndarray, pd.DataFrame], **predict_params) -> np.ndarray: """预测类别标签. 基于 predict_proba 取阈值,确保自定义损失(原始分数输出)下也能返回正确类别。 :param X: 待预测的二维特征数据;字段名称、顺序及预处理方式应与训练输入一致。 """ self._require_fitted() if any(predict_params.get(name) for name in ("raw_score", "pred_leaf", "pred_contrib")): return self._model.predict(self._prepare_data(X)[0], **predict_params) proba = self.predict_proba(X, **predict_params) indices = np.argmax(proba, axis=1) return np.asarray(self.classes_)[indices]
[文档] def predict_proba(self, X: Union[np.ndarray, pd.DataFrame], **predict_params) -> np.ndarray: """预测概率. 自定义损失函数下显式向 LightGBM 请求原始分数,再使用稳定的 sigmoid 转换为两列概率,避免原生接口无法直接计算自定义目标概率的警告。 :param X: 特征矩阵。 :type X: Union[np.ndarray, pd.DataFrame] :param predict_params: LightGBM 原生预测参数,例如 ``num_iteration`` 。 显式设置 ``raw_score=True`` 、 ``pred_leaf=True`` 或 ``pred_contrib=True`` 时返回对应原生结果,不转换为概率。 :return: 默认返回形状为 ``(n_samples, 2)`` 的类别概率,列顺序为 ``classes_`` 。 **参考样例** >>> probability = model.predict_proba(X_test)[:, 1] >>> raw_margin = model.predict_proba(X_test, raw_score=True) """ self._require_fitted() X = self._prepare_data(X)[0] if isinstance(X, np.ndarray) and hasattr(self._model, "feature_name_"): X = pd.DataFrame(X, columns=list(self._model.feature_name_)) native_output_requested = any(predict_params.get(name) for name in ("raw_score", "pred_leaf", "pred_contrib")) if getattr(self, "_native_margin_output_", False): proba = self._model.booster_.predict(X, **predict_params) else: native_predict_params = dict(predict_params) if (callable(getattr(self._model, "_objective", None)) or callable(getattr(self._model, "objective", None))) and not native_output_requested: native_predict_params["raw_score"] = True proba = self._model.predict_proba(X, **native_predict_params) proba = np.asarray(proba) if native_output_requested: return proba # 自定义损失返回一维原始分数,应用 sigmoid 并补齐为两列概率 if proba.ndim == 1: p1 = expit(proba) proba = np.column_stack([1.0 - p1, p1]) return proba
[文档] def get_feature_importances(self, importance_type: str = "gain") -> pd.Series: """获取特征重要性. :param importance_type: 重要性类型,可选: - 'gain': 平均增益 (默认) - 'split': 分裂次数 :type importance_type: str :return: 特征重要性Series """ self._require_fitted() importances = self._model.booster_.feature_importance(importance_type=importance_type) # 创建Series importance_series = pd.Series(importances, index=self.feature_names_in_, name="importance").sort_values(ascending=False) self._feature_importances = importance_series return importance_series
@property def feature_importances_(self) -> np.ndarray: """特征重要性属性 (兼容sklearn风格). 直接在包装类上暴露重要性,兼容sklearn RFE/SFS等组件的 importance_getter。 """ self._require_fitted() return np.asarray(self._model.feature_importances_)
[文档] def get_booster(self) -> "lgb.Booster": """获取底层LightGBM booster对象. :return: LightGBM Booster对象 """ self._require_fitted() return self._model.booster_
[文档] def plot_tree(self, tree_index: int = 0, **kwargs): """绘制树结构. :param tree_index: 默认值为 ``0`` 。树的索引 :type tree_index: int :param kwargs: 其他绘图参数 """ self._require_fitted() return lgb.plot_tree(self._model, tree_index=tree_index, **kwargs)
[文档] def plot_importance(self, max_num_features: int = 10, **kwargs): """绘制特征重要性. :param max_num_features: 默认值为 ``10`` 。显示的最大特征数 :type max_num_features: int :param kwargs: 其他绘图参数 """ self._require_fitted() return lgb.plot_importance(self._model, max_num_features=max_num_features, **kwargs)
[文档] def get_leaf_indices(self, X: Union[np.ndarray, pd.DataFrame]) -> np.ndarray: """获取叶子节点索引. 返回每棵树上的叶子节点索引,用于GBDT+LR等场景。 :param X: 特征矩阵 :type X: Union[np.ndarray, pd.DataFrame] :return: 叶子节点索引,形状 (n_samples, n_trees) **参考样例** >>> model = LightGBM(n_estimators=50) >>> model.fit(X, y) >>> leaf_indices = model.get_leaf_indices(X) >>> print(leaf_indices.shape) """ self._require_fitted() X = self._prepare_data(X)[0] return self._model.predict(X, pred_leaf=True)
def _convert_metrics(self, metrics: Union[str, List[str]]) -> Union[str, List[str]]: """转换评估指标名称. :param metrics: 指标名称或列表 :return: LightGBM格式的指标名称 """ metric_map = { "auc": "auc", "logloss": "binary_logloss", "error": "binary_error", "rmse": "rmse", "mae": "mae", "map": "map", } if isinstance(metrics, str): return metric_map.get(metrics.lower(), metrics) return [metric_map.get(m.lower(), m) for m in metrics]
[文档] def save_model(self, path: str): """保存底层LightGBM模型(原生格式). :param path: 保存路径(.txt/.bin 格式) :type path: str """ self._require_fitted() self._model.booster_.save_model(path) self._save_score_transformer_sidecar(path)
[文档] def load_model(self, path: str) -> "LightGBM": """加载底层LightGBM模型(原生格式). :param path: 模型路径 :type path: str :return: self """ booster = lgb.Booster(model_file=path) self._model = lgb.LGBMClassifier() self._model._Booster = booster self._model.fitted_ = True self._model._n_features = booster.num_feature() self._model._n_features_in = booster.num_feature() self._model._classes = np.asarray([0, 1]) self._model._n_classes = 2 self._is_fitted = True self.classes_ = np.array([0, 1]) self.feature_names_in_ = booster.feature_name() self._feature_names_known_ = True self.n_features_in_ = booster.num_feature() self._load_score_transformer_sidecar(path) objective = getattr(self, "native_params_", {}).get("objective", booster.params.get("objective")) self._native_margin_output_ = callable(objective) or objective in ("custom", "none") return self