跳转至

Modeling_Tool.WOE

WOE 编码层 —— 主控类、转换器、绘图器、贪心单调分箱器。

主控类 — WOE_Master

WOE_Master

WOE_Master

Bases: object

WOE Master class for WOE fitting, transformation, adjustment and plotting.

This class provides a complete WOE encoding workflow including: - Fitting WOE bins from data - Loading existing WOE mapping tables - Transforming new data with WOE - Updating and adjusting WOE bins - Plotting bivariate WOE comparison charts

Attributes: train_data: pandas.DataFrame, training dataset varlist: list, variable names for WOE transformation dep: str, target variable name graph_save_dir: str, directory for saving graphs woe_suffix: str, suffix for WOE variable names missing_ref_value: int/float, reference value for missing data woe_dict: dict, WOE mapping dictionary

源代码位于: Modeling_Tool/WOE/WOE_Master.py
class WOE_Master(object):
    """WOE Master class for WOE fitting, transformation, adjustment and plotting.

    This class provides a complete WOE encoding workflow including:
    - Fitting WOE bins from data
    - Loading existing WOE mapping tables
    - Transforming new data with WOE
    - Updating and adjusting WOE bins
    - Plotting bivariate WOE comparison charts

    Attributes:
        train_data: pandas.DataFrame, training dataset
        varlist: list, variable names for WOE transformation
        dep: str, target variable name
        graph_save_dir: str, directory for saving graphs
        woe_suffix: str, suffix for WOE variable names
        missing_ref_value: int/float, reference value for missing data
        woe_dict: dict, WOE mapping dictionary
    """

    def __init__(self, train_data, varlist, dep=None, graph_save_dir="", woe_suffix="_woe", missing_ref_value=-999999, remove_exist_dir = False):
        """Initialize WOE_Master instance.

        Args:
            train_data: pandas.DataFrame, training dataset with features and target
            varlist: list, variables to perform WOE transformation
            dep: str, target variable name
            graph_save_dir: str, directory to save graphs
            woe_suffix: str, suffix for WOE variable names
            missing_ref_value: int/float, reference value for missing values
        """
        self.train_data = train_data
        self.varlist = varlist
        self.dep = dep
        self.graph_save_dir = graph_save_dir
        self.woe_suffix = woe_suffix
        self.missing_ref_value = missing_ref_value
        self.woe_dict = {}

        if remove_exist_dir:
            self.remove_folder(graph_save_dir)

    @staticmethod
    def remove_folder(file_path):
        """删除指定文件夹。

        递归删除指定路径的文件夹及其所有内容,
        如果文件夹不存在则静默处理。

        Parameters
        ----------
        file_path : str
            要删除的文件夹路径

        Examples
        --------
        >>> VarExtractionInsights.remove_folder('/path/to/folder')
        """
        import shutil
        try:
            shutil.rmtree(file_path)
        except Exception:
            pass

    def load_mapping_table(self, mapping_table_csv):
        """Load WOE mapping table from CSV file or DataFrame.

        Args:
            mapping_table_csv: str or pandas.DataFrame, path to CSV or DataFrame object
        Returns:
            None, updates self.woe_dict and self.varlist attributes
        Raises:
            AttributeError: if input is neither string path nor DataFrame
        """
        if isinstance(mapping_table_csv, str):
            woe_mapping_table = pd.read_csv(mapping_table_csv)
        elif isinstance(mapping_table_csv, pd.DataFrame):
            woe_mapping_table = mapping_table_csv
        else:
            raise AttributeError("Please give either CSV path or Pandas DataFrame as an input! ")

        varlist = woe_mapping_table['VAR'].unique().tolist()

        woe_dict = {}
        for var in varlist:
            single_var_woe = woe_mapping_table.query(f"VAR == '{var}'")
            woe_dict[var] = single_var_woe

        self.woe_dict = woe_dict
        self.varlist = varlist

    def fit(self, nbins=10, equal_freq=True, tree_binning_seed=None, chi2_config=None,
            precision=5, min_bin_prop=0.05, include_missing=True, fillna=None, spec_values=[]):
        """Fit WOE binning for variables in varlist.

        Args:
            nbins: int, number of bins (default 10)
            equal_freq: bool, use equal frequency binning (default True)
            tree_binning_seed: int, random seed for tree-based binning
            chi2_config: dict, chi-square binning configuration
            precision: int, numerical precision (default 5)
            min_bin_prop: float, minimum bin proportion (default 0.05)
            include_missing: bool, include missing value bin (default True)
            fillna: int/float, value to fill missing data
            spec_values: list, special values to handle
        Returns:
            None, updates self.woe_dict attribute
        """
        if fillna is None:
            fillna = self.missing_ref_value

        for var in self.varlist:
            woe_res = woe_transform(train_df=self.train_data,
                                    oot_df=None,
                                    var=var,
                                    dep=self.dep,
                                    nbins=nbins,
                                    chi2_config=chi2_config,
                                    tree_binning_seed=tree_binning_seed,
                                    precision=precision,
                                    min_bin_prop=min_bin_prop,
                                    include_missing=include_missing,
                                    equal_freq=equal_freq,
                                    ascending=True,
                                    fillna=fillna,
                                    spec_values=spec_values,
                                    drop_bin_info=True,
                                    ret_woe_table=True)
            woe_table = woe_res[-1]
            woe_table["VAR"] = var
            woe_table = woe_table.rename(columns={f"_bin_num_{var}": "BIN_NUM", f"_bin_range_{var}": "BIN_RANGE"})
            self.woe_dict[var] = woe_table

    def get_mapping_table(self):
        """Get WOE mapping table for all variables.

        Returns:
            pandas.DataFrame with WOE mapping information for all variables
        """
        return pd.concat([v for k, v in self.woe_dict.items()])

    def save_mapping_table(self, save_dir):
        """Save WOE mapping table as CSV file.

        Args:
            save_dir: str, path to save the CSV file
        Returns:
            None, saves file directly
        """
        mapping_table = self.get_mapping_table()
        mapping_table.to_csv(save_dir, index=False)

    def transform(self, data=None, varlist=None):
        """Transform data using WOE encoding.

        Args:
            data: pandas.DataFrame, data to transform (default: train_data)
            varlist: list, variables to transform (default: self.varlist)
        Returns:
            pandas.DataFrame with WOE transformed data
        """
        if data is None:
            data = self.train_data
        if varlist is None:
            varlist = self.varlist

        woe_mapping_table = self.get_mapping_table()
        data_woe = mapping_woe(data, varlist, woe_mapping_table, suffix=self.woe_suffix, drop_bin_info=True)
        return data_woe

    def update_woe(self, varlist, nbins=10, equal_freq=True, tree_binning_seed=None, chi2_config=None,
                   precision=5, min_bin_prop=0.05, include_missing=True, fillna=None, spec_values=[]):
        """Update WOE binning for specified variables.

        Args:
            varlist: list, variables to update WOE for
            nbins: int, number of bins (default 10)
            equal_freq: bool, use equal frequency binning (default True)
            tree_binning_seed: int, random seed for tree-based binning
            chi2_config: dict, chi-square binning configuration
            precision: int, numerical precision (default 5)
            min_bin_prop: float, minimum bin proportion (default 0.05)
            include_missing: bool, include missing value bin (default True)
            fillna: int/float, value to fill missing data
            spec_values: list, special values to handle
        Returns:
            None, updates self.woe_dict attribute
        """
        if fillna is None:
            fillna = self.missing_ref_value

        new_woe_dict = {}
        for var in varlist:
            woe_res = woe_transform(train_df=self.train_data,
                                    oot_df=None,
                                    var=var,
                                    dep=self.dep,
                                    nbins=nbins,
                                    chi2_config=chi2_config,
                                    tree_binning_seed=tree_binning_seed,
                                    precision=precision,
                                    min_bin_prop=min_bin_prop,
                                    include_missing=include_missing,
                                    equal_freq=equal_freq,
                                    ascending=True,
                                    fillna=fillna,
                                    spec_values=spec_values,
                                    drop_bin_info=True,
                                    ret_woe_table=True)
            woe_table = woe_res[-1]
            woe_table["VAR"] = var
            woe_table = woe_table.rename(columns={f"_bin_num_{var}": "BIN_NUM", f"_bin_range_{var}": "BIN_RANGE"})
            new_woe_dict[var] = woe_table

        self.woe_dict.update(new_woe_dict)

    def plot_bivar_graph(self, data, group, dirname, varlist=None):
        """Plot bivariate WOE comparison graph.

        Args:
            data: pandas.DataFrame, data for plotting
            group: str, grouping variable name for distinguishing curves
            dirname: str, subdirectory name for saving (under graph_save_dir)
            varlist: list, variables to plot (default: self.varlist)
        Returns:
            None, saves images directly
        """
        if varlist is None:
            varlist = self.varlist

        get_bivar_graph(data=data,
                        varlist=varlist,
                        sep=self.dep,
                        ref_woe_table=self.get_mapping_table(),
                        group=group,
                        save_dir=os.path.join(self.graph_save_dir, dirname))

remove_folder staticmethod

remove_folder(file_path)

删除指定文件夹。

递归删除指定路径的文件夹及其所有内容, 如果文件夹不存在则静默处理。

参数:

名称 类型 描述 默认
file_path str

要删除的文件夹路径

必需

示例:

>>> VarExtractionInsights.remove_folder('/path/to/folder')
源代码位于: Modeling_Tool/WOE/WOE_Master.py
@staticmethod
def remove_folder(file_path):
    """删除指定文件夹。

    递归删除指定路径的文件夹及其所有内容,
    如果文件夹不存在则静默处理。

    Parameters
    ----------
    file_path : str
        要删除的文件夹路径

    Examples
    --------
    >>> VarExtractionInsights.remove_folder('/path/to/folder')
    """
    import shutil
    try:
        shutil.rmtree(file_path)
    except Exception:
        pass

load_mapping_table

load_mapping_table(mapping_table_csv)

Load WOE mapping table from CSV file or DataFrame.

Args: mapping_table_csv: str or pandas.DataFrame, path to CSV or DataFrame object Returns: None, updates self.woe_dict and self.varlist attributes Raises: AttributeError: if input is neither string path nor DataFrame

源代码位于: Modeling_Tool/WOE/WOE_Master.py
def load_mapping_table(self, mapping_table_csv):
    """Load WOE mapping table from CSV file or DataFrame.

    Args:
        mapping_table_csv: str or pandas.DataFrame, path to CSV or DataFrame object
    Returns:
        None, updates self.woe_dict and self.varlist attributes
    Raises:
        AttributeError: if input is neither string path nor DataFrame
    """
    if isinstance(mapping_table_csv, str):
        woe_mapping_table = pd.read_csv(mapping_table_csv)
    elif isinstance(mapping_table_csv, pd.DataFrame):
        woe_mapping_table = mapping_table_csv
    else:
        raise AttributeError("Please give either CSV path or Pandas DataFrame as an input! ")

    varlist = woe_mapping_table['VAR'].unique().tolist()

    woe_dict = {}
    for var in varlist:
        single_var_woe = woe_mapping_table.query(f"VAR == '{var}'")
        woe_dict[var] = single_var_woe

    self.woe_dict = woe_dict
    self.varlist = varlist

fit

fit(nbins=10, equal_freq=True, tree_binning_seed=None, chi2_config=None, precision=5, min_bin_prop=0.05, include_missing=True, fillna=None, spec_values=[])

Fit WOE binning for variables in varlist.

Args: nbins: int, number of bins (default 10) equal_freq: bool, use equal frequency binning (default True) tree_binning_seed: int, random seed for tree-based binning chi2_config: dict, chi-square binning configuration precision: int, numerical precision (default 5) min_bin_prop: float, minimum bin proportion (default 0.05) include_missing: bool, include missing value bin (default True) fillna: int/float, value to fill missing data spec_values: list, special values to handle Returns: None, updates self.woe_dict attribute

源代码位于: Modeling_Tool/WOE/WOE_Master.py
def fit(self, nbins=10, equal_freq=True, tree_binning_seed=None, chi2_config=None,
        precision=5, min_bin_prop=0.05, include_missing=True, fillna=None, spec_values=[]):
    """Fit WOE binning for variables in varlist.

    Args:
        nbins: int, number of bins (default 10)
        equal_freq: bool, use equal frequency binning (default True)
        tree_binning_seed: int, random seed for tree-based binning
        chi2_config: dict, chi-square binning configuration
        precision: int, numerical precision (default 5)
        min_bin_prop: float, minimum bin proportion (default 0.05)
        include_missing: bool, include missing value bin (default True)
        fillna: int/float, value to fill missing data
        spec_values: list, special values to handle
    Returns:
        None, updates self.woe_dict attribute
    """
    if fillna is None:
        fillna = self.missing_ref_value

    for var in self.varlist:
        woe_res = woe_transform(train_df=self.train_data,
                                oot_df=None,
                                var=var,
                                dep=self.dep,
                                nbins=nbins,
                                chi2_config=chi2_config,
                                tree_binning_seed=tree_binning_seed,
                                precision=precision,
                                min_bin_prop=min_bin_prop,
                                include_missing=include_missing,
                                equal_freq=equal_freq,
                                ascending=True,
                                fillna=fillna,
                                spec_values=spec_values,
                                drop_bin_info=True,
                                ret_woe_table=True)
        woe_table = woe_res[-1]
        woe_table["VAR"] = var
        woe_table = woe_table.rename(columns={f"_bin_num_{var}": "BIN_NUM", f"_bin_range_{var}": "BIN_RANGE"})
        self.woe_dict[var] = woe_table

get_mapping_table

get_mapping_table()

Get WOE mapping table for all variables.

Returns: pandas.DataFrame with WOE mapping information for all variables

源代码位于: Modeling_Tool/WOE/WOE_Master.py
def get_mapping_table(self):
    """Get WOE mapping table for all variables.

    Returns:
        pandas.DataFrame with WOE mapping information for all variables
    """
    return pd.concat([v for k, v in self.woe_dict.items()])

save_mapping_table

save_mapping_table(save_dir)

Save WOE mapping table as CSV file.

Args: save_dir: str, path to save the CSV file Returns: None, saves file directly

源代码位于: Modeling_Tool/WOE/WOE_Master.py
def save_mapping_table(self, save_dir):
    """Save WOE mapping table as CSV file.

    Args:
        save_dir: str, path to save the CSV file
    Returns:
        None, saves file directly
    """
    mapping_table = self.get_mapping_table()
    mapping_table.to_csv(save_dir, index=False)

transform

transform(data=None, varlist=None)

Transform data using WOE encoding.

Args: data: pandas.DataFrame, data to transform (default: train_data) varlist: list, variables to transform (default: self.varlist) Returns: pandas.DataFrame with WOE transformed data

源代码位于: Modeling_Tool/WOE/WOE_Master.py
def transform(self, data=None, varlist=None):
    """Transform data using WOE encoding.

    Args:
        data: pandas.DataFrame, data to transform (default: train_data)
        varlist: list, variables to transform (default: self.varlist)
    Returns:
        pandas.DataFrame with WOE transformed data
    """
    if data is None:
        data = self.train_data
    if varlist is None:
        varlist = self.varlist

    woe_mapping_table = self.get_mapping_table()
    data_woe = mapping_woe(data, varlist, woe_mapping_table, suffix=self.woe_suffix, drop_bin_info=True)
    return data_woe

update_woe

update_woe(varlist, nbins=10, equal_freq=True, tree_binning_seed=None, chi2_config=None, precision=5, min_bin_prop=0.05, include_missing=True, fillna=None, spec_values=[])

Update WOE binning for specified variables.

Args: varlist: list, variables to update WOE for nbins: int, number of bins (default 10) equal_freq: bool, use equal frequency binning (default True) tree_binning_seed: int, random seed for tree-based binning chi2_config: dict, chi-square binning configuration precision: int, numerical precision (default 5) min_bin_prop: float, minimum bin proportion (default 0.05) include_missing: bool, include missing value bin (default True) fillna: int/float, value to fill missing data spec_values: list, special values to handle Returns: None, updates self.woe_dict attribute

源代码位于: Modeling_Tool/WOE/WOE_Master.py
def update_woe(self, varlist, nbins=10, equal_freq=True, tree_binning_seed=None, chi2_config=None,
               precision=5, min_bin_prop=0.05, include_missing=True, fillna=None, spec_values=[]):
    """Update WOE binning for specified variables.

    Args:
        varlist: list, variables to update WOE for
        nbins: int, number of bins (default 10)
        equal_freq: bool, use equal frequency binning (default True)
        tree_binning_seed: int, random seed for tree-based binning
        chi2_config: dict, chi-square binning configuration
        precision: int, numerical precision (default 5)
        min_bin_prop: float, minimum bin proportion (default 0.05)
        include_missing: bool, include missing value bin (default True)
        fillna: int/float, value to fill missing data
        spec_values: list, special values to handle
    Returns:
        None, updates self.woe_dict attribute
    """
    if fillna is None:
        fillna = self.missing_ref_value

    new_woe_dict = {}
    for var in varlist:
        woe_res = woe_transform(train_df=self.train_data,
                                oot_df=None,
                                var=var,
                                dep=self.dep,
                                nbins=nbins,
                                chi2_config=chi2_config,
                                tree_binning_seed=tree_binning_seed,
                                precision=precision,
                                min_bin_prop=min_bin_prop,
                                include_missing=include_missing,
                                equal_freq=equal_freq,
                                ascending=True,
                                fillna=fillna,
                                spec_values=spec_values,
                                drop_bin_info=True,
                                ret_woe_table=True)
        woe_table = woe_res[-1]
        woe_table["VAR"] = var
        woe_table = woe_table.rename(columns={f"_bin_num_{var}": "BIN_NUM", f"_bin_range_{var}": "BIN_RANGE"})
        new_woe_dict[var] = woe_table

    self.woe_dict.update(new_woe_dict)

plot_bivar_graph

plot_bivar_graph(data, group, dirname, varlist=None)

Plot bivariate WOE comparison graph.

Args: data: pandas.DataFrame, data for plotting group: str, grouping variable name for distinguishing curves dirname: str, subdirectory name for saving (under graph_save_dir) varlist: list, variables to plot (default: self.varlist) Returns: None, saves images directly

源代码位于: Modeling_Tool/WOE/WOE_Master.py
def plot_bivar_graph(self, data, group, dirname, varlist=None):
    """Plot bivariate WOE comparison graph.

    Args:
        data: pandas.DataFrame, data for plotting
        group: str, grouping variable name for distinguishing curves
        dirname: str, subdirectory name for saving (under graph_save_dir)
        varlist: list, variables to plot (default: self.varlist)
    Returns:
        None, saves images directly
    """
    if varlist is None:
        varlist = self.varlist

    get_bivar_graph(data=data,
                    varlist=varlist,
                    sep=self.dep,
                    ref_woe_table=self.get_mapping_table(),
                    group=group,
                    save_dir=os.path.join(self.graph_save_dir, dirname))

get_overall_woe_table

get_overall_woe_table(woe_master, data, varlist=None)

生成整体样本的WOE统计表,结构对齐训练集映射表。

源代码位于: Modeling_Tool/WOE/WOE_Master.py
def get_overall_woe_table(woe_master, data, varlist=None):
    """生成整体样本的WOE统计表,结构对齐训练集映射表。"""
    if varlist is None:
        varlist = woe_master.varlist

    all_tables = []
    for var in varlist:
        var_map = woe_master.woe_dict[var]

        # 提取分箱边界并保留 inf
        edges = get_bin_range_list(var_map, col="BIN_RANGE")
        custom_edges = sorted(set(list(edges) + [-np.inf, np.inf]))

        # 从训练集 BIN_RANGE 推断闭合方式
        first_bin = var_map["BIN_RANGE"].dropna().iloc[0]
        include_lowest = first_bin[0] == '['
        right = first_bin[-1] == ']'

        fill_val = woe_master.missing_ref_value
        data_proc = data.copy()
        data_proc[var] = data_proc[var].fillna(fill_val)

        # 使用训练集边界分箱
        binned, _ = run_binning(
            data=data_proc,
            column=var,
            nbins=custom_edges,
            include_missing=True,
            equal_freq=False,
            bin_colnames=("_BIN_NUM", "_BIN_RANGE"),
            ascending=True,
            include_lowest=include_lowest,
            right=right,
            spec_values=[fill_val]
        )

        dep = woe_master.dep
        grp = binned.groupby(["_BIN_NUM", "_BIN_RANGE"], dropna=False)
        stats = grp.agg(
            MIN=(var, "min"),
            MAX=(var, "max"),
            N=(var, "count"),
            AVG_BAD=(dep, "mean"),
            N_BAD=(dep, "sum"),
            N_GOOD=(dep, lambda x: (x == 0).sum())
        ).reset_index()

        # 计算 WOE / IV / LIFT
        stats["BAD_PCT_PER_BIN"] = stats["N_BAD"] / stats["N_BAD"].sum()
        stats["GOOD_PCT_PER_BIN"] = stats["N_GOOD"] / stats["N_GOOD"].sum()
        stats["WOE"] = calc_woe(stats, bad_pct="BAD_PCT_PER_BIN", good_pct="GOOD_PCT_PER_BIN")
        stats["IV"] = calc_iv(stats, bad_pct="BAD_PCT_PER_BIN", good_pct="GOOD_PCT_PER_BIN")
        stats["LIFT"] = stats["AVG_BAD"] / stats["AVG_BAD"].mean()
        stats["VAR"] = var

        stats = stats.rename(columns={"_BIN_NUM": "BIN_NUM", "_BIN_RANGE": "BIN_RANGE"})

        cols = ["VAR", "BIN_NUM", "BIN_RANGE", "MIN", "MAX", "N",
                "AVG_BAD", "WOE", "IV", "N_BAD", "N_GOOD",
                "BAD_PCT_PER_BIN", "GOOD_PCT_PER_BIN", "LIFT"]
        stats = stats[cols]
        all_tables.append(stats)

    return pd.concat(all_tables, ignore_index=True)

get_group_woe_table

get_group_woe_table(woe_master, data, group, varlist=None)

生成分组样本的WOE汇总、透视和详细表。

源代码位于: Modeling_Tool/WOE/WOE_Master.py
def get_group_woe_table(woe_master, data, group, varlist=None):
    """生成分组样本的WOE汇总、透视和详细表。"""
    if varlist is None:
        varlist = woe_master.varlist

    summaries = []
    pivots_woe = []
    pivots_bad = []
    detail_list = []

    for var in varlist:
        var_map = woe_master.woe_dict[var]
        edges = get_bin_range_list(var_map, col="BIN_RANGE")
        custom_edges = sorted(set(list(edges) + [-np.inf, np.inf]))
        first_bin = var_map["BIN_RANGE"].dropna().iloc[0]
        include_lowest = first_bin[0] == '['
        right = first_bin[-1] == ']'
        fill_val = woe_master.missing_ref_value

        data_proc = data.copy()
        data_proc[var] = data_proc[var].fillna(fill_val)

        binned, _ = run_binning(
            data=data_proc,
            column=var,
            nbins=custom_edges,
            include_missing=True,
            equal_freq=False,
            bin_colnames=("_BIN_NUM", "_BIN_RANGE"),
            ascending=True,
            include_lowest=include_lowest,
            right=right,
            spec_values=[fill_val]
        )

        dep = woe_master.dep
        # 按分箱与分组双重聚合
        grp = binned.groupby([group, "_BIN_NUM", "_BIN_RANGE"], dropna=False)
        stats = grp.agg(
            MIN=(var, "min"),
            MAX=(var, "max"),
            N=(var, "count"),
            AVG_BAD=(dep, "mean"),
            N_BAD=(dep, "sum"),
            N_GOOD=(dep, lambda x: (x == 0).sum())
        ).reset_index()

        # 计算各分箱内 WOE(全局分母)
        total_bad = stats["N_BAD"].sum()
        total_good = stats["N_GOOD"].sum()
        stats["BAD_PCT_PER_BIN"] = stats["N_BAD"] / total_bad
        stats["GOOD_PCT_PER_BIN"] = stats["N_GOOD"] / total_good
        stats["WOE"] = calc_woe(stats, bad_pct="BAD_PCT_PER_BIN", good_pct="GOOD_PCT_PER_BIN")
        stats["IV"] = calc_iv(stats, bad_pct="BAD_PCT_PER_BIN", good_pct="GOOD_PCT_PER_BIN")
        stats["LIFT"] = stats["AVG_BAD"] / stats["AVG_BAD"].mean()
        stats["VAR"] = var

        # 生成透视表:WOE 和 AVG_BAD 在不同分组下的值
        pvt_woe = stats.pivot_table(index=["_BIN_NUM", "_BIN_RANGE"], columns=group, values="WOE")
        pvt_bad = stats.pivot_table(index=["_BIN_NUM", "_BIN_RANGE"], columns=group, values="AVG_BAD")

        # 汇总各分组的总指标
        sum_grp = stats.groupby(group).agg(
            N=("N", "sum"),
            IV=("IV", "sum"),
            KS_PER_BIN=("LIFT", "max"),  # 简化处理,可进一步细算
            TOP_LIFT=("LIFT", "max"),
            BTM_LIFT=("LIFT", "min")
        ).reset_index()

        # 计算单调性斜率(可选)
        from Modeling_Tool.Core.Slope_Tool import calculate_slope_manual
        slopes = stats.groupby(group).apply(lambda x: calculate_slope_manual(x, "AVG_BAD"))
        sum_grp["SLOPE"] = sum_grp[group].map(slopes)
        sum_grp["direction"] = sum_grp["SLOPE"].apply(lambda x: 1 if x > 0 else -1 if x < 0 else 0)
        sum_grp["VAR"] = var

        summaries.append(sum_grp)
        pivots_woe.append(pvt_woe)
        pivots_bad.append(pvt_bad)
        detail_list.append(stats)

    final_pivot = pd.concat(pivots_woe, keys=varlist, names=["VAR", "BIN_NUM", "BIN_RANGE"])
    # 如需同时返回 AVG_BAD 透视表,可以合并或单独返回
    return {
        "summary": pd.concat(summaries, ignore_index=True),
        "pivot": final_pivot,
        "detail": pd.concat(detail_list, ignore_index=True)
    }

load_mapping_table

load_mapping_table(mapping_table_csv)

Load WOE mapping table from CSV or DataFrame.

Args: mapping_table_csv: str or pandas.DataFrame, path to CSV or DataFrame Returns: tuple: (varlist, woe_dict) Raises: AttributeError: if input is neither string path nor DataFrame

源代码位于: Modeling_Tool/WOE/WOE_Master.py
def load_mapping_table(mapping_table_csv):
    """Load WOE mapping table from CSV or DataFrame.

    Args:
        mapping_table_csv: str or pandas.DataFrame, path to CSV or DataFrame
    Returns:
        tuple: (varlist, woe_dict)
    Raises:
        AttributeError: if input is neither string path nor DataFrame
    """
    if isinstance(mapping_table_csv, str):
        woe_mapping_table = pd.read_csv(mapping_table_csv)
    elif isinstance(mapping_table_csv, pd.DataFrame):
        woe_mapping_table = mapping_table_csv
    else:
        raise AttributeError("Please give either CSV path or Pandas DataFrame as an input! ")

    varlist = woe_mapping_table['VAR'].unique().tolist()
    woe_dict = {}
    for var in varlist:
        single_var_woe = woe_mapping_table.query(f"VAR == '{var}'")
        woe_dict[var] = single_var_woe
    return varlist, woe_dict

get_mapping_table

get_mapping_table(woe_dict)

Get combined mapping table from WOE dictionary.

Args: woe_dict: dict, WOE mapping dictionary Returns: pandas.DataFrame with WOE mapping information

源代码位于: Modeling_Tool/WOE/WOE_Master.py
def get_mapping_table(woe_dict):
    """Get combined mapping table from WOE dictionary.

    Args:
        woe_dict: dict, WOE mapping dictionary
    Returns:
        pandas.DataFrame with WOE mapping information
    """
    return pd.concat([v for k, v in woe_dict.items()])

save_mapping_table

save_mapping_table(woe_dict, save_dir)

Save WOE dictionary as CSV file.

Args: woe_dict: dict, WOE mapping dictionary save_dir: str, path to save the CSV file Returns: None, saves file directly

源代码位于: Modeling_Tool/WOE/WOE_Master.py
def save_mapping_table(woe_dict, save_dir):
    """Save WOE dictionary as CSV file.

    Args:
        woe_dict: dict, WOE mapping dictionary
        save_dir: str, path to save the CSV file
    Returns:
        None, saves file directly
    """
    mapping_table = get_mapping_table(woe_dict)
    mapping_table.to_csv(save_dir, index=False)

transform

transform(data, varlist, woe_mapping_table, woe_suffix='_woe')

Transform data using WOE encoding.

Args: data: pandas.DataFrame, data to transform varlist: list, variables to transform woe_mapping_table: pandas.DataFrame, WOE mapping table woe_suffix: str, suffix for WOE variable names (default "_woe") Returns: pandas.DataFrame with WOE transformed data

源代码位于: Modeling_Tool/WOE/WOE_Master.py
def transform(data, varlist, woe_mapping_table, woe_suffix="_woe"):
    """Transform data using WOE encoding.

    Args:
        data: pandas.DataFrame, data to transform
        varlist: list, variables to transform
        woe_mapping_table: pandas.DataFrame, WOE mapping table
        woe_suffix: str, suffix for WOE variable names (default "_woe")
    Returns:
        pandas.DataFrame with WOE transformed data
    """
    return mapping_woe(data, varlist, woe_mapping_table, suffix=woe_suffix, drop_bin_info=True)

plot_bivar_graph_func

plot_bivar_graph_func(data, varlist, dep, ref_woe_table, group, save_dir)

Plot bivariate WOE comparison graph.

Args: data: pandas.DataFrame, data for plotting varlist: list, variables to plot dep: str, target variable name ref_woe_table: pandas.DataFrame, reference WOE mapping table group: str, grouping variable name for distinguishing curves save_dir: str, directory path to save images Returns: None, saves images directly

源代码位于: Modeling_Tool/WOE/WOE_Master.py
def plot_bivar_graph_func(data, varlist, dep, ref_woe_table, group, save_dir):
    """Plot bivariate WOE comparison graph.

    Args:
        data: pandas.DataFrame, data for plotting
        varlist: list, variables to plot
        dep: str, target variable name
        ref_woe_table: pandas.DataFrame, reference WOE mapping table
        group: str, grouping variable name for distinguishing curves
        save_dir: str, directory path to save images
    Returns:
        None, saves images directly
    """
    get_bivar_graph(data=data,
                    varlist=varlist,
                    sep=dep,
                    ref_woe_table=ref_woe_table,
                    group=group,
                    save_dir=save_dir)

转换器与单调性 — WOE_Tool

WOE_Tool

WOE转换与单调性分析工具包 提供WOE分箱、转换、映射及单调性检验功能

WOETransformer

WOE转换器。

提供WOE分箱、转换和单调性检验的完整功能, 支持单变量和多变量批量处理,支持训练集和验证集的WOE映射。

参数:

nbins : int, optional 分箱数量,默认为10 precision : int, optional WOE和IV计算精度,默认为5 min_bin_prop : float, optional 每个分箱的最小样本比例,默认为0.05 include_missing : bool, optional 是否将缺失值作为单独分箱,默认为False equal_freq : bool, optional 是否使用等频分箱,默认为True fillna : int/float, optional 缺失值填充值,默认为-999999 chi2_config : tuple, optional 卡方分箱配置,(init_bins, p_value)元组,默认为None tree_binning_seed : int, optional 决策树分箱随机种子,默认为None spec_values : list, optional 特殊值列表,默认为空列表 drop_bin_info : bool, optional 是否删除中间分箱信息列,默认为True ret_woe_table : bool, optional 是否返回WOE映射表,默认为True

示例:

transformer = WOETransformer(nbins=10) result = transformer.transform(df, ['var1', 'var2'], 'target')

源代码位于: Modeling_Tool/WOE/WOE_Tool.py
class WOETransformer:
    """WOE转换器。

    提供WOE分箱、转换和单调性检验的完整功能,
    支持单变量和多变量批量处理,支持训练集和验证集的WOE映射。

    参数:
    -----------
    nbins : int, optional
        分箱数量,默认为10
    precision : int, optional
        WOE和IV计算精度,默认为5
    min_bin_prop : float, optional
        每个分箱的最小样本比例,默认为0.05
    include_missing : bool, optional
        是否将缺失值作为单独分箱,默认为False
    equal_freq : bool, optional
        是否使用等频分箱,默认为True
    fillna : int/float, optional
        缺失值填充值,默认为-999999
    chi2_config : tuple, optional
        卡方分箱配置,(init_bins, p_value)元组,默认为None
    tree_binning_seed : int, optional
        决策树分箱随机种子,默认为None
    spec_values : list, optional
        特殊值列表,默认为空列表
    drop_bin_info : bool, optional
        是否删除中间分箱信息列,默认为True
    ret_woe_table : bool, optional
        是否返回WOE映射表,默认为True

    示例:
    --------
    >>> transformer = WOETransformer(nbins=10)
    >>> result = transformer.transform(df, ['var1', 'var2'], 'target')
    """

    def __init__(self, nbins=10, precision=5, min_bin_prop=0.05, include_missing=False,
                 equal_freq=True, fillna=-999999, chi2_config=None, tree_binning_seed=None,
                 spec_values=None, drop_bin_info=True, ret_woe_table=True):
        """初始化WOE转换器。

        参数:
        -----------
        nbins : int, optional
            分箱数量
        precision : int, optional
            WOE和IV计算精度
        min_bin_prop : float, optional
            每个分箱的最小样本比例
        include_missing : bool, optional
            是否将缺失值作为单独分箱
        equal_freq : bool, optional
            是否使用等频分箱
        fillna : int/float, optional
            缺失值填充值
        chi2_config : tuple, optional
            卡方分箱配置
        tree_binning_seed : int, optional
            决策树分箱随机种子
        spec_values : list, optional
            特殊值列表
        drop_bin_info : bool, optional
            是否删除中间分箱信息列
        ret_woe_table : bool, optional
            是否返回WOE映射表
        """
        self.nbins = nbins
        self.precision = precision
        self.min_bin_prop = min_bin_prop
        self.include_missing = include_missing
        self.equal_freq = equal_freq
        self.fillna = fillna
        self.chi2_config = chi2_config
        self.tree_binning_seed = tree_binning_seed
        self.spec_values = spec_values if spec_values is not None else []
        self.drop_bin_info = drop_bin_info
        self.ret_woe_table = ret_woe_table

    def _get_woe_table(self, binning_res, var, dep):
        """根据分箱结果计算WOE表。

        参数:
        -----------
        binning_res : pd.DataFrame
            分箱结果数据框
        var : str
            变量名
        dep : str
            目标变量名

        返回:
        --------
        tuple
            (woe_table, woe_mapping_dict) 元组
        """
        woe_table = binning_res.groupby([f"_bin_num_{var}", f"_bin_range_{var}"], dropna=False)\
            .agg(
            MIN=(var, "min"),
            MAX=(var, "max"),
            N=(f"_bin_num_{var}", "count"),
            AVG_SCORE=(var, "mean"),
            AVG_BAD=(dep, lambda x: ((x == 1).sum() / x.count())),
            AVG_GOOD=(dep, lambda x: ((x == 0).sum() / x.count())),
            N_BAD=(dep, "sum"),
            N_GOOD=(dep, lambda x: (x == 0).sum())
        )

        # IV/WOE Calculation
        woe_table["BAD_PCT_PER_BIN"] = woe_table["N_BAD"] / woe_table["N_BAD"].sum()
        woe_table["GOOD_PCT_PER_BIN"] = woe_table["N_GOOD"] / woe_table["N_GOOD"].sum()
        woe_table["LIFT"] = woe_table['AVG_BAD'] / woe_table['AVG_BAD'].mean()
        woe_table["WOE"] = calc_woe(data=woe_table, bad_pct="BAD_PCT_PER_BIN", good_pct="GOOD_PCT_PER_BIN")
        woe_table["IV"] = calc_iv(data=woe_table, bad_pct="BAD_PCT_PER_BIN", good_pct="GOOD_PCT_PER_BIN")

        # WOE Mapping Dictionary
        woe_table = woe_table.reset_index(drop=False)
        woe_mapping_dict = dict(zip(woe_table[f"_bin_range_{var}"], woe_table["WOE"]))

        return woe_table, woe_mapping_dict

    def transform_single(self, train_df, var, dep, oot_df=None, check_monotonicity_flag=False):
        """对单个变量进行WOE转换。

        参数:
        -----------
        train_df : pd.DataFrame
            训练数据集
        var : str
            待转换的变量名
        dep : str
            目标变量(因变量)名
        oot_df : pd.DataFrame, optional
            验证/测试数据集,默认为None
        check_monotonicity_flag : bool, optional
            是否检查单调性,默认为False

        返回:
        --------
        tuple/list
            根据参数返回训练结果、验证结果和WOE映射表
        """
        chi2_method = False
        if self.chi2_config:
            chi2_method = True
        else:
            self.chi2_config = (100, 0.99)

        tree_binning = False
        if self.tree_binning_seed:
            tree_binning = True

        train_res, train_edges = super_binning(
            data=train_df,
            score=var,
            dep=dep,
            nbins=self.nbins,
            precision=self.precision,
            min_bin_prop=self.min_bin_prop,
            include_missing=self.include_missing,
            equal_freq=self.equal_freq,
            chi2_method=chi2_method,
            chi2_p=self.chi2_config[1],
            init_equi_bins=self.chi2_config[0],
            fillna=self.fillna,
            spec_values=self.spec_values,
            tree_binning=tree_binning,
            random_state=self.tree_binning_seed,
            return_edges=True,
            bin_colnames=(f"_bin_num_{var}", f"_bin_range_{var}"),
            ascending=True
        )

        train_woe_table, train_woe_mapping_dict = self._get_woe_table(train_res, var, dep)

        if check_monotonicity_flag:
            if not is_monotonic(train_woe_table.query("MIN != MAX"), "WOE")[0]:
                logging.warning(f"WARNING: {var} WOE values are NOT monotonic in Train Dataset!")

        # WOE Mapping to DataFrame
        train_res[f"{var}_woe"] = train_res[f"_bin_range_{var}"].map(train_woe_mapping_dict)

        # Drop Bin Info
        if self.drop_bin_info:
            train_res = train_res.drop(columns=[f"_bin_num_{var}", f"_bin_range_{var}"])

        if oot_df is not None:
            woe_mapping_table = train_woe_table.copy()
            woe_mapping_table["BIN_RANGE"] = woe_mapping_table[f"_bin_range_{var}"]
            woe_mapping_table["BIN_NUM"] = woe_mapping_table[f"_bin_num_{var}"]
            woe_mapping_table["VAR"] = var
            oot_res = _mapping_woe_single_var(
                data=oot_df, var=var, woe_mapping_table=woe_mapping_table
            )

        if self.ret_woe_table and oot_df is not None:
            return train_res, oot_res, train_woe_table

        if self.ret_woe_table and oot_df is None:
            return train_res, train_woe_table

        if oot_df is not None:
            return train_res, oot_res

        return train_res

    def transform(self, train_df, varlist, dep, oot_df=None, check_monotonicity_flag=False):
        """对多个变量进行WOE转换。

        参数:
        -----------
        train_df : pd.DataFrame
            训练数据集
        varlist : list
            待转换的变量名列表
        dep : str
            目标变量(因变量)名
        oot_df : pd.DataFrame, optional
            验证/测试数据集,默认为None
        check_monotonicity_flag : bool, optional
            是否检查单调性,默认为False

        返回:
        --------
        tuple/list
            返回结果的字典和WOE映射表。
            字典键为'TRAIN'和'OOT'(当oot_df不为None时)

        示例:
        --------
        >>> transformer = WOETransformer(nbins=10)
        >>> result = transformer.transform(df, ['var1', 'var2'], 'target')
        """
        fnl_res = {}
        for i, var in enumerate(varlist):
            woe_res = self.transform_single(
                train_df=train_df,
                var=var,
                dep=dep,
                oot_df=oot_df,
                check_monotonicity_flag=check_monotonicity_flag
            )

            train_df = woe_res[0]
            if oot_df is not None:
                oot_df = woe_res[1]

            if i == 0:
                train_woe_table = woe_res[-1]
                train_woe_table["VAR"] = var
                train_woe_table = train_woe_table.rename(columns={
                    f"_bin_num_{var}": "BIN_NUM",
                    f"_bin_range_{var}": "BIN_RANGE"
                })
            else:
                train_woe_table_append = woe_res[-1]
                train_woe_table_append["VAR"] = var
                train_woe_table_append = train_woe_table_append.rename(columns={
                    f"_bin_num_{var}": "BIN_NUM",
                    f"_bin_range_{var}": "BIN_RANGE"
                })

            if i > 0:
                train_woe_table = pd.concat([train_woe_table, train_woe_table_append])

        fnl_res["TRAIN"] = train_df
        if oot_df is not None:
            fnl_res["OOT"] = oot_df

        if self.ret_woe_table:
            return fnl_res, train_woe_table

        return fnl_res

transform_single

transform_single(train_df, var, dep, oot_df=None, check_monotonicity_flag=False)

对单个变量进行WOE转换。

参数:

train_df : pd.DataFrame 训练数据集 var : str 待转换的变量名 dep : str 目标变量(因变量)名 oot_df : pd.DataFrame, optional 验证/测试数据集,默认为None check_monotonicity_flag : bool, optional 是否检查单调性,默认为False

返回:

tuple/list 根据参数返回训练结果、验证结果和WOE映射表

源代码位于: Modeling_Tool/WOE/WOE_Tool.py
def transform_single(self, train_df, var, dep, oot_df=None, check_monotonicity_flag=False):
    """对单个变量进行WOE转换。

    参数:
    -----------
    train_df : pd.DataFrame
        训练数据集
    var : str
        待转换的变量名
    dep : str
        目标变量(因变量)名
    oot_df : pd.DataFrame, optional
        验证/测试数据集,默认为None
    check_monotonicity_flag : bool, optional
        是否检查单调性,默认为False

    返回:
    --------
    tuple/list
        根据参数返回训练结果、验证结果和WOE映射表
    """
    chi2_method = False
    if self.chi2_config:
        chi2_method = True
    else:
        self.chi2_config = (100, 0.99)

    tree_binning = False
    if self.tree_binning_seed:
        tree_binning = True

    train_res, train_edges = super_binning(
        data=train_df,
        score=var,
        dep=dep,
        nbins=self.nbins,
        precision=self.precision,
        min_bin_prop=self.min_bin_prop,
        include_missing=self.include_missing,
        equal_freq=self.equal_freq,
        chi2_method=chi2_method,
        chi2_p=self.chi2_config[1],
        init_equi_bins=self.chi2_config[0],
        fillna=self.fillna,
        spec_values=self.spec_values,
        tree_binning=tree_binning,
        random_state=self.tree_binning_seed,
        return_edges=True,
        bin_colnames=(f"_bin_num_{var}", f"_bin_range_{var}"),
        ascending=True
    )

    train_woe_table, train_woe_mapping_dict = self._get_woe_table(train_res, var, dep)

    if check_monotonicity_flag:
        if not is_monotonic(train_woe_table.query("MIN != MAX"), "WOE")[0]:
            logging.warning(f"WARNING: {var} WOE values are NOT monotonic in Train Dataset!")

    # WOE Mapping to DataFrame
    train_res[f"{var}_woe"] = train_res[f"_bin_range_{var}"].map(train_woe_mapping_dict)

    # Drop Bin Info
    if self.drop_bin_info:
        train_res = train_res.drop(columns=[f"_bin_num_{var}", f"_bin_range_{var}"])

    if oot_df is not None:
        woe_mapping_table = train_woe_table.copy()
        woe_mapping_table["BIN_RANGE"] = woe_mapping_table[f"_bin_range_{var}"]
        woe_mapping_table["BIN_NUM"] = woe_mapping_table[f"_bin_num_{var}"]
        woe_mapping_table["VAR"] = var
        oot_res = _mapping_woe_single_var(
            data=oot_df, var=var, woe_mapping_table=woe_mapping_table
        )

    if self.ret_woe_table and oot_df is not None:
        return train_res, oot_res, train_woe_table

    if self.ret_woe_table and oot_df is None:
        return train_res, train_woe_table

    if oot_df is not None:
        return train_res, oot_res

    return train_res

transform

transform(train_df, varlist, dep, oot_df=None, check_monotonicity_flag=False)

对多个变量进行WOE转换。

参数:

train_df : pd.DataFrame 训练数据集 varlist : list 待转换的变量名列表 dep : str 目标变量(因变量)名 oot_df : pd.DataFrame, optional 验证/测试数据集,默认为None check_monotonicity_flag : bool, optional 是否检查单调性,默认为False

返回:

tuple/list 返回结果的字典和WOE映射表。 字典键为'TRAIN'和'OOT'(当oot_df不为None时)

示例:

transformer = WOETransformer(nbins=10) result = transformer.transform(df, ['var1', 'var2'], 'target')

源代码位于: Modeling_Tool/WOE/WOE_Tool.py
def transform(self, train_df, varlist, dep, oot_df=None, check_monotonicity_flag=False):
    """对多个变量进行WOE转换。

    参数:
    -----------
    train_df : pd.DataFrame
        训练数据集
    varlist : list
        待转换的变量名列表
    dep : str
        目标变量(因变量)名
    oot_df : pd.DataFrame, optional
        验证/测试数据集,默认为None
    check_monotonicity_flag : bool, optional
        是否检查单调性,默认为False

    返回:
    --------
    tuple/list
        返回结果的字典和WOE映射表。
        字典键为'TRAIN'和'OOT'(当oot_df不为None时)

    示例:
    --------
    >>> transformer = WOETransformer(nbins=10)
    >>> result = transformer.transform(df, ['var1', 'var2'], 'target')
    """
    fnl_res = {}
    for i, var in enumerate(varlist):
        woe_res = self.transform_single(
            train_df=train_df,
            var=var,
            dep=dep,
            oot_df=oot_df,
            check_monotonicity_flag=check_monotonicity_flag
        )

        train_df = woe_res[0]
        if oot_df is not None:
            oot_df = woe_res[1]

        if i == 0:
            train_woe_table = woe_res[-1]
            train_woe_table["VAR"] = var
            train_woe_table = train_woe_table.rename(columns={
                f"_bin_num_{var}": "BIN_NUM",
                f"_bin_range_{var}": "BIN_RANGE"
            })
        else:
            train_woe_table_append = woe_res[-1]
            train_woe_table_append["VAR"] = var
            train_woe_table_append = train_woe_table_append.rename(columns={
                f"_bin_num_{var}": "BIN_NUM",
                f"_bin_range_{var}": "BIN_RANGE"
            })

        if i > 0:
            train_woe_table = pd.concat([train_woe_table, train_woe_table_append])

    fnl_res["TRAIN"] = train_df
    if oot_df is not None:
        fnl_res["OOT"] = oot_df

    if self.ret_woe_table:
        return fnl_res, train_woe_table

    return fnl_res

WOEMappingTransformer

基于WOE映射表的转换器。

使用预计算的WOE映射表对新数据进行WOE转换, 支持单变量和多变量批量处理。

参数:

woe_mapping_table : pd.DataFrame WOE映射表 missing_ref : any, optional 缺失值参考值,默认为None ret_bin_no : bool, optional 是否返回分箱编号,默认为False ret_category : bool, optional 是否返回分类类型,默认为False rename_orig_var : bool, optional 是否重命名原始变量,默认为False suffix : str, optional 变量名后缀,默认为''

示例:

transformer = WOEMappingTransformer(woe_mapping_table) result = transformer.transform(df, ['var1', 'var2'])

源代码位于: Modeling_Tool/WOE/WOE_Tool.py
class WOEMappingTransformer:
    """基于WOE映射表的转换器。

    使用预计算的WOE映射表对新数据进行WOE转换,
    支持单变量和多变量批量处理。

    参数:
    -----------
    woe_mapping_table : pd.DataFrame
        WOE映射表
    missing_ref : any, optional
        缺失值参考值,默认为None
    ret_bin_no : bool, optional
        是否返回分箱编号,默认为False
    ret_category : bool, optional
        是否返回分类类型,默认为False
    rename_orig_var : bool, optional
        是否重命名原始变量,默认为False
    suffix : str, optional
        变量名后缀,默认为''

    示例:
    --------
    >>> transformer = WOEMappingTransformer(woe_mapping_table)
    >>> result = transformer.transform(df, ['var1', 'var2'])
    """

    def __init__(self, woe_mapping_table, missing_ref=None, ret_bin_no=False,
                 ret_category=False, rename_orig_var=False, suffix=''):
        """初始化WOE映射转换器。

        参数:
        -----------
        woe_mapping_table : pd.DataFrame
            WOE映射表
        missing_ref : any, optional
            缺失值参考值
        ret_bin_no : bool, optional
            是否返回分箱编号
        ret_category : bool, optional
            是否返回分类类型
        rename_orig_var : bool, optional
            是否重命名原始变量
        suffix : str, optional
            变量名后缀
        """
        self.woe_mapping_table = woe_mapping_table
        self.missing_ref = missing_ref
        self.ret_bin_no = ret_bin_no
        self.ret_category = ret_category
        self.rename_orig_var = rename_orig_var
        self.suffix = suffix

    def transform_single(self, data, var):
        """对单个变量进行WOE转换。

        参数:
        -----------
        data : pd.DataFrame
            输入的数据框
        var : str
            待转换的变量名

        返回:
        --------
        pd.DataFrame
            转换后的数据框
        """
        if self.rename_orig_var:
            data = data.rename(columns={var: (var + self.suffix)})
            data[var] = data[(var + self.suffix)].copy()
            data[var] = convert_single_var_woe(
                data, var, self.woe_mapping_table,
                self.missing_ref, self.ret_bin_no
            )
            if not self.ret_category:
                data[var] = data[var].astype(float)
        else:
            data[var + self.suffix] = convert_single_var_woe(
                data, var, self.woe_mapping_table,
                self.missing_ref, self.ret_bin_no
            )
            if not self.ret_category:
                data[var + self.suffix] = data[var + self.suffix].astype(float)

        return data

    def transform(self, data, varlist):
        """对多个变量进行WOE转换。

        参数:
        -----------
        data : pd.DataFrame
            输入的数据框
        varlist : list
            待转换的变量名列表

        返回:
        --------
        pd.DataFrame
            转换后的数据框

        示例:
        --------
        >>> transformer = WOEMappingTransformer(woe_mapping_table)
        >>> result = transformer.transform(df, ['var1', 'var2'])
        """
        res = data.copy()
        for var in varlist:
            res = self.transform_single(res, var)
        return res

transform_single

transform_single(data, var)

对单个变量进行WOE转换。

参数:

data : pd.DataFrame 输入的数据框 var : str 待转换的变量名

返回:

pd.DataFrame 转换后的数据框

源代码位于: Modeling_Tool/WOE/WOE_Tool.py
def transform_single(self, data, var):
    """对单个变量进行WOE转换。

    参数:
    -----------
    data : pd.DataFrame
        输入的数据框
    var : str
        待转换的变量名

    返回:
    --------
    pd.DataFrame
        转换后的数据框
    """
    if self.rename_orig_var:
        data = data.rename(columns={var: (var + self.suffix)})
        data[var] = data[(var + self.suffix)].copy()
        data[var] = convert_single_var_woe(
            data, var, self.woe_mapping_table,
            self.missing_ref, self.ret_bin_no
        )
        if not self.ret_category:
            data[var] = data[var].astype(float)
    else:
        data[var + self.suffix] = convert_single_var_woe(
            data, var, self.woe_mapping_table,
            self.missing_ref, self.ret_bin_no
        )
        if not self.ret_category:
            data[var + self.suffix] = data[var + self.suffix].astype(float)

    return data

transform

transform(data, varlist)

对多个变量进行WOE转换。

参数:

data : pd.DataFrame 输入的数据框 varlist : list 待转换的变量名列表

返回:

pd.DataFrame 转换后的数据框

示例:

transformer = WOEMappingTransformer(woe_mapping_table) result = transformer.transform(df, ['var1', 'var2'])

源代码位于: Modeling_Tool/WOE/WOE_Tool.py
def transform(self, data, varlist):
    """对多个变量进行WOE转换。

    参数:
    -----------
    data : pd.DataFrame
        输入的数据框
    varlist : list
        待转换的变量名列表

    返回:
    --------
    pd.DataFrame
        转换后的数据框

    示例:
    --------
    >>> transformer = WOEMappingTransformer(woe_mapping_table)
    >>> result = transformer.transform(df, ['var1', 'var2'])
    """
    res = data.copy()
    for var in varlist:
        res = self.transform_single(res, var)
    return res

is_monotonic

is_monotonic(data, column, direction='auto', strict=False, handle_nan='drop')

检查Pandas Series或DataFrame列是否单调(递增或递减)。

参数:

data : pd.DataFrame 包含数据的数据框 column : str 要检查的列名 direction : str, optional 检查方向,'auto'(自动检测)、'increasing'(递增)或'decreasing'(递减), 默认为'auto' strict : bool, optional 是否要求严格单调(不允许相等值),默认为False handle_nan : str, optional 处理NaN值的方法,可选'drop'(忽略)、'forward'(向前填充)、 'backward'(向后填充)或'error'(报错),默认为'drop'

返回:

tuple (是否单调, 单调方向) 的元组。 是否单调为bool值,方向为1(递增)、-1(递减)或0(非单调)

源代码位于: Modeling_Tool/WOE/WOE_Tool.py
def is_monotonic(data, column, direction='auto', strict=False, handle_nan='drop'):
    """检查Pandas Series或DataFrame列是否单调(递增或递减)。

    参数:
    -----------
    data : pd.DataFrame
        包含数据的数据框
    column : str
        要检查的列名
    direction : str, optional
        检查方向,'auto'(自动检测)、'increasing'(递增)或'decreasing'(递减),
        默认为'auto'
    strict : bool, optional
        是否要求严格单调(不允许相等值),默认为False
    handle_nan : str, optional
        处理NaN值的方法,可选'drop'(忽略)、'forward'(向前填充)、
        'backward'(向后填充)或'error'(报错),默认为'drop'

    返回:
    --------
    tuple
        (是否单调, 单调方向) 的元组。
        是否单调为bool值,方向为1(递增)、-1(递减)或0(非单调)
    """
    series = data[column]

    # 处理NaN值
    if series.isna().any():
        if handle_nan == 'drop':
            series = series.dropna()
        elif handle_nan == 'forward':
            series = series.ffill()
        elif handle_nan == 'backward':
            series = series.bfill()
        elif handle_nan == 'error':
            raise ValueError("序列包含NaN值")
        else:
            raise ValueError("handle_nan参数必须是'drop'、'forward'、'backward'或'error'")

    # 如果序列为空或只有一个元素,则认为是单调的
    if len(series) <= 1:
        return True, 0 if len(series) == 0 else 0

    # 计算差值
    diffs = series.diff().iloc[1:]

    # 检查单调性
    if direction == 'auto':
        if strict:
            if (diffs > 0).all():  # 所有差值都为正
                return True, 1
            elif (diffs < 0).all():  # 所有差值都为负
                return True, -1
            else:
                return False, 0
        else:
            if (diffs >= 0).all():  # 所有差值都非负
                return True, 1
            elif (diffs <= 0).all():  # 所有差值都非正
                return True, -1
            else:
                return False, 0
    elif direction == 'increasing':
        if strict:
            is_mono = (diffs > 0).all()
        else:
            is_mono = (diffs >= 0).all()
        return is_mono, 1 if is_mono else 0
    elif direction == 'decreasing':
        if strict:
            is_mono = (diffs < 0).all()
        else:
            is_mono = (diffs <= 0).all()
        return is_mono, -1 if is_mono else 0
    else:
        raise ValueError("direction参数必须是'auto'、'increasing'或'decreasing'")

check_monotonicity

check_monotonicity(data, var)

检查WOE值的单调性。

对指定变量验证其WOE值是否满足单调性要求, 用于评估分箱效果是否符合业务逻辑。

参数:

data : pd.DataFrame 包含分箱信息和WOE值的数据框 var : str 待检查的变量名

返回:

tuple (是否单调, 单调方向) 的元组,格式同 is_monotonic 函数

示例:

result = check_monotonicity(woe_df, 'age')

源代码位于: Modeling_Tool/WOE/WOE_Tool.py
def check_monotonicity(data, var):
    """检查WOE值的单调性。

    对指定变量验证其WOE值是否满足单调性要求,
    用于评估分箱效果是否符合业务逻辑。

    参数:
    -----------
    data : pd.DataFrame
        包含分箱信息和WOE值的数据框
    var : str
        待检查的变量名

    返回:
    --------
    tuple
        (是否单调, 单调方向) 的元组,格式同 is_monotonic 函数

    示例:
    --------
    >>> result = check_monotonicity(woe_df, 'age')
    """
    df_grp = data.groupby([f"_bin_num_{var}"]).agg(
        {f"_bin_num_{var}": "count", var: [min, max], f"{var}_woe": [min, max, "mean"]}
    )
    assert (df_grp[(f"{var}_woe", "min")] == df_grp[(f"{var}_woe", "max")]).all()
    woe = pd.DataFrame(df_grp.loc[df_grp[(var, "min")] != df_grp[(var, "max")], (f"{var}_woe", "min")])
    res = is_monotonic(woe, (f"{var}_woe", "min"))
    return res

convert_single_var_woe

convert_single_var_woe(data, var, woe_mapping_table, missing_ref=None, ret_bin_no=False)

将原始变量值转换为WOE值。

根据预计算的WOE映射表,对指定变量进行WOE转换。 支持缺失值处理和分箱编号返回。

参数:

data : pd.DataFrame 输入的数据框 var : str 待转换的变量名 woe_mapping_table : pd.DataFrame WOE映射表,包含bin_no、bin_value、woe和n列 missing_ref : any, optional 缺失值参考值,默认为None ret_bin_no : bool, optional 是否返回分箱编号而非WOE值,默认为False

返回:

pd.Series/pd.Categorical 转换后的WOE值或分箱编号

示例:

woe_values = convert_single_var_woe(df, 'age', woe_table)

源代码位于: Modeling_Tool/WOE/WOE_Tool.py
def convert_single_var_woe(data, var, woe_mapping_table, missing_ref=None, ret_bin_no=False):
    """将原始变量值转换为WOE值。

    根据预计算的WOE映射表,对指定变量进行WOE转换。
    支持缺失值处理和分箱编号返回。

    参数:
    -----------
    data : pd.DataFrame
        输入的数据框
    var : str
        待转换的变量名
    woe_mapping_table : pd.DataFrame
        WOE映射表,包含bin_no、bin_value、woe和n列
    missing_ref : any, optional
        缺失值参考值,默认为None
    ret_bin_no : bool, optional
        是否返回分箱编号而非WOE值,默认为False

    返回:
    --------
    pd.Series/pd.Categorical
        转换后的WOE值或分箱编号

    示例:
    --------
    >>> woe_values = convert_single_var_woe(df, 'age', woe_table)
    """
    var_woe_mapping = woe_mapping_table.query(f"var_name == '{var}_woe'")
    var_woe_mapping = var_woe_mapping[["bin_no", "bin_value", "woe", "n"]]

    var_woe_mapping["bin_value_list"] = var_woe_mapping["bin_value"].apply(
        lambda x: x.replace("[", "").replace(")", "").split(",")
    )

    woe_mapping_dict = dict(zip(var_woe_mapping['bin_no'], var_woe_mapping['woe']))
    bin_range = [
        float(v.strip()) if v.strip() != 'inf' else np.inf
        for x in var_woe_mapping["bin_value_list"].tolist()
        for v in x
    ]

    unique_range = []
    for x in bin_range:
        if x not in unique_range:
            unique_range.append(x)

    if missing_ref:
        var_serires = data[var].fillna(missing_ref)

    bin_no_transform = pd.cut(
        var_serires,
        bins=unique_range,
        right=False,
        labels=[x for x in range(0, len(unique_range) - 1)]
    )

    if ret_bin_no:
        return bin_no_transform

    woe_res = bin_no_transform.map(woe_mapping_dict)

    return woe_res

woe_transform_cdaml

woe_transform_cdaml(data, varlist, woe_mapping_path, missing_ref=None, ret_bin_no=False, ret_category=False, rename_orig_var=False, suffix='')

使用cdaml包进行WOE转换。

从文件路径读取WOE映射表或直接使用映射表数据框, 对指定变量列表进行WOE转换。

参数:

data : pd.DataFrame 输入的数据框 varlist : list 待转换的变量名列表 woe_mapping_path : str/pd.DataFrame WOE映射表文件路径或数据框 missing_ref : any, optional 缺失值参考值,默认为None ret_bin_no : bool, optional 是否返回分箱编号,默认为False ret_category : bool, optional 是否返回分类类型,默认为False rename_orig_var : bool, optional 是否重命名原始变量,默认为False suffix : str, optional 变量名后缀,默认为''

返回:

pd.DataFrame 转换后的数据框

示例:

result = woe_transform_cdaml(df, ['var1', 'var2'], 'woe_mapping.csv')

源代码位于: Modeling_Tool/WOE/WOE_Tool.py
def woe_transform_cdaml(data, varlist, woe_mapping_path, missing_ref=None,
                        ret_bin_no=False, ret_category=False, rename_orig_var=False, suffix=''):
    """使用cdaml包进行WOE转换。

    从文件路径读取WOE映射表或直接使用映射表数据框,
    对指定变量列表进行WOE转换。

    参数:
    -----------
    data : pd.DataFrame
        输入的数据框
    varlist : list
        待转换的变量名列表
    woe_mapping_path : str/pd.DataFrame
        WOE映射表文件路径或数据框
    missing_ref : any, optional
        缺失值参考值,默认为None
    ret_bin_no : bool, optional
        是否返回分箱编号,默认为False
    ret_category : bool, optional
        是否返回分类类型,默认为False
    rename_orig_var : bool, optional
        是否重命名原始变量,默认为False
    suffix : str, optional
        变量名后缀,默认为''

    返回:
    --------
    pd.DataFrame
        转换后的数据框

    示例:
    --------
    >>> result = woe_transform_cdaml(df, ['var1', 'var2'], 'woe_mapping.csv')
    """
    woe_mapping_table = pd.read_csv(woe_mapping_path) if isinstance(woe_mapping_path, str) else woe_mapping_path
    woe_mapping_table.columns = [x.lower() for x in woe_mapping_table.columns]

    transformer = WOEMappingTransformer(
        woe_mapping_table=woe_mapping_table,
        missing_ref=missing_ref,
        ret_bin_no=ret_bin_no,
        ret_category=ret_category,
        rename_orig_var=rename_orig_var,
        suffix=suffix
    )
    return transformer.transform(data, varlist)

get_woe_table

get_woe_table(data, var, dep, grp_name=None, nbins=10, precision=5, min_bin_prop=0.05, include_missing=True, equal_freq=True, fillna=-999999, chi2_config=None, tree_binning_seed=None, spec_values=None)

获取WOE分箱表。

对指定变量进行分箱处理,计算各分箱的WOE值、IV值等统计量。 支持分组分析和单调性检验。

参数:

data : pd.DataFrame 输入的数据框 var : str 待分析的变量名 dep : str 目标变量(因变量)名 grp_name : str, optional 分组变量名,默认为None nbins : int, optional 分箱数量,默认为10 precision : int, optional 计算精度,默认为5 min_bin_prop : float, optional 每个分箱的最小样本比例,默认为0.05 include_missing : bool, optional 是否将缺失值作为单独分箱,默认为True equal_freq : bool, optional 是否使用等频分箱,默认为True fillna : int/float, optional 缺失值填充值,默认为-999999 chi2_config : tuple, optional 卡方分箱配置,(init_bins, p_value)元组,默认为None tree_binning_seed : int, optional 决策树分箱随机种子,默认为None spec_values : list, optional 特殊值列表,默认为None

返回:

tuple/pd.DataFrame 当grp_name不为None时返回(woe_table, grp_summary, grp_woe_pvt)元组; 当grp_name为None时返回(woe_table, is_monotonic, direction, slope)元组

示例:

woe_table, is_mono, direction, slope = get_woe_table(df, 'age', 'target')

源代码位于: Modeling_Tool/WOE/WOE_Tool.py
def get_woe_table(data, var, dep, grp_name=None, nbins=10, precision=5,
                  min_bin_prop=0.05, include_missing=True, equal_freq=True,
                  fillna=-999999, chi2_config=None, tree_binning_seed=None, spec_values=None):
    """获取WOE分箱表。

    对指定变量进行分箱处理,计算各分箱的WOE值、IV值等统计量。
    支持分组分析和单调性检验。

    参数:
    -----------
    data : pd.DataFrame
        输入的数据框
    var : str
        待分析的变量名
    dep : str
        目标变量(因变量)名
    grp_name : str, optional
        分组变量名,默认为None
    nbins : int, optional
        分箱数量,默认为10
    precision : int, optional
        计算精度,默认为5
    min_bin_prop : float, optional
        每个分箱的最小样本比例,默认为0.05
    include_missing : bool, optional
        是否将缺失值作为单独分箱,默认为True
    equal_freq : bool, optional
        是否使用等频分箱,默认为True
    fillna : int/float, optional
        缺失值填充值,默认为-999999
    chi2_config : tuple, optional
        卡方分箱配置,(init_bins, p_value)元组,默认为None
    tree_binning_seed : int, optional
        决策树分箱随机种子,默认为None
    spec_values : list, optional
        特殊值列表,默认为None

    返回:
    --------
    tuple/pd.DataFrame
        当grp_name不为None时返回(woe_table, grp_summary, grp_woe_pvt)元组;
        当grp_name为None时返回(woe_table, is_monotonic, direction, slope)元组

    示例:
    --------
    >>> woe_table, is_mono, direction, slope = get_woe_table(df, 'age', 'target')
    """
    from pandas.api.types import is_numeric_dtype, is_string_dtype

    if spec_values is None:
        spec_values = []

    chi2_method = False
    if chi2_config:
        chi2_method = True
    else:
        chi2_config = (100, 0.99)

    tree_binning = False
    if tree_binning_seed:
        tree_binning = True

    from Modeling_Tool.Eval.Model_Eval_Tool import get_gains_table

    gains_table = get_gains_table(
        data=data,
        score=var,
        dep=dep,
        nbins=nbins,
        precision=precision,
        min_bin_prop=min_bin_prop,
        include_missing=include_missing,
        equal_freq=equal_freq,
        chi2_method=chi2_method,
        chi2_p=chi2_config[1],
        tree_binning=tree_binning,
        init_equi_bins=chi2_config[0],
        fillna=fillna,
        spec_values=spec_values,
        sync_range=True,
        grp_name=grp_name,
        retSummary=False,
        random_state=tree_binning_seed,
        ascending=True,
        withSummary=False
    )

    gains_table = gains_table.reset_index(drop=False).rename(columns={
        "_bin_num": "BIN_NUM", "_bin_range": "BIN_RANGE"
    })
    woe_cols = ["BIN_NUM", "BIN_RANGE", "MIN", "MAX", "N", "RANK_ORDER_BUMP", "WOE", "IV", "AVG_BAD"]
    if grp_name:
        woe_cols += [grp_name]
    woe_table = gains_table[woe_cols]
    avg_bad_df = woe_table.loc[woe_table["BIN_NUM"] != "Grand Summary", :]

    if include_missing:
        monoto_info = is_monotonic(avg_bad_df.iloc[1:, :], "AVG_BAD")
    else:
        monoto_info = is_monotonic(avg_bad_df, "AVG_BAD")

    dep_slope = calculate_slope_manual(avg_bad_df, "AVG_BAD")
    direction = 1 if dep_slope > 0 else -1 if dep_slope < 0 else 0

    if grp_name:
        slope_grp = pd.DataFrame(
            gains_table.groupby([grp_name]).apply(calculate_slope_manual, "AVG_BAD"),
            columns=["SLOPE"]
        )
        grp_summary = gains_table.groupby([grp_name]).agg(
            N=("N", sum), IV=("IV", sum), KS=("KS_PER_BIN", max),
            BTM_LIFT=("LIFT", min), TOP_LIFT=("LIFT", max)
        ).merge(slope_grp, left_index=True, right_index=True)
        grp_summary['direction'] = grp_summary['SLOPE'].apply(
            lambda x: 1 if x > 0 else -1 if x < 0 else 0
        )
        grp_woe_pvt = gains_table.pivot_table(
            index=["BIN_NUM", "BIN_RANGE"],
            columns=[grp_name],
            values=["WOE", 'AVG_BAD']
        )

        return woe_table, grp_summary, grp_woe_pvt

    return (woe_table, monoto_info[0], direction, dep_slope)

plot_monotonicity_check

plot_monotonicity_check(data, column, title=None, include_missing=True)

绘制序列并标注其单调性。

创建折线图可视化指定列的值分布, 并在图上标注单调性检验结果。

参数:

data : pd.DataFrame 包含数据的数据框 column : str 要绑制的列名 title : str, optional 图表标题,默认为None(自动生成) include_missing : bool, optional 是否包含缺失值处理,默认为True

返回:

None 直接显示图表

示例:

plot_monotonicity_check(df, 'woe_values')

源代码位于: Modeling_Tool/WOE/WOE_Tool.py
def plot_monotonicity_check(data, column, title=None, include_missing=True):
    """绘制序列并标注其单调性。

    创建折线图可视化指定列的值分布,
    并在图上标注单调性检验结果。

    参数:
    -----------
    data : pd.DataFrame
        包含数据的数据框
    column : str
        要绑制的列名
    title : str, optional
        图表标题,默认为None(自动生成)
    include_missing : bool, optional
        是否包含缺失值处理,默认为True

    返回:
    --------
    None
        直接显示图表

    示例:
    --------
    >>> plot_monotonicity_check(df, 'woe_values')
    """
    import matplotlib.pyplot as plt

    series = data[column]

    # 检查单调性
    if include_missing:
        is_mono, direction = is_monotonic(
            data.iloc[1:, :], "AVG_BAD", strict=True, handle_nan='drop'
        )
    else:
        is_mono, direction = is_monotonic(data, "AVG_BAD", strict=True, handle_nan='drop')

    # 创建图表
    plt.figure(figsize=(10, 6))
    plt.plot(series.index, series.values, 'bo-', linewidth=2, markersize=6)

    # 添加标题和标签
    if title is None:
        title = f"Monotonicity Check: {'Strict' if is_mono else 'Not'} Monotonic {direction if is_mono else ''}"
    plt.title(title, fontsize=14)
    plt.xlabel('Index')
    plt.ylabel('Value')

    # 添加网格
    plt.grid(True, alpha=0.3)

    # 显示单调性信息
    plt.text(
        0.02, 0.98,
        f"Strict Monotonic: {is_mono}\n Direction: {direction}",
        transform=plt.gca().transAxes,
        verticalalignment='top',
        bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.8)
    )

    plt.tight_layout()
    plt.show()

woe_transform

woe_transform(train_df, var, dep, nbins, oot_df=None, chi2_config=None, tree_binning_seed=None, precision=5, min_bin_prop=0.05, include_missing=False, equal_freq=True, ascending=True, fillna=-999999, spec_values=None, drop_bin_info=True, ret_woe_table=True, check_monotonicity=False)

将变量转换为WOE值。

对单个变量进行分箱并计算WOE值,支持训练集和验证集的转换。 基于WOETransformer类实现。

参数:

train_df : pd.DataFrame 训练数据集 var : str 待转换的变量名 dep : str 目标变量(因变量)名 nbins : int 分箱数量 oot_df : pd.DataFrame, optional 验证/测试数据集,默认为None chi2_config : tuple, optional 卡方分箱配置,(init_bins, p_value)元组,默认为None tree_binning_seed : int, optional 决策树分箱随机种子,默认为None precision : int, optional 计算精度,默认为5 min_bin_prop : float, optional 每个分箱的最小样本比例,默认为0.05 include_missing : bool, optional 是否将缺失值作为单独分箱,默认为False equal_freq : bool, optional 是否使用等频分箱,默认为True ascending : bool, optional 是否升序排列,默认为True fillna : int/float, optional 缺失值填充值,默认为-999999 spec_values : list, optional 特殊值列表,默认为None drop_bin_info : bool, optional 是否删除中间分箱信息列,默认为True ret_woe_table : bool, optional 是否返回WOE映射表,默认为True check_monotonicity : bool, optional 是否检查单调性,默认为False

返回:

tuple/list/pd.DataFrame 根据参数返回不同的组合: - ret_woe_table=True, oot_df=None: (train_res, train_woe_table) - ret_woe_table=True, oot_df不为None: (train_res, oot_res, train_woe_table) - ret_woe_table=False, oot_df不为None: (train_res, oot_res) - ret_woe_table=False, oot_df=None: train_res

示例:

train_res, woe_table = woe_transform(df, 'age', 'target', nbins=10)

源代码位于: Modeling_Tool/WOE/WOE_Tool.py
def woe_transform(train_df, var, dep, nbins, oot_df=None, chi2_config=None, tree_binning_seed=None,
                  precision=5, min_bin_prop=0.05, include_missing=False, equal_freq=True,
                  ascending=True, fillna=-999999, spec_values=None, drop_bin_info=True,
                  ret_woe_table=True, check_monotonicity=False):
    """将变量转换为WOE值。

    对单个变量进行分箱并计算WOE值,支持训练集和验证集的转换。
    基于WOETransformer类实现。

    参数:
    -----------
    train_df : pd.DataFrame
        训练数据集
    var : str
        待转换的变量名
    dep : str
        目标变量(因变量)名
    nbins : int
        分箱数量
    oot_df : pd.DataFrame, optional
        验证/测试数据集,默认为None
    chi2_config : tuple, optional
        卡方分箱配置,(init_bins, p_value)元组,默认为None
    tree_binning_seed : int, optional
        决策树分箱随机种子,默认为None
    precision : int, optional
        计算精度,默认为5
    min_bin_prop : float, optional
        每个分箱的最小样本比例,默认为0.05
    include_missing : bool, optional
        是否将缺失值作为单独分箱,默认为False
    equal_freq : bool, optional
        是否使用等频分箱,默认为True
    ascending : bool, optional
        是否升序排列,默认为True
    fillna : int/float, optional
        缺失值填充值,默认为-999999
    spec_values : list, optional
        特殊值列表,默认为None
    drop_bin_info : bool, optional
        是否删除中间分箱信息列,默认为True
    ret_woe_table : bool, optional
        是否返回WOE映射表,默认为True
    check_monotonicity : bool, optional
        是否检查单调性,默认为False

    返回:
    --------
    tuple/list/pd.DataFrame
        根据参数返回不同的组合:
        - ret_woe_table=True, oot_df=None: (train_res, train_woe_table)
        - ret_woe_table=True, oot_df不为None: (train_res, oot_res, train_woe_table)
        - ret_woe_table=False, oot_df不为None: (train_res, oot_res)
        - ret_woe_table=False, oot_df=None: train_res

    示例:
    --------
    >>> train_res, woe_table = woe_transform(df, 'age', 'target', nbins=10)
    """
    if spec_values is None:
        spec_values = []

    transformer = WOETransformer(
        nbins=nbins,
        precision=precision,
        min_bin_prop=min_bin_prop,
        include_missing=include_missing,
        equal_freq=equal_freq,
        fillna=fillna,
        chi2_config=chi2_config,
        tree_binning_seed=tree_binning_seed,
        spec_values=spec_values,
        drop_bin_info=drop_bin_info,
        ret_woe_table=ret_woe_table
    )
    return transformer.transform_single(
        train_df=train_df,
        var=var,
        dep=dep,
        oot_df=oot_df,
        check_monotonicity_flag=check_monotonicity
    )

woe_transformation

woe_transformation(train_df, varlist, dep, oot_df=None, nbins=10, chi2_config=None, tree_binning_seed=None, precision=5, min_bin_prop=0.05, include_missing=False, equal_freq=True, fillna=-999999, spec_values=None, drop_bin_info=True, ret_woe_table=True)

对变量列表进行WOE转换。

批量对多个变量进行WOE分箱和转换,支持训练集和验证集。 基于WOETransformer类实现。

参数:

train_df : pd.DataFrame 训练数据集 varlist : list 待转换的变量名列表 dep : str 目标变量(因变量)名 oot_df : pd.DataFrame, optional 验证/测试数据集,默认为None nbins : int, optional 分箱数量,默认为10 chi2_config : tuple, optional 卡方分箱配置,(init_bins, p_value)元组,默认为None tree_binning_seed : int, optional 决策树分箱随机种子,默认为None precision : int, optional 计算精度,默认为5 min_bin_prop : float, optional 每个分箱的最小样本比例,默认为0.05 include_missing : bool, optional 是否将缺失值作为单独分箱,默认为False equal_freq : bool, optional 是否使用等频分箱,默认为True fillna : int/float, optional 缺失值填充值,默认为-999999 spec_values : list, optional 特殊值列表,默认为None drop_bin_info : bool, optional 是否删除中间分箱信息列,默认为True ret_woe_table : bool, optional 是否返回WOE映射表,默认为True

返回:

tuple (结果字典, train_woe_table) 元组。 结果字典包含'TRAIN'键,验证集通过'OOT'键(当oot_df不为None时)

示例:

result, woe_table = woe_transformation(df, ['var1', 'var2'], 'target')

源代码位于: Modeling_Tool/WOE/WOE_Tool.py
def woe_transformation(train_df, varlist, dep, oot_df=None, nbins=10, chi2_config=None,
                       tree_binning_seed=None, precision=5, min_bin_prop=0.05,
                       include_missing=False, equal_freq=True, fillna=-999999,
                       spec_values=None, drop_bin_info=True, ret_woe_table=True):
    """对变量列表进行WOE转换。

    批量对多个变量进行WOE分箱和转换,支持训练集和验证集。
    基于WOETransformer类实现。

    参数:
    -----------
    train_df : pd.DataFrame
        训练数据集
    varlist : list
        待转换的变量名列表
    dep : str
        目标变量(因变量)名
    oot_df : pd.DataFrame, optional
        验证/测试数据集,默认为None
    nbins : int, optional
        分箱数量,默认为10
    chi2_config : tuple, optional
        卡方分箱配置,(init_bins, p_value)元组,默认为None
    tree_binning_seed : int, optional
        决策树分箱随机种子,默认为None
    precision : int, optional
        计算精度,默认为5
    min_bin_prop : float, optional
        每个分箱的最小样本比例,默认为0.05
    include_missing : bool, optional
        是否将缺失值作为单独分箱,默认为False
    equal_freq : bool, optional
        是否使用等频分箱,默认为True
    fillna : int/float, optional
        缺失值填充值,默认为-999999
    spec_values : list, optional
        特殊值列表,默认为None
    drop_bin_info : bool, optional
        是否删除中间分箱信息列,默认为True
    ret_woe_table : bool, optional
        是否返回WOE映射表,默认为True

    返回:
    --------
    tuple
        (结果字典, train_woe_table) 元组。
        结果字典包含'TRAIN'键,验证集通过'OOT'键(当oot_df不为None时)

    示例:
    --------
    >>> result, woe_table = woe_transformation(df, ['var1', 'var2'], 'target')
    """
    if spec_values is None:
        spec_values = []

    transformer = WOETransformer(
        nbins=nbins,
        precision=precision,
        min_bin_prop=min_bin_prop,
        include_missing=include_missing,
        equal_freq=equal_freq,
        fillna=fillna,
        chi2_config=chi2_config,
        tree_binning_seed=tree_binning_seed,
        spec_values=spec_values,
        drop_bin_info=drop_bin_info,
        ret_woe_table=ret_woe_table
    )
    return transformer.transform(train_df, varlist, dep, oot_df)

mapping_woe

mapping_woe(data, varlist, woe_mapping_table, suffix='_woe', drop_bin_info=True)

基于WOE映射表批量映射WOE值。

使用预计算的WOE映射表对多个变量进行WOE转换。

参数:

data : pd.DataFrame 输入的数据框 varlist : list 待映射的变量名列表 woe_mapping_table : pd.DataFrame WOE映射表 suffix : str, optional 变量名后缀,默认为'_woe' drop_bin_info : bool, optional 是否删除中间分箱信息列,默认为True

返回:

pd.DataFrame 映射后的数据框

示例:

result = mapping_woe(df, ['var1', 'var2'], woe_table)

源代码位于: Modeling_Tool/WOE/WOE_Tool.py
def mapping_woe(data, varlist, woe_mapping_table, suffix="_woe", drop_bin_info = True):
    """基于WOE映射表批量映射WOE值。

    使用预计算的WOE映射表对多个变量进行WOE转换。

    参数:
    -----------
    data : pd.DataFrame
        输入的数据框
    varlist : list
        待映射的变量名列表
    woe_mapping_table : pd.DataFrame
        WOE映射表
    suffix : str, optional
        变量名后缀,默认为'_woe'
    drop_bin_info : bool, optional
        是否删除中间分箱信息列,默认为True

    返回:
    --------
    pd.DataFrame
        映射后的数据框

    示例:
    --------
    >>> result = mapping_woe(df, ['var1', 'var2'], woe_table)
    """
    transformer = WOEMappingTransformer(
        woe_mapping_table=woe_mapping_table,
        suffix=suffix
#         drop_bin_info=drop_bin_info
    )
    res = data.copy()
    for var in varlist:
        res = _mapping_woe_single_var(data=res, var=var, woe_mapping_table=woe_mapping_table,
                                       suffix=suffix, drop_bin_info=drop_bin_info)
    return res

绑图工具 — WOE_Plot_Tool

WOE_Plot_Tool

WOEPlotter

WOE绘图类,封装单个变量和分组变量的WOE图表绘制功能。

参数:

名称 类型 描述 默认
var_rename str

变量重命名,用于图表标题显示,默认为None

None
to_show bool

是否展示图片,默认为True

True
save_dir str

结果图片存放的文件夹路径,默认为None

None
fig_name str

保存图片的文件名,默认为'var.png'

'var.png'
grp_name str

分组字段名称,默认为None

None

属性:

名称 类型 描述
var_rename str

变量重命名

to_show bool

是否展示图片

save_dir str

图片保存目录

fig_name str

图片文件名

grp_name str

分组字段名称

示例:

>>> plotter = WOEPlotter(save_dir='./output', var_rename='年龄')
>>> plotter.plot(woe_df)
>>> plotter.plot_group(woe_grp_df, grp_name='城市')
源代码位于: Modeling_Tool/WOE/WOE_Plot_Tool.py
class WOEPlotter:
    """
    WOE绘图类,封装单个变量和分组变量的WOE图表绘制功能。

    Parameters
    ----------
    var_rename : str, optional
        变量重命名,用于图表标题显示,默认为None
    to_show : bool, optional
        是否展示图片,默认为True
    save_dir : str, optional
        结果图片存放的文件夹路径,默认为None
    fig_name : str, optional
        保存图片的文件名,默认为'var.png'
    grp_name : str, optional
        分组字段名称,默认为None

    Attributes
    ----------
    var_rename : str
        变量重命名
    to_show : bool
        是否展示图片
    save_dir : str
        图片保存目录
    fig_name : str
        图片文件名
    grp_name : str
        分组字段名称

    Examples
    --------
    >>> plotter = WOEPlotter(save_dir='./output', var_rename='年龄')
    >>> plotter.plot(woe_df)
    >>> plotter.plot_group(woe_grp_df, grp_name='城市')
    """

    def __init__(self, var_rename=None, to_show=True, save_dir=None, fig_name='var.png', grp_name=None):
        """
        初始化WOEPlotter实例。

        Parameters
        ----------
        var_rename : str, optional
            变量重命名,用于图表标题显示
        to_show : bool, optional
            是否展示图片,默认为True
        save_dir : str, optional
            结果图片存放的文件夹路径
        fig_name : str, optional
            保存图片的文件名,默认为'var.png'
        grp_name : str, optional
            分组字段名称
        """
        self.var_rename = var_rename
        self.to_show = to_show
        self.save_dir = save_dir
        self.fig_name = fig_name
        self.grp_name = grp_name

    def plot(self, woe_df, var_rename=None, to_show=None, save_dir=None, fig_name=None):
        """
        绘制单个变量的WOE图。

        Parameters
        ----------
        woe_df : pandas.DataFrame
            WOE表,包含变量、分箱等信息
        var_rename : str, optional
            变量重命名,会覆盖实例属性
        to_show : bool, optional
            是否展示图片,会覆盖实例属性
        save_dir : str, optional
            图片保存目录,会覆盖实例属性
        fig_name : str, optional
            图片文件名,会覆盖实例属性

        Returns
        -------
        None

        Examples
        --------
        >>> plotter = WOEPlotter(save_dir='./output')
        >>> plotter.plot(woe_df, var_rename='年龄')
        """
        # 使用实例属性作为默认值,允许覆盖
        _var_rename = var_rename if var_rename is not None else self.var_rename
        _to_show = to_show if to_show is not None else self.to_show
        _save_dir = save_dir if save_dir is not None else self.save_dir
        _fig_name = fig_name if fig_name is not None else self.fig_name

        plot_woe(woe_df, _var_rename, _to_show, _save_dir, _fig_name)

    def plot_group(self, woe_grp_df, grp_name=None, var_rename=None, to_show=None, save_dir=None, fig_name=None):
        """
        绘制分组变量的WOE图。

        Parameters
        ----------
        woe_grp_df : pandas.DataFrame
            分组WOE表,包含按组别分组后的WOE信息
        grp_name : str, optional
            分组字段名称,会覆盖实例属性
        var_rename : str, optional
            变量重命名,会覆盖实例属性
        to_show : bool, optional
            是否展示图片,会覆盖实例属性
        save_dir : str, optional
            图片保存目录,会覆盖实例属性
        fig_name : str, optional
            图片文件名,会覆盖实例属性

        Returns
        -------
        None

        Examples
        --------
        >>> plotter = WOEPlotter(save_dir='./output')
        >>> plotter.plot_group(woe_grp_df, grp_name='城市')
        """
        _grp_name = grp_name if grp_name is not None else self.grp_name
        _var_rename = var_rename if var_rename is not None else self.var_rename
        _to_show = to_show if to_show is not None else self.to_show
        _save_dir = save_dir if save_dir is not None else self.save_dir
        _fig_name = fig_name if fig_name is not None else self.fig_name

        plot_woe_group(woe_grp_df, _grp_name, _var_rename, _to_show, _save_dir, _fig_name)

plot

plot(woe_df, var_rename=None, to_show=None, save_dir=None, fig_name=None)

绘制单个变量的WOE图。

参数:

名称 类型 描述 默认
woe_df DataFrame

WOE表,包含变量、分箱等信息

必需
var_rename str

变量重命名,会覆盖实例属性

None
to_show bool

是否展示图片,会覆盖实例属性

None
save_dir str

图片保存目录,会覆盖实例属性

None
fig_name str

图片文件名,会覆盖实例属性

None

返回:

类型 描述
None

示例:

>>> plotter = WOEPlotter(save_dir='./output')
>>> plotter.plot(woe_df, var_rename='年龄')
源代码位于: Modeling_Tool/WOE/WOE_Plot_Tool.py
def plot(self, woe_df, var_rename=None, to_show=None, save_dir=None, fig_name=None):
    """
    绘制单个变量的WOE图。

    Parameters
    ----------
    woe_df : pandas.DataFrame
        WOE表,包含变量、分箱等信息
    var_rename : str, optional
        变量重命名,会覆盖实例属性
    to_show : bool, optional
        是否展示图片,会覆盖实例属性
    save_dir : str, optional
        图片保存目录,会覆盖实例属性
    fig_name : str, optional
        图片文件名,会覆盖实例属性

    Returns
    -------
    None

    Examples
    --------
    >>> plotter = WOEPlotter(save_dir='./output')
    >>> plotter.plot(woe_df, var_rename='年龄')
    """
    # 使用实例属性作为默认值,允许覆盖
    _var_rename = var_rename if var_rename is not None else self.var_rename
    _to_show = to_show if to_show is not None else self.to_show
    _save_dir = save_dir if save_dir is not None else self.save_dir
    _fig_name = fig_name if fig_name is not None else self.fig_name

    plot_woe(woe_df, _var_rename, _to_show, _save_dir, _fig_name)

plot_group

plot_group(woe_grp_df, grp_name=None, var_rename=None, to_show=None, save_dir=None, fig_name=None)

绘制分组变量的WOE图。

参数:

名称 类型 描述 默认
woe_grp_df DataFrame

分组WOE表,包含按组别分组后的WOE信息

必需
grp_name str

分组字段名称,会覆盖实例属性

None
var_rename str

变量重命名,会覆盖实例属性

None
to_show bool

是否展示图片,会覆盖实例属性

None
save_dir str

图片保存目录,会覆盖实例属性

None
fig_name str

图片文件名,会覆盖实例属性

None

返回:

类型 描述
None

示例:

>>> plotter = WOEPlotter(save_dir='./output')
>>> plotter.plot_group(woe_grp_df, grp_name='城市')
源代码位于: Modeling_Tool/WOE/WOE_Plot_Tool.py
def plot_group(self, woe_grp_df, grp_name=None, var_rename=None, to_show=None, save_dir=None, fig_name=None):
    """
    绘制分组变量的WOE图。

    Parameters
    ----------
    woe_grp_df : pandas.DataFrame
        分组WOE表,包含按组别分组后的WOE信息
    grp_name : str, optional
        分组字段名称,会覆盖实例属性
    var_rename : str, optional
        变量重命名,会覆盖实例属性
    to_show : bool, optional
        是否展示图片,会覆盖实例属性
    save_dir : str, optional
        图片保存目录,会覆盖实例属性
    fig_name : str, optional
        图片文件名,会覆盖实例属性

    Returns
    -------
    None

    Examples
    --------
    >>> plotter = WOEPlotter(save_dir='./output')
    >>> plotter.plot_group(woe_grp_df, grp_name='城市')
    """
    _grp_name = grp_name if grp_name is not None else self.grp_name
    _var_rename = var_rename if var_rename is not None else self.var_rename
    _to_show = to_show if to_show is not None else self.to_show
    _save_dir = save_dir if save_dir is not None else self.save_dir
    _fig_name = fig_name if fig_name is not None else self.fig_name

    plot_woe_group(woe_grp_df, _grp_name, _var_rename, _to_show, _save_dir, _fig_name)

WOEAnalyzer

WOE分析器类,封装WOE表计算和映射汇总功能。

参数:

名称 类型 描述 默认
ref_woe_table DataFrame

参考WOE映射表,包含各变量的标准WOE分箱信息,默认为None

None
tgt_name str

目标变量名称,用于计算好坏样本比例,默认为None

None

属性:

名称 类型 描述
ref_woe_table DataFrame

参考WOE映射表

tgt_name str

目标变量名称

示例:

>>> analyzer = WOEAnalyzer(ref_woe_table, tgt_name='default')
>>> woe_table, woe_dict = analyzer.get_woe_table(binning_res, 'age')
>>> summary = analyzer.get_summary(data, 'income')
源代码位于: Modeling_Tool/WOE/WOE_Plot_Tool.py
class WOEAnalyzer:
    """
    WOE分析器类,封装WOE表计算和映射汇总功能。

    Parameters
    ----------
    ref_woe_table : pandas.DataFrame, optional
        参考WOE映射表,包含各变量的标准WOE分箱信息,默认为None
    tgt_name : str, optional
        目标变量名称,用于计算好坏样本比例,默认为None

    Attributes
    ----------
    ref_woe_table : pandas.DataFrame
        参考WOE映射表
    tgt_name : str
        目标变量名称

    Examples
    --------
    >>> analyzer = WOEAnalyzer(ref_woe_table, tgt_name='default')
    >>> woe_table, woe_dict = analyzer.get_woe_table(binning_res, 'age')
    >>> summary = analyzer.get_summary(data, 'income')
    """

    def __init__(self, ref_woe_table=None, tgt_name=None):
        """
        初始化WOEAnalyzer实例。

        Parameters
        ----------
        ref_woe_table : pandas.DataFrame, optional
            参考WOE映射表
        tgt_name : str, optional
            目标变量名称
        """
        self.ref_woe_table = ref_woe_table
        self.tgt_name = tgt_name

    def get_woe_table(self, binning_res, var, dep=None):
        """
        根据分箱结果计算并返回WOE表和WOE映射字典。

        Parameters
        ----------
        binning_res : pandas.DataFrame
            包含分箱结果的数据框
        var : str
            变量名称
        dep : str, optional
            目标变量名称,会覆盖实例属性tgt_name

        Returns
        -------
        tuple
            - woe_table (pandas.DataFrame): WOE表
            - woe_mapping_dict (dict): WOE映射字典

        Examples
        --------
        >>> analyzer = WOEAnalyzer(tgt_name='default')
        >>> woe_table, woe_dict = analyzer.get_woe_table(binning_res, 'age')
        """
        _dep = dep if dep is not None else self.tgt_name
        return get_woe_table(binning_res, var, _dep)

    def get_mapped_woe_summary_single(self, data, var, ref_woe_table=None, tgt_name=None):
        """
        根据参考WOE映射表对单个变量生成WOE汇总表。

        Parameters
        ----------
        data : pandas.DataFrame
            输入数据
        var : str
            变量名称
        ref_woe_table : pandas.DataFrame, optional
            参考WOE表,会覆盖实例属性
        tgt_name : str, optional
            目标变量名称,会覆盖实例属性

        Returns
        -------
        pandas.DataFrame
            变量WOE汇总表

        Examples
        --------
        >>> analyzer = WOEAnalyzer(ref_woe_table, 'default')
        >>> summary = analyzer.get_mapped_woe_summary_single(data, 'income')
        """
        _ref_woe_table = ref_woe_table if ref_woe_table is not None else self.ref_woe_table
        _tgt_name = tgt_name if tgt_name is not None else self.tgt_name
        return get_mapped_woe_summary_single(data, var, _ref_woe_table, _tgt_name)

    def get_mapped_woe_summary_grp(self, data, var, ref_woe_table=None, tgt_name=None, grp_name=None):
        """
        获取分组后的单个变量WOE汇总表。

        Parameters
        ----------
        data : pandas.DataFrame
            输入数据
        var : str
            变量名称
        ref_woe_table : pandas.DataFrame, optional
            参考WOE表,会覆盖实例属性
        tgt_name : str, optional
            目标变量名称,会覆盖实例属性
        grp_name : str or list, optional
            分组字段名称

        Returns
        -------
        pandas.DataFrame
            分组后的变量WOE汇总表

        Examples
        --------
        >>> analyzer = WOEAnalyzer(ref_woe_table, 'default')
        >>> summary = analyzer.get_mapped_woe_summary_grp(data, 'age', grp_name='city')
        """
        _ref_woe_table = ref_woe_table if ref_woe_table is not None else self.ref_woe_table
        _tgt_name = tgt_name if tgt_name is not None else self.tgt_name
        return get_mapped_woe_summary_grp(data, var, _ref_woe_table, _tgt_name, grp_name)

    def get_mapped_woe_summary(self, data, ref_woe_table=None, tgt_name=None, varlist=None, grp_name=None):
        """
        获取多个变量的WOE汇总表。

        Parameters
        ----------
        data : pandas.DataFrame
            输入数据
        ref_woe_table : pandas.DataFrame, optional
            参考WOE表,会覆盖实例属性
        tgt_name : str, optional
            目标变量名称,会覆盖实例属性
        varlist : list, optional
            要计算的变量列表
        grp_name : str or list, optional
            分组字段名称

        Returns
        -------
        pandas.DataFrame
            包含所有变量WOE信息的汇总表

        Examples
        --------
        >>> analyzer = WOEAnalyzer(ref_woe_table, 'default')
        >>> summary = analyzer.get_mapped_woe_summary(data, varlist=['age', 'income'])
        """
        _ref_woe_table = ref_woe_table if ref_woe_table is not None else self.ref_woe_table
        _tgt_name = tgt_name if tgt_name is not None else self.tgt_name
        return get_mapped_woe_summary(data, _ref_woe_table, _tgt_name, varlist, grp_name)

    def align_bin_num(self, woe_table, grp_woe_df, grp_name):
        """
        对齐分组WOE表与参考WOE表的分箱编号。

        Parameters
        ----------
        woe_table : pandas.DataFrame
            参考WOE表
        grp_woe_df : pandas.DataFrame
            分组WOE表
        grp_name : str or list
            分组字段名称

        Returns
        -------
        pandas.DataFrame
            对齐后的分组WOE表

        Examples
        --------
        >>> analyzer = WOEAnalyzer()
        >>> aligned = analyzer.align_bin_num(ref_table, grp_df, 'city')
        """
        return align_bin_num(woe_table, grp_woe_df, grp_name)

    def get_bivar_graph(self, data, varlist, sep=None, ref_woe_table=None, save_dir=None, group=None, woe_suffix="_woe"):
        """
        生成双变量分析图表。

        Parameters
        ----------
        data : pandas.DataFrame
            输入数据
        varlist : list
            要分析的变量列表
        sep : str, optional
            目标变量名称,会覆盖实例属性tgt_name
        ref_woe_table : pandas.DataFrame, optional
            参考WOE表,会覆盖实例属性
        save_dir : str, optional
            图片保存目录
        group : str, optional
            分组字段名称
        woe_suffix : str, optional
            WOE变量后缀,默认为'_woe'

        Returns
        -------
        None

        Examples
        --------
        >>> analyzer = WOEAnalyzer(ref_woe_table, 'default')
        >>> analyzer.get_bivar_graph(data, ['age', 'income'], save_dir='./output', group='city')
        """
        _sep = sep if sep is not None else self.tgt_name
        _ref_woe_table = ref_woe_table if ref_woe_table is not None else self.ref_woe_table
        return get_bivar_graph(data, varlist, _sep, _ref_woe_table, save_dir, group, woe_suffix)

get_woe_table

get_woe_table(binning_res, var, dep=None)

根据分箱结果计算并返回WOE表和WOE映射字典。

参数:

名称 类型 描述 默认
binning_res DataFrame

包含分箱结果的数据框

必需
var str

变量名称

必需
dep str

目标变量名称,会覆盖实例属性tgt_name

None

返回:

类型 描述
tuple
  • woe_table (pandas.DataFrame): WOE表
  • woe_mapping_dict (dict): WOE映射字典

示例:

>>> analyzer = WOEAnalyzer(tgt_name='default')
>>> woe_table, woe_dict = analyzer.get_woe_table(binning_res, 'age')
源代码位于: Modeling_Tool/WOE/WOE_Plot_Tool.py
def get_woe_table(self, binning_res, var, dep=None):
    """
    根据分箱结果计算并返回WOE表和WOE映射字典。

    Parameters
    ----------
    binning_res : pandas.DataFrame
        包含分箱结果的数据框
    var : str
        变量名称
    dep : str, optional
        目标变量名称,会覆盖实例属性tgt_name

    Returns
    -------
    tuple
        - woe_table (pandas.DataFrame): WOE表
        - woe_mapping_dict (dict): WOE映射字典

    Examples
    --------
    >>> analyzer = WOEAnalyzer(tgt_name='default')
    >>> woe_table, woe_dict = analyzer.get_woe_table(binning_res, 'age')
    """
    _dep = dep if dep is not None else self.tgt_name
    return get_woe_table(binning_res, var, _dep)

get_mapped_woe_summary_single

get_mapped_woe_summary_single(data, var, ref_woe_table=None, tgt_name=None)

根据参考WOE映射表对单个变量生成WOE汇总表。

参数:

名称 类型 描述 默认
data DataFrame

输入数据

必需
var str

变量名称

必需
ref_woe_table DataFrame

参考WOE表,会覆盖实例属性

None
tgt_name str

目标变量名称,会覆盖实例属性

None

返回:

类型 描述
DataFrame

变量WOE汇总表

示例:

>>> analyzer = WOEAnalyzer(ref_woe_table, 'default')
>>> summary = analyzer.get_mapped_woe_summary_single(data, 'income')
源代码位于: Modeling_Tool/WOE/WOE_Plot_Tool.py
def get_mapped_woe_summary_single(self, data, var, ref_woe_table=None, tgt_name=None):
    """
    根据参考WOE映射表对单个变量生成WOE汇总表。

    Parameters
    ----------
    data : pandas.DataFrame
        输入数据
    var : str
        变量名称
    ref_woe_table : pandas.DataFrame, optional
        参考WOE表,会覆盖实例属性
    tgt_name : str, optional
        目标变量名称,会覆盖实例属性

    Returns
    -------
    pandas.DataFrame
        变量WOE汇总表

    Examples
    --------
    >>> analyzer = WOEAnalyzer(ref_woe_table, 'default')
    >>> summary = analyzer.get_mapped_woe_summary_single(data, 'income')
    """
    _ref_woe_table = ref_woe_table if ref_woe_table is not None else self.ref_woe_table
    _tgt_name = tgt_name if tgt_name is not None else self.tgt_name
    return get_mapped_woe_summary_single(data, var, _ref_woe_table, _tgt_name)

get_mapped_woe_summary_grp

get_mapped_woe_summary_grp(data, var, ref_woe_table=None, tgt_name=None, grp_name=None)

获取分组后的单个变量WOE汇总表。

参数:

名称 类型 描述 默认
data DataFrame

输入数据

必需
var str

变量名称

必需
ref_woe_table DataFrame

参考WOE表,会覆盖实例属性

None
tgt_name str

目标变量名称,会覆盖实例属性

None
grp_name str or list

分组字段名称

None

返回:

类型 描述
DataFrame

分组后的变量WOE汇总表

示例:

>>> analyzer = WOEAnalyzer(ref_woe_table, 'default')
>>> summary = analyzer.get_mapped_woe_summary_grp(data, 'age', grp_name='city')
源代码位于: Modeling_Tool/WOE/WOE_Plot_Tool.py
def get_mapped_woe_summary_grp(self, data, var, ref_woe_table=None, tgt_name=None, grp_name=None):
    """
    获取分组后的单个变量WOE汇总表。

    Parameters
    ----------
    data : pandas.DataFrame
        输入数据
    var : str
        变量名称
    ref_woe_table : pandas.DataFrame, optional
        参考WOE表,会覆盖实例属性
    tgt_name : str, optional
        目标变量名称,会覆盖实例属性
    grp_name : str or list, optional
        分组字段名称

    Returns
    -------
    pandas.DataFrame
        分组后的变量WOE汇总表

    Examples
    --------
    >>> analyzer = WOEAnalyzer(ref_woe_table, 'default')
    >>> summary = analyzer.get_mapped_woe_summary_grp(data, 'age', grp_name='city')
    """
    _ref_woe_table = ref_woe_table if ref_woe_table is not None else self.ref_woe_table
    _tgt_name = tgt_name if tgt_name is not None else self.tgt_name
    return get_mapped_woe_summary_grp(data, var, _ref_woe_table, _tgt_name, grp_name)

get_mapped_woe_summary

get_mapped_woe_summary(data, ref_woe_table=None, tgt_name=None, varlist=None, grp_name=None)

获取多个变量的WOE汇总表。

参数:

名称 类型 描述 默认
data DataFrame

输入数据

必需
ref_woe_table DataFrame

参考WOE表,会覆盖实例属性

None
tgt_name str

目标变量名称,会覆盖实例属性

None
varlist list

要计算的变量列表

None
grp_name str or list

分组字段名称

None

返回:

类型 描述
DataFrame

包含所有变量WOE信息的汇总表

示例:

>>> analyzer = WOEAnalyzer(ref_woe_table, 'default')
>>> summary = analyzer.get_mapped_woe_summary(data, varlist=['age', 'income'])
源代码位于: Modeling_Tool/WOE/WOE_Plot_Tool.py
def get_mapped_woe_summary(self, data, ref_woe_table=None, tgt_name=None, varlist=None, grp_name=None):
    """
    获取多个变量的WOE汇总表。

    Parameters
    ----------
    data : pandas.DataFrame
        输入数据
    ref_woe_table : pandas.DataFrame, optional
        参考WOE表,会覆盖实例属性
    tgt_name : str, optional
        目标变量名称,会覆盖实例属性
    varlist : list, optional
        要计算的变量列表
    grp_name : str or list, optional
        分组字段名称

    Returns
    -------
    pandas.DataFrame
        包含所有变量WOE信息的汇总表

    Examples
    --------
    >>> analyzer = WOEAnalyzer(ref_woe_table, 'default')
    >>> summary = analyzer.get_mapped_woe_summary(data, varlist=['age', 'income'])
    """
    _ref_woe_table = ref_woe_table if ref_woe_table is not None else self.ref_woe_table
    _tgt_name = tgt_name if tgt_name is not None else self.tgt_name
    return get_mapped_woe_summary(data, _ref_woe_table, _tgt_name, varlist, grp_name)

align_bin_num

align_bin_num(woe_table, grp_woe_df, grp_name)

对齐分组WOE表与参考WOE表的分箱编号。

参数:

名称 类型 描述 默认
woe_table DataFrame

参考WOE表

必需
grp_woe_df DataFrame

分组WOE表

必需
grp_name str or list

分组字段名称

必需

返回:

类型 描述
DataFrame

对齐后的分组WOE表

示例:

>>> analyzer = WOEAnalyzer()
>>> aligned = analyzer.align_bin_num(ref_table, grp_df, 'city')
源代码位于: Modeling_Tool/WOE/WOE_Plot_Tool.py
def align_bin_num(self, woe_table, grp_woe_df, grp_name):
    """
    对齐分组WOE表与参考WOE表的分箱编号。

    Parameters
    ----------
    woe_table : pandas.DataFrame
        参考WOE表
    grp_woe_df : pandas.DataFrame
        分组WOE表
    grp_name : str or list
        分组字段名称

    Returns
    -------
    pandas.DataFrame
        对齐后的分组WOE表

    Examples
    --------
    >>> analyzer = WOEAnalyzer()
    >>> aligned = analyzer.align_bin_num(ref_table, grp_df, 'city')
    """
    return align_bin_num(woe_table, grp_woe_df, grp_name)

get_bivar_graph

get_bivar_graph(data, varlist, sep=None, ref_woe_table=None, save_dir=None, group=None, woe_suffix='_woe')

生成双变量分析图表。

参数:

名称 类型 描述 默认
data DataFrame

输入数据

必需
varlist list

要分析的变量列表

必需
sep str

目标变量名称,会覆盖实例属性tgt_name

None
ref_woe_table DataFrame

参考WOE表,会覆盖实例属性

None
save_dir str

图片保存目录

None
group str

分组字段名称

None
woe_suffix str

WOE变量后缀,默认为'_woe'

'_woe'

返回:

类型 描述
None

示例:

>>> analyzer = WOEAnalyzer(ref_woe_table, 'default')
>>> analyzer.get_bivar_graph(data, ['age', 'income'], save_dir='./output', group='city')
源代码位于: Modeling_Tool/WOE/WOE_Plot_Tool.py
def get_bivar_graph(self, data, varlist, sep=None, ref_woe_table=None, save_dir=None, group=None, woe_suffix="_woe"):
    """
    生成双变量分析图表。

    Parameters
    ----------
    data : pandas.DataFrame
        输入数据
    varlist : list
        要分析的变量列表
    sep : str, optional
        目标变量名称,会覆盖实例属性tgt_name
    ref_woe_table : pandas.DataFrame, optional
        参考WOE表,会覆盖实例属性
    save_dir : str, optional
        图片保存目录
    group : str, optional
        分组字段名称
    woe_suffix : str, optional
        WOE变量后缀,默认为'_woe'

    Returns
    -------
    None

    Examples
    --------
    >>> analyzer = WOEAnalyzer(ref_woe_table, 'default')
    >>> analyzer.get_bivar_graph(data, ['age', 'income'], save_dir='./output', group='city')
    """
    _sep = sep if sep is not None else self.tgt_name
    _ref_woe_table = ref_woe_table if ref_woe_table is not None else self.ref_woe_table
    return get_bivar_graph(data, varlist, _sep, _ref_woe_table, save_dir, group, woe_suffix)

plot_woe

plot_woe(woe_df, var_rename=None, to_show=True, save_dir=None, fig_name='var.png')

绘制变量的WOE图。

参数:

名称 类型 描述 默认
woe_df DataFrame

WOE表,包含变量、分箱等信息

必需
var_rename str

变量重命名,用于图表标题显示,默认为None

None
to_show bool

是否展示图片,默认为True

True
save_dir str

结果图片存放的文件夹路径,默认为None

None
fig_name str

保存图片的文件名,默认为'var.png'

'var.png'

返回:

类型 描述
None

函数直接绘制图表并可选保存或展示

示例:

>>> plot_woe(woe_df, var_rename='年龄', save_dir='./output')
源代码位于: Modeling_Tool/WOE/WOE_Plot_Tool.py
def plot_woe(woe_df, var_rename=None, to_show=True, save_dir=None, fig_name='var.png'):
    """
    绘制变量的WOE图。

    Parameters
    ----------
    woe_df : pandas.DataFrame
        WOE表,包含变量、分箱等信息
    var_rename : str, optional
        变量重命名,用于图表标题显示,默认为None
    to_show : bool, optional
        是否展示图片,默认为True
    save_dir : str, optional
        结果图片存放的文件夹路径,默认为None
    fig_name : str, optional
        保存图片的文件名,默认为'var.png'

    Returns
    -------
    None
        函数直接绘制图表并可选保存或展示

    Examples
    --------
    >>> plot_woe(woe_df, var_rename='年龄', save_dir='./output')
    """
    woe_df.columns = [x.lower() for x in woe_df.columns]
    woe_df[['woe', 'iv']] = woe_df[['woe', 'iv']].replace([np.inf, -np.inf], 0)

    woe_res = []
    for _, group in woe_df.groupby('var'):
        group['p'] = group['n']/group['n'].sum()
        woe_res.append(group)
    woe_res = pd.concat(woe_res)
    woe_df = woe_res.copy()

    var_name = woe_df["var"].iloc[0]
    iv = round(sum(woe_df["iv"]), 5)
    X = woe_df["bin_num"]
    xticks_list = [str(x)[:20]+"..." if len(str(x)) > 20 else str(x) for x in woe_df["bin_range"]]

    # 创建画布
    plt.figure(figsize=(12, 5), dpi=200) # 8,4
    grid = plt.GridSpec(1, 12, wspace=0.5, hspace=0.5)

    # 1.绘制Woe图
    ax1 = plt.subplot(grid[:, :5])
    # 绘制主坐标轴
    ax1.bar(X, woe_df["p"], color=palette["single_01"][0], label="0", align="edge", width=0.985, alpha=0.8)
    ax1.bar(X, woe_df["p"] * woe_df["avg_bad"], color=palette["single_01"][1], label="1", align="edge", width=0.985)

    plt.xticks(X+0.5, xticks_list, fontsize=6, rotation=45)
    plt.yticks(fontsize=6)
    ax1.axis(ymin=0.0, ymax=1)
    ax1.set_ylabel("Proportion", fontsize=6)
    ax1.legend(loc=2, fontsize=6)

    # 绘制次坐标轴
    ax1_2 = plt.twinx()
    plt.axis(ymin=np.min([-1, woe_df["woe"].min() * 1.1]), ymax=np.max([1, woe_df["woe"].max() * 1.1])) # 设置次轴区间
    plt.plot(X+0.5, woe_df["woe"], color="black", linewidth=1.5)
    for x, woe, avg_bad in zip(X, woe_df["woe"], woe_df["avg_bad"]):
        ax1_2.annotate(f"{woe:.3f} ({avg_bad:.2%})",
            xy=(x+0.5, woe),
            va="center",
            ha="center",
            bbox={"boxstyle": "round", "fc": "w"},
            fontsize=7
            )
    plt.yticks(fontsize=6)
    ax1_2.set_ylabel("WOE (TargetRate)", fontsize=6)

    # 绘制标题
    if bool(var_rename):
        plt.title(f"{str(var_rename)}: IV={iv:.3f}", fontsize=12, fontproperties=zhfont)
    else:
        plt.title(f"{var_name}: IV={iv:.3f}", fontsize=12, fontproperties=zhfont)

    # 2.绘制Woe表
    ax2 = plt.subplot(grid[:, 7:])
    ax2.set_axis_off()

    # 调整要展示的数据
    tbl = woe_df[["n", "p", "avg_bad", "lift", "woe",]].copy()
    tbl.loc["total"] = [tbl["n"].sum(), tbl["p"].sum(), woe_df["n_bad"].sum()/woe_df["n"].sum(), 1, 0]
    tbl["n"] = [f"{x:,.0f}" for x in tbl["n"]]
    tbl["p"] = [f"{x:.2%}" for x in tbl["p"]]
    tbl["avg_bad"] = [f"{x:.2%}" for x in tbl["avg_bad"]]
    tbl["lift"] = [f"{x:.2}" for x in tbl["lift"]]
    tbl["woe"] = [f"{x:.3f}" for x in tbl["woe"]]

    # 绘制表格
    rowls = xticks_list
    rowls.append("total")
    tbl = ax2.table(
        cellText=tbl[["n", "p", "avg_bad", "lift", "woe"]].values,
        colLabels=["N", "Prop", "BadRate", "Lift", "WOE"],
        rowLabels=rowls,
        colWidths=[0.2]*5,
        loc="center",
        cellLoc="right",
        rowLoc="right",
        colLoc="center",
        colColours=["#CCCCCC"]*5,
        rowColours=["#CCCCCC"]*len(rowls),
    )

    tbl.scale(1, 1.5)
    for key, cell in tbl.get_celld().items():
        row, col = key
        if row == 0 or col == -1:
             cell.set_text_props(font=zhfont, fontsize=7, fontstyle="oblique")
        if row > 0 and col > -1:
            cell.set_text_props(font=zhfont, fontsize=7)

    # 保存结果
    if bool(save_dir):
        plt.savefig(os.path.join(save_dir, fig_name), bbox_inches="tight")

    # 展示结果
    if to_show:
        plt.show()
    plt.close()

get_woe_table

get_woe_table(binning_res, var, dep)

根据分箱结果计算并返回WOE表和WOE映射字典。

参数:

名称 类型 描述 默认
binning_res DataFrame

包含分箱结果的数据框,应包含 bin_numbin_range

必需
var str

变量名称,用于标识要分析的特征列

必需
dep str

目标变量名称,用于计算好坏样本统计信息

必需

返回:

类型 描述
tuple
  • woe_table (pandas.DataFrame): 包含每个分箱的WOE、IV等统计信息的表格
  • woe_mapping_dict (dict): 将分箱范围映射到WOE值的字典

示例:

>>> woe_table, woe_dict = get_woe_table(binning_res, 'age', 'target')
源代码位于: Modeling_Tool/WOE/WOE_Plot_Tool.py
def get_woe_table(binning_res, var, dep):
    """
    根据分箱结果计算并返回WOE表和WOE映射字典。

    Parameters
    ----------
    binning_res : pandas.DataFrame
        包含分箱结果的数据框,应包含 _bin_num_{var} 和 _bin_range_{var} 列
    var : str
        变量名称,用于标识要分析的特征列
    dep : str
        目标变量名称,用于计算好坏样本统计信息

    Returns
    -------
    tuple
        - woe_table (pandas.DataFrame): 包含每个分箱的WOE、IV等统计信息的表格
        - woe_mapping_dict (dict): 将分箱范围映射到WOE值的字典

    Examples
    --------
    >>> woe_table, woe_dict = get_woe_table(binning_res, 'age', 'target')
    """
    # 计算每个分箱的统计信息
    woe_table = binning_res.groupby([f"_bin_num_{var}", f"_bin_range_{var}"], dropna = False)\
                         .agg(MIN = (var, "min"),
                              MAX = (var, "max"),
                              N = (f"_bin_num_{var}", "count"),
                              AVG_SCORE = (var, "mean"),
                              AVG_BAD = (dep, lambda x: ( (x==1).sum() / x.count()) ),
                              AVG_GOOD = (dep, lambda x: ( (x==0).sum() / x.count()) ),
                              N_BAD = (dep, "sum"),
                              N_GOOD = (dep, lambda x: (x==0).sum()))

    ## IV/WOE Calculation
    woe_table["BAD_PCT_PER_BIN"] = woe_table["N_BAD"] / woe_table["N_BAD"].sum()
    woe_table["GOOD_PCT_PER_BIN"] = woe_table["N_GOOD"] / woe_table["N_GOOD"].sum()
    woe_table["LIFT"] = woe_table['AVG_BAD'] / woe_table['AVG_BAD'].mean()
    woe_table["WOE"] = calc_woe(data = woe_table, bad_pct = "BAD_PCT_PER_BIN", good_pct = "GOOD_PCT_PER_BIN")
    woe_table["IV"] = calc_iv(data = woe_table, bad_pct = "BAD_PCT_PER_BIN", good_pct = "GOOD_PCT_PER_BIN")

    ## WOE Mapping Dictionary
    woe_table = woe_table.reset_index(drop=False)
    woe_mapping_dict = dict(zip(woe_table[f"_bin_range_{var}"], woe_table["WOE"]))

    return woe_table, woe_mapping_dict

get_mapped_woe_summary_single

get_mapped_woe_summary_single(data, var, ref_woe_table, tgt_name)

根据给定的参考WOE映射表,对单个变量生成WOE汇总表。

参数:

名称 类型 描述 默认
data DataFrame

输入数据,包含原始变量值

必需
var str

变量名称

必需
ref_woe_table DataFrame

参考WOE映射表,包含各变量的标准WOE分箱信息

必需
tgt_name str

目标变量名称,用于计算好坏样本比例

必需

返回:

类型 描述
DataFrame

与参考WOE表格式一致的变量WOE汇总表

示例:

>>> summary = get_mapped_woe_summary_single(data, 'income', ref_table, 'default')
源代码位于: Modeling_Tool/WOE/WOE_Plot_Tool.py
def get_mapped_woe_summary_single(data, var, ref_woe_table, tgt_name):
    """
    根据给定的参考WOE映射表,对单个变量生成WOE汇总表。

    Parameters
    ----------
    data : pandas.DataFrame
        输入数据,包含原始变量值
    var : str
        变量名称
    ref_woe_table : pandas.DataFrame
        参考WOE映射表,包含各变量的标准WOE分箱信息
    tgt_name : str
        目标变量名称,用于计算好坏样本比例

    Returns
    -------
    pandas.DataFrame
        与参考WOE表格式一致的变量WOE汇总表

    Examples
    --------
    >>> summary = get_mapped_woe_summary_single(data, 'income', ref_table, 'default')
    """

    ref_var_woe_table = ref_woe_table[ref_woe_table["VAR"] == var]

    df_mapped = mapping_woe(data, [var.replace("_woe", "")], ref_woe_table, suffix = "_woe", drop_bin_info = False)
    df_mapped.columns = [x.lower() for x in df_mapped.columns]

    if f"_bin_num_{var}" in df_mapped.columns:
        df_mapped = df_mapped.drop(columns = [f"_bin_num_{var}"])

    if f"_bin_range_{var}" in df_mapped.columns:
        df_mapped = df_mapped.drop(columns = [f"_bin_range_{var}"])

    df_mapped = df_mapped.rename(columns = {"_bin_num_": f"_bin_num_{var}",
                                            "_bin_range_": f"_bin_range_{var}"})

    var_woe_table = get_woe_table(df_mapped, var, dep = tgt_name)[0]
    var_woe_table["VAR"] = var

    var_woe_table = var_woe_table.rename(columns = {f"_bin_num_{var}": "bin_num", f"_bin_range_{var}": f"bin_range"})
    var_woe_table.columns = [x.upper() for x in var_woe_table.columns]
    fnlcollist = ref_woe_table.columns.tolist()
    return var_woe_table[fnlcollist]

get_mapped_woe_summary_grp

get_mapped_woe_summary_grp(data, var, ref_woe_table, tgt_name, grp_name=None)

获取分组后的单个变量WOE汇总表。

参数:

名称 类型 描述 默认
data DataFrame

输入数据,包含原始变量值和分组信息

必需
var str

变量名称

必需
ref_woe_table DataFrame

参考WOE映射表,包含各变量的标准WOE分箱信息

必需
tgt_name str

目标变量名称,用于计算好坏样本比例

必需
grp_name str or list

分组字段名称,用于按组别分别计算WOE,默认为None

None

返回:

类型 描述
DataFrame

分组后的变量WOE汇总表

Notes

如果数据中存在缺失值,会自动删除包含缺失值的记录并记录警告日志

示例:

>>> summary = get_mapped_woe_summary_grp(data, 'age', ref_table, 'default', 'city')
源代码位于: Modeling_Tool/WOE/WOE_Plot_Tool.py
def get_mapped_woe_summary_grp(data, var, ref_woe_table, tgt_name, grp_name=None):
    """
    获取分组后的单个变量WOE汇总表。

    Parameters
    ----------
    data : pandas.DataFrame
        输入数据,包含原始变量值和分组信息
    var : str
        变量名称
    ref_woe_table : pandas.DataFrame
        参考WOE映射表,包含各变量的标准WOE分箱信息
    tgt_name : str
        目标变量名称,用于计算好坏样本比例
    grp_name : str or list, optional
        分组字段名称,用于按组别分别计算WOE,默认为None

    Returns
    -------
    pandas.DataFrame
        分组后的变量WOE汇总表

    Notes
    -----
    如果数据中存在缺失值,会自动删除包含缺失值的记录并记录警告日志

    Examples
    --------
    >>> summary = get_mapped_woe_summary_grp(data, 'age', ref_table, 'default', 'city')
    """

    if data.query(f"{var} != {var}").shape[0] > 0:
        data = data.dropna(subset=[var])
        logging.info(f"WARNING: Found Missing Value in {var}, Missing Records Had Been Dropped!")

    if grp_name:
        fnl_res = []
        for grp, group in data.groupby(grp_name):
            grp_res = get_mapped_woe_summary_single(data = group, var = var, ref_woe_table = ref_woe_table, tgt_name = tgt_name)
            for i, g in enumerate(grp):
                grp_res[grp_name[i]] = g
            fnl_res.append(grp_res)

        return pd.concat(fnl_res)

    return get_mapped_woe_summary_single(data = data, var = var, ref_woe_table = ref_woe_table, tgt_name=tgt_name)

get_mapped_woe_summary

get_mapped_woe_summary(data, ref_woe_table, tgt_name, varlist=None, grp_name=None)

获取多个变量的WOE汇总表。

参数:

名称 类型 描述 默认
data DataFrame

输入数据,包含原始变量值

必需
ref_woe_table DataFrame

参考WOE映射表,包含各变量的标准WOE分箱信息

必需
tgt_name str

目标变量名称,用于计算好坏样本比例

必需
varlist list

要计算的变量列表,默认为None(使用参考表中的所有变量)

None
grp_name str or list

分组字段名称,用于按组别分别计算WOE,默认为None

None

返回:

类型 描述
DataFrame

包含所有变量WOE信息的汇总表

示例:

>>> summary = get_mapped_woe_summary(data, ref_table, 'default', varlist=['age', 'income'])
源代码位于: Modeling_Tool/WOE/WOE_Plot_Tool.py
def get_mapped_woe_summary(data, ref_woe_table, tgt_name, varlist=None, grp_name=None):
    """
    获取多个变量的WOE汇总表。

    Parameters
    ----------
    data : pandas.DataFrame
        输入数据,包含原始变量值
    ref_woe_table : pandas.DataFrame
        参考WOE映射表,包含各变量的标准WOE分箱信息
    tgt_name : str
        目标变量名称,用于计算好坏样本比例
    varlist : list, optional
        要计算的变量列表,默认为None(使用参考表中的所有变量)
    grp_name : str or list, optional
        分组字段名称,用于按组别分别计算WOE,默认为None

    Returns
    -------
    pandas.DataFrame
        包含所有变量WOE信息的汇总表

    Examples
    --------
    >>> summary = get_mapped_woe_summary(data, ref_table, 'default', varlist=['age', 'income'])
    """

    if varlist is None:
        varlist = ref_woe_table['VAR'].unique().tolist()

    fnl_res = []
    for var in varlist:
        var_res = get_mapped_woe_summary_grp(data, var, ref_woe_table, tgt_name, grp_name)
        fnl_res.append(var_res)

    return pd.concat(fnl_res)

plot_woe_group

plot_woe_group(woe_grp_df, grp_name=None, var_rename=None, to_show=True, save_dir=None, fig_name='var_group.png')

绘制变量的分组WOE图。

参数:

名称 类型 描述 默认
woe_grp_df DataFrame

分组WOE表,包含按组别分组后的WOE信息

必需
grp_name str

分组字段名称,用于区分不同组的WOE曲线,默认为None

None
var_rename str

变量重命名,用于图表标题显示,默认为None

None
to_show bool

是否展示图片,默认为True

True
save_dir str

结果图片存放的文件夹路径,默认为None

None
fig_name str

保存图片的文件名,默认为'var_group.png'

'var_group.png'

返回:

类型 描述
None

函数直接绘制图表并可选保存或展示

示例:

>>> plot_woe_group(woe_grp_df, grp_name='gender', save_dir='./output')
源代码位于: Modeling_Tool/WOE/WOE_Plot_Tool.py
def plot_woe_group(woe_grp_df, grp_name=None, var_rename=None, to_show=True, save_dir=None, fig_name="var_group.png"):
    """
    绘制变量的分组WOE图。

    Parameters
    ----------
    woe_grp_df : pandas.DataFrame
        分组WOE表,包含按组别分组后的WOE信息
    grp_name : str, optional
        分组字段名称,用于区分不同组的WOE曲线,默认为None
    var_rename : str, optional
        变量重命名,用于图表标题显示,默认为None
    to_show : bool, optional
        是否展示图片,默认为True
    save_dir : str, optional
        结果图片存放的文件夹路径,默认为None
    fig_name : str, optional
        保存图片的文件名,默认为'var_group.png'

    Returns
    -------
    None
        函数直接绘制图表并可选保存或展示

    Examples
    --------
    >>> plot_woe_group(woe_grp_df, grp_name='gender', save_dir='./output')
    """


    woe_grp_df.columns = [x.lower() for x in woe_grp_df.columns]
    woe_grp_df[['woe', 'iv']] = woe_grp_df[['woe', 'iv']].replace([np.inf, -np.inf], np.nan)

    var_name = woe_grp_df["var"].iloc[0]
    summary_df = woe_grp_df.groupby([grp_name]).agg({"iv": sum, "n": sum, "n_bad": sum})
    summary_df["avg_bad"] = summary_df["n_bad"] / summary_df["n"]

    iv_dict = {x: round(y, 5) for x, y in zip(summary_df.index, summary_df["iv"])}
    tr_dict = {x: round(y, 5) for x, y in zip(summary_df.index, summary_df["avg_bad"])}
    N_dict = {x: y for x, y in zip(summary_df.index, summary_df["n"])}
    X = woe_grp_df["bin_num"].drop_duplicates()
    Xticks = woe_grp_df.groupby(["bin_num"]).agg({"bin_range": max})["bin_range"]

    gs = list(set(woe_grp_df[grp_name]))
    gs.sort()
    n = len(gs)

    # 构建画布
    plt.figure(figsize=(12, 5), dpi=200) # 8,4
    grid = plt.GridSpec(1, 12, wspace=0.5, hspace=0.5)

    # 1.绘制Woe图
    ax1 = plt.subplot(grid[:, :5])

    # 绘制主坐标轴
    width = 0.9 / n
    alpha = 0.5 / n
    for i in range(n):
        g = gs[i]
        df_plot = woe_grp_df.loc[woe_grp_df[grp_name] == g, ].reset_index(drop=True)
        df_plot['p'] = df_plot['n'] / df_plot['n'].sum()
        ax1.bar(X + i * (0.01 + width), df_plot["p"], color=palette["single_01"][0], label=f"{g} N={N_dict[g]:,.0f} TR={tr_dict[g]:.2%}", align="edge", width=width, alpha=0.5 + alpha*(i+1))
        ax1.bar(X + i * (0.01 + width), df_plot["p"] * df_plot["avg_bad"], color=palette["red_list"][2], align="edge", width=width, alpha=1)

    xticks_list = [str(x)[:20]+"..." if len(str(x)) > 20 else str(x) for x in Xticks]
    plt.xticks(X+0.5, xticks_list, fontsize=6, rotation=45)
    plt.axis(ymin=0.0, ymax=1)
    plt.yticks(fontsize=6)
    plt.ylabel("Proportion", fontsize=6)
    plt.legend(loc=2, fontsize=6)

    # 绘制次坐标轴
    alpha = 0.8 / n
    ax1_2 = plt.twinx()
    for i in range(n):
        g = gs[i]
        df_plot = woe_grp_df.loc[woe_grp_df[grp_name] == g, ].reset_index(drop=True)
        plt.plot(X+0.5, df_plot["woe"], color=palette["grey"], linewidth=1, label=f"{g} IV={iv_dict[g]:.2f}", alpha=0.2 + alpha*(i+1))
    plt.axis(ymin=np.min([-1, woe_grp_df["woe"].min() * 1.1]), ymax=np.max([1, woe_grp_df["woe"].max() * 1.1])) # 设置次轴区间
    plt.yticks(fontsize=6)
    plt.ylabel("WOE", fontsize=6)
    plt.legend(loc=1, fontsize=6)

    # 绘制总标题
    if bool(var_rename):
        plt.title(f"{str(var_rename)}: IV_range={summary_df.iv.min():.2f}-{summary_df.iv.max():.2f}", fontsize=12, fontproperties=zhfont)
    else:
        plt.title(f"{var_name}: IV_range={summary_df.iv.min():.2f}-{summary_df.iv.max():.2f}", fontsize=12, fontproperties=zhfont)

    # 2.绘制Woe表
    ax2 = plt.subplot(grid[:, 7:])
    ax2.set_axis_off()

    # 调整要展示的数据
    tbl = pd.DataFrame()
    for i in range(n):
        g = gs[i]
        tbl.loc[:, g] = woe_grp_df.loc[woe_grp_df[grp_name] == g, "woe"]
        tbl.loc[:, g] = [f"{x:.3f}" for x in tbl[g]]

    # 绘制表格
    rowls = xticks_list
    colls = ["_".join([x, "woe"]) for x in gs]
    tbl = ax2.table(
        cellText=tbl.values,
        colLabels=colls,
        rowLabels=rowls,
        colWidths=[1.0 / n] * n,
        loc="center",
        cellLoc="right",
        rowLoc="right",
        colLoc="center",
        colColours=["#CCCCCC"] * n,
        rowColours=["#CCCCCC"] * len(rowls),
    )
    tbl.scale(1, 1.5)
    for key, cell in tbl.get_celld().items():
        row, col = key
        if row == 0 or col == -1:
             cell.set_text_props(font=zhfont, fontsize=7, fontstyle="oblique")
        if row > 0 and col > -1:
            cell.set_text_props(font=zhfont, fontsize=7)

    # 保存结果
    if bool(save_dir):
        plt.savefig(os.path.join(save_dir, fig_name), bbox_inches="tight")

    # 展示结果
    if to_show:
        plt.show()
    plt.close()

align_bin_num

align_bin_num(woe_table, grp_woe_df, grp_name)

对齐分组WOE表与参考WOE表的分箱编号。

参数:

名称 类型 描述 默认
woe_table DataFrame

参考WOE表,包含标准的分箱定义

必需
grp_woe_df DataFrame

分组WOE表,需要与参考表对齐

必需
grp_name str or list

分组字段名称

必需

返回:

类型 描述
DataFrame

对齐后的分组WOE表,BIN_NUM重新编号以避免空值

示例:

>>> aligned = align_bin_num(ref_woe_table, grp_woe_df, 'city')
源代码位于: Modeling_Tool/WOE/WOE_Plot_Tool.py
def align_bin_num(woe_table, grp_woe_df, grp_name):
    """
    对齐分组WOE表与参考WOE表的分箱编号。

    Parameters
    ----------
    woe_table : pandas.DataFrame
        参考WOE表,包含标准的分箱定义
    grp_woe_df : pandas.DataFrame
        分组WOE表,需要与参考表对齐
    grp_name : str or list
        分组字段名称

    Returns
    -------
    pandas.DataFrame
        对齐后的分组WOE表,BIN_NUM重新编号以避免空值

    Examples
    --------
    >>> aligned = align_bin_num(ref_woe_table, grp_woe_df, 'city')
    """

    left_data = woe_table[['BIN_RANGE', 'VAR']]
    left_data.columns = [x.upper() for x in left_data.columns]

    fnl_res = []
    for grp, group in grp_woe_df.groupby(grp_name):
        grp_res = left_data.merge(group, on = ['BIN_RANGE', 'VAR'], how = 'left')
        for i, g in enumerate(grp):
            grp_res[grp_name[i]] = g

        fnl_res.append(grp_res)
    fnl_res = pd.concat(fnl_res)


    ## Reset BIN_NUM to Avoid Null values in BIN_NUM column
    reset_bin_num_res = []
    for _, group_data in fnl_res.groupby(['VAR', *grp_name]):
        group_data = group_data.drop(columns = ['BIN_NUM'])
        group_data = group_data.reset_index(drop = True)
        group_data['BIN_NUM'] = (group_data.index + 1).tolist()
        reset_bin_num_res.append(group_data)
    reset_bin_num_res = pd.concat(reset_bin_num_res)
    reset_bin_num_res = reset_bin_num_res[['BIN_RANGE', 'VAR', 'BIN_NUM'] + [x for x in reset_bin_num_res.columns if x not in ['BIN_RANGE', 'VAR', 'BIN_NUM']]]

    return reset_bin_num_res

get_bivar_graph

get_bivar_graph(data, varlist, sep, ref_woe_table, save_dir, group=None, woe_suffix='_woe')

生成双变量分析图表,包括参考WOE图和分组WOE图。

参数:

名称 类型 描述 默认
data DataFrame

输入数据,包含原始变量值和分组信息

必需
varlist list

要分析的变量列表

必需
sep str

目标变量名称,用于计算好坏样本比例

必需
ref_woe_table DataFrame

参考WOE映射表,包含各变量的标准WOE分箱信息

必需
save_dir str

图片保存目录路径

必需
group str

分组字段名称,用于生成分组对比图,默认为None

None
woe_suffix str

WOE变量后缀,默认为'_woe'

'_woe'

返回:

类型 描述
None

函数直接保存图表到指定目录

示例:

>>> get_bivar_graph(data, ['age', 'income'], 'default', ref_table, './output', group='city')
源代码位于: Modeling_Tool/WOE/WOE_Plot_Tool.py
def get_bivar_graph(data, varlist, sep, ref_woe_table, save_dir, group=None, woe_suffix="_woe"):
    """
    生成双变量分析图表,包括参考WOE图和分组WOE图。

    Parameters
    ----------
    data : pandas.DataFrame
        输入数据,包含原始变量值和分组信息
    varlist : list
        要分析的变量列表
    sep : str
        目标变量名称,用于计算好坏样本比例
    ref_woe_table : pandas.DataFrame
        参考WOE映射表,包含各变量的标准WOE分箱信息
    save_dir : str
        图片保存目录路径
    group : str, optional
        分组字段名称,用于生成分组对比图,默认为None
    woe_suffix : str, optional
        WOE变量后缀,默认为'_woe'

    Returns
    -------
    None
        函数直接保存图表到指定目录

    Examples
    --------
    >>> get_bivar_graph(data, ['age', 'income'], 'default', ref_table, './output', group='city')
    """

#     try:
#         shutil.rmtree(save_dir)
#     except Exception as e:
#         mkdir_if_not_exist(save_dir)

    ################ Reference WOE Table Plot ##########################
    for var in varlist:
        var = var.replace(woe_suffix, "")
        woe_df = ref_woe_table[ref_woe_table['VAR'] == var]
        plot_woe(woe_df, to_show=False, save_dir=save_dir, fig_name = f"{var}.png")

    ################ Group WOE Table Plot ##########################
    grp_woe_res = get_mapped_woe_summary(data = data,
                                         ref_woe_table = ref_woe_table,
                                         tgt_name = sep,
                                         varlist = varlist,
                                         grp_name=[group])

    grp_woe_res = align_bin_num(woe_table = ref_woe_table, grp_woe_df = grp_woe_res, grp_name = [group])

    if group:

        for var in varlist:
            var = var.replace(woe_suffix, "")
            woe_grp_df = grp_woe_res[grp_woe_res['VAR'] == var]
            plot_woe_group(woe_grp_df, grp_name = group, to_show=False, save_dir=save_dir, fig_name = f"{var}_{group}.png")

    return None

贪心单调分箱器 — WOE_Monotone_Binner

大型模块

MonotoneWOEBinner 是本子包最重磅的类(3.3k 行),支持卡方初始化、类别聚类、Optuna 调参、ProcessPool 并行。

WOE_Monotone_Binner

WOE_Monotone_Binner.py

贪心单调 WOE 分箱器 — 可复用独立类

用法示例: from WOE_Monotone_Binner import MonotoneWOEBinner

binner = MonotoneWOEBinner(
    feature_cols=["age", "income", "score"],
    target_col="is_bad",
    n_init_bins=20,
    min_bin_size=0.03,
    special_values=[-1, -100],   # 这些值会单独成一箱
    cate_feats=["city_grade", "edu_level"],  # 已离散化的类别特征,直接算 WOE/IV,不做区间切分
)
binner.fit(train_df)                            # 训练拟合(贪心单调)
# 或开启卡方后合并
binner.fit(train_df, chi2_binning=True, chi2_p=0.95, chi2_init_size=2000)
# 类别特征:按坏率聚类合并坏率相近的类别(只作用于 cate_feats)
binner.refine_cate(max_bins=5)

# --- 或直接加载已有分箱结果,跳过 fit ---
bins_dict   = binner.get_final_bins()           # 获取分箱区间+WOE
edges_dict  = binner.get_bin_edges()            # 获取分箱边界列表(含 ±inf)
binner2 = MonotoneWOEBinner(feature_cols=[...], target_col="is_bad")
binner2.load_woe_bins(bins_dict)                # 直接加载

df_woe      = binner.apply_woe(test_df)         # WOE转换
binner.export_woe_report("woe_report.xlsx")     # 输出Excel报告(含图片Sheet)
binner.plot_woe_graph("woe_charts/")            # 输出每个特征的图
binner.plot_woe_graph("woe_charts/", group_name="month", _df_for_group=df)

依赖: pip install pandas numpy matplotlib xlsxwriter pillow (export_woe_report 通过 SuperModelingFactory 的 ExcelMaster 写出, 底层依赖 xlsxwriter + pillow)

MonotoneWOEBinner

贪心合并单调 WOE 分箱器(支持特殊值单独分箱 + 可选卡方后合并)。

参数:

名称 类型 描述 默认
feature_cols List[str]
必需
target_col str
必需
n_init_bins int
20
min_bin_size float
0.03
min_n_bins int
2
eps float
1e-06
missing_woe float
         注意:若 nan 已在 special_values 中则会独立计算 WOE,
         此参数仅对未列入 special_values 的 NaN 生效。
0.0
special_values 需要单独成箱的特殊值列表,如 [-1, -100, float('nan')]
         这些值会在 fit 时先被剔除,对剩余数据做单调分箱;
         最终在汇总表中单独追加为独立箱,WOE 独立计算。
         支持 nan / None / float('nan') 表示"缺失值单独分箱"。
         注意:仅作用于 feature_cols(数值特征),不影响 cate_feats。
None
cate_feats Optional[List[str]]
         这些特征**不做任何区间切分**——每个不同的取值直接作为一箱,
         直接计算其 WOE / IV,箱标签即类别取值本身。
         缺失值(NaN)若存在则单独归为 [Missing] 箱(独立计算 WOE)。
         与 feature_cols 互斥(同名时按 cate_feats 处理);卡方/决策树
         后合并(refine_chi2 / refine_dtree)对类别特征自动跳过。
         可用 refine_cate() 按坏率(bad rate)聚类合并坏率相近的类别。
None
bin_label_decimals 分箱区间边界值的小数点保留位数,默认 None(使用 .8g
             格式,最多 8 位有效数字)。设为正整数 N 时,边界值固定
             显示 N 位小数(:.Nf),例如 N=2 时 1234.5678 → 1234.57。
             注意:较低的精度会使 load_woe_bins(get_final_bins()) 的
             round-trip 边界稍有误差,但通常可忽略。
None
fit() 参数(传入 fit() 方法,不在 init 中设置)

chi2_binning : 是否在贪心单调分箱后再做卡方后合并,默认 False。 True 时:以贪心结果为起点,迭代合并卡方值最小的相邻箱对, 直到所有相邻对的卡方检验 p 值均 < (1 - chi2_p), 合并过程中严格保持 WOE 单调(不满足则跳过该对)。 chi2_p : 卡方检验置信度阈值,默认 0.99。相邻箱 p > (1-chi2_p) 时认为两箱分布无显著差异,可以合并。 chi2_init_size : 卡方计算时的全局 stratified 采样上限,默认 1000。 若普通行数 > chi2_init_size,则按 target 比例分层 抽样后再计算卡方,避免大数据集下卡方值虚高。

源代码位于: Modeling_Tool/WOE/WOE_Monotone_Binner.py
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
class MonotoneWOEBinner:
    """
    贪心合并单调 WOE 分箱器(支持特殊值单独分箱 + 可选卡方后合并)。

    Parameters
    ----------
    feature_cols   : 需要分箱的数值特征列名列表
    target_col     : 二分类目标变量列名(0=好,1=坏)
    n_init_bins    : 初始等频分箱数,默认 20
    min_bin_size   : 每箱最小样本占比,默认 0.03(3%)
    min_n_bins     : 最终分箱数下限(不含特殊值箱),默认 2
    eps            : 防止 log(0) 的微小量,默认 1e-6
    missing_woe    : 缺失值(NaN)对应的 WOE 填充值,默认 0.0(中性)
                     注意:若 nan 已在 special_values 中则会独立计算 WOE,
                     此参数仅对未列入 special_values 的 NaN 生效。
    special_values : 需要单独成箱的特殊值列表,如 [-1, -100, float('nan')]
                     这些值会在 fit 时先被剔除,对剩余数据做单调分箱;
                     最终在汇总表中单独追加为独立箱,WOE 独立计算。
                     支持 nan / None / float('nan') 表示"缺失值单独分箱"。
                     注意:仅作用于 feature_cols(数值特征),不影响 cate_feats。
    cate_feats     : 已离散化的类别(离散)特征列名列表,默认 None。
                     这些特征**不做任何区间切分**——每个不同的取值直接作为一箱,
                     直接计算其 WOE / IV,箱标签即类别取值本身。
                     缺失值(NaN)若存在则单独归为 [Missing] 箱(独立计算 WOE)。
                     与 feature_cols 互斥(同名时按 cate_feats 处理);卡方/决策树
                     后合并(refine_chi2 / refine_dtree)对类别特征自动跳过。
                     可用 refine_cate() 按坏率(bad rate)聚类合并坏率相近的类别。
    bin_label_decimals : 分箱区间边界值的小数点保留位数,默认 None(使用 .8g
                         格式,最多 8 位有效数字)。设为正整数 N 时,边界值固定
                         显示 N 位小数(:.Nf),例如 N=2 时 1234.5678 → 1234.57。
                         注意:较低的精度会使 load_woe_bins(get_final_bins()) 的
                         round-trip 边界稍有误差,但通常可忽略。

    fit() 参数(传入 fit() 方法,不在 __init__ 中设置)
    -------------------------------------------------------
    chi2_binning   : 是否在贪心单调分箱后再做卡方后合并,默认 False。
                     True 时:以贪心结果为起点,迭代合并卡方值最小的相邻箱对,
                     直到所有相邻对的卡方检验 p 值均 < (1 - chi2_p),
                     合并过程中严格保持 WOE 单调(不满足则跳过该对)。
    chi2_p         : 卡方检验置信度阈值,默认 0.99。相邻箱 p > (1-chi2_p)
                     时认为两箱分布无显著差异,可以合并。
    chi2_init_size : 卡方计算时的全局 stratified 采样上限,默认 1000。
                     若普通行数 > chi2_init_size,则按 target 比例分层
                     抽样后再计算卡方,避免大数据集下卡方值虚高。
    """

    def __init__(
        self,
        feature_cols: List[str],
        target_col: str,
        n_init_bins: int = 20,
        min_bin_size: float = 0.03,
        min_n_bins: int = 2,
        eps: float = 1e-6,
        missing_woe: float = 0.0,
        special_values: Optional[List] = None,
        cate_feats: Optional[List[str]] = None,
        bin_label_decimals: Optional[int] = None,
    ):
        self.feature_cols      = list(feature_cols)
        self.target_col        = target_col
        self.n_init_bins       = n_init_bins
        self.min_bin_size      = min_bin_size
        self.min_n_bins        = min_n_bins
        self.eps               = eps
        self.missing_woe       = missing_woe
        self.special_values    = list(special_values) if special_values else []
        self.cate_feats        = list(cate_feats) if cate_feats else []
        self._cate_feats_set   = set(self.cate_feats)
        self.bin_label_decimals = bin_label_decimals

        # 判断 special_values 中是否包含 nan(缺失值独立分箱)
        self._sv_has_nan = any(
            v is None or (isinstance(v, float) and math.isnan(v))
            for v in self.special_values
        )
        # 非 nan 特殊值列表
        self._sv_numeric = [
            v for v in self.special_values
            if not (v is None or (isinstance(v, float) and math.isnan(v)))
        ]

        # 拟合结果,fit() 后填充
        # {feat: {
        #   "edges"       : list of float (普通箱切割点),
        #   "woe_table"   : pd.DataFrame  (普通箱 WOE 明细,bin 列 0-based),
        #   "sv_table"    : pd.DataFrame  (特殊值箱 WOE 明细,每行一个特殊值),
        #   "iv"          : float (含特殊值箱的总 IV),
        #   "is_monotonic": bool (仅对普通箱),
        #   "n_bins"      : int  (普通箱数),
        #   --- 类别特征(cate_feats)额外字段 ---
        #   "is_categorical": True,
        #   "categories"  : list (类别取值,按自然顺序;woe_table 每行一个类别,
        #                          含 cat_value/bin_label 列),
        # }}
        self._results: Dict[str, Any] = {}
        self._is_fitted = False

    # ─────────────────────────────────────────────────────────────────
    # 内部工具
    # ─────────────────────────────────────────────────────────────────

    def _split_special(self, df: pd.DataFrame, feat: str):
        """
        将 df 拆分为:普通行(用于单调分箱)+ 各特殊值行。

        Returns
        -------
        df_normal : 剔除了特殊值和(视情况)NaN 的普通行
        sv_groups : {sv -> sub_df},每个特殊值对应的行子集
        """
        mask_normal = pd.Series(True, index=df.index)

        sv_groups: Dict[Any, pd.DataFrame] = {}

        # NaN 单独分箱
        if self._sv_has_nan:
            nan_mask = df[feat].isna()
            sv_groups[float("nan")] = df[nan_mask]
            mask_normal &= ~nan_mask
        else:
            # NaN 不单独分箱 → 普通分箱时直接 dropna(_compute_woe_table 内部处理)
            mask_normal &= df[feat].notna()

        # 数值特殊值
        for sv in self._sv_numeric:
            sv_mask = (df[feat] == sv)
            sv_groups[sv] = df[sv_mask]
            mask_normal &= ~sv_mask

        df_normal = df[mask_normal]
        return df_normal, sv_groups

    # ── 分组绘图(by-group)用的分箱辅助:数值=edges,类别=取值映射 ──────────────

    @staticmethod
    def _cat_to_bin_map(vr: Dict) -> Dict:
        """类别特征:构建 {类别取值 -> 普通箱索引} 映射
        (含 refine_cate 合并后的成员展开)。"""
        wt = vr["woe_table"]
        has_members = "cat_members" in wt.columns
        has_value   = "cat_value"   in wt.columns
        m: Dict = {}
        for _, r in wt.iterrows():
            if has_members and isinstance(r["cat_members"], (list, tuple)):
                members = r["cat_members"]
            elif has_value and not pd.isna(r["cat_value"]):
                members = [r["cat_value"]]
            else:
                members = []
            for cv in members:
                if not pd.isna(cv):
                    m[cv] = int(r["bin"])
        return m

    def _split_special_for_plot(self, df: pd.DataFrame, feat: str, vr: Dict):
        """分组绘图用的特殊值拆分。
        数值特征:沿用 _split_special(按 special_values 拆分)。
        类别特征:仅把 NaN 拆为 [Missing](与 _categorical_fit_one 口径一致),
                  数值不视为特殊值。
        """
        if vr.get("is_categorical"):
            nan_mask = df[feat].isna()
            sv_groups: Dict[Any, pd.DataFrame] = {}
            if bool(nan_mask.any()):
                sv_groups[float("nan")] = df[nan_mask]
            return df[~nan_mask], sv_groups
        return self._split_special(df, feat)

    def _assign_normal_bins(self, sub: pd.DataFrame, feat: str, vr: Dict,
                            fitted_edges: list) -> pd.Series:
        """把普通行映射到普通箱索引(NaN = 未命中,不计入任何箱)。
        数值特征:pd.cut on edges;类别特征:按取值查 cat_to_bin。
        """
        if len(sub) == 0:
            return pd.Series([], dtype=float, index=sub.index)
        if vr.get("is_categorical"):
            return sub[feat].map(self._cat_to_bin_map(vr))
        if len(fitted_edges) > 0:
            return pd.cut(sub[feat], bins=[-np.inf] + list(fitted_edges) + [np.inf],
                          labels=False, right=True)
        return pd.Series(0, index=sub.index)

    def _compute_woe_single_bin(
        self, sub: pd.DataFrame, total_bad: float, total_good: float
    ) -> Dict[str, float]:
        """计算某子集的 bad/good/woe/iv 等统计量。"""
        eps = self.eps
        n    = len(sub)
        bad  = float(sub[self.target_col].sum())
        good = float((sub[self.target_col] == 0).sum())
        bad_rate = bad / (bad + good) if (bad + good) > 0 else 0.0
        pct_bad  = bad  / (total_bad  + eps)
        pct_good = good / (total_good + eps)
        woe = math.log((pct_bad + eps) / (pct_good + eps))
        iv  = (pct_bad - pct_good) * woe
        return dict(n=n, bad=int(bad), good=int(good),
                    bad_rate=bad_rate, pct_bad=pct_bad,
                    pct_good=pct_good, woe=woe, iv=iv)

    def _compute_woe_table(
        self, df: pd.DataFrame, feat: str, edges: list
    ) -> tuple:
        """给定分割点 edges,计算普通箱的 WOE 明细表和 IV。"""
        sub = df[[feat, self.target_col]].dropna(subset=[feat])
        if len(sub) == 0 or len(edges) == 0:
            bins = pd.Series([0] * len(sub), index=sub.index)
        else:
            bins = pd.cut(
                sub[feat],
                bins=[-np.inf] + list(edges) + [np.inf],
                labels=False, right=True,
            )
        sub = sub.copy()
        sub["_bin"] = bins

        total_bad  = float(sub[self.target_col].sum())
        total_good = float((sub[self.target_col] == 0).sum())
        eps = self.eps
        records = []
        for b in sorted(sub["_bin"].dropna().unique()):
            grp  = sub[sub["_bin"] == b]
            n    = len(grp)
            bad  = float(grp[self.target_col].sum())
            good = float((grp[self.target_col] == 0).sum())
            pct_bad  = bad  / (total_bad  + eps)
            pct_good = good / (total_good + eps)
            woe = math.log((pct_bad + eps) / (pct_good + eps))
            iv  = (pct_bad - pct_good) * woe
            records.append(dict(
                bin=int(b), n=n, bad=int(bad), good=int(good),
                bad_rate=bad / (bad + good) if (bad + good) > 0 else 0.0,
                pct_bad=pct_bad, pct_good=pct_good, woe=woe, iv=iv,
            ))
        wt = pd.DataFrame(records)
        if len(wt) == 0:
            wt = pd.DataFrame(columns=["bin", "n", "bad", "good", "bad_rate",
                                        "pct_bad", "pct_good", "woe", "iv"])
            return wt, 0.0
        return wt, float(wt["iv"].sum())

    def _compute_sv_table(
        self, sv_groups: Dict, total_bad: float, total_good: float
    ) -> pd.DataFrame:
        """
        计算所有特殊值的独立 WOE 明细,返回 DataFrame。
        每行对应一个特殊值,bin_label 为 '[sv=xxx]' 或 '[Missing]'。
        """
        records = []
        for sv, sv_df in sv_groups.items():
            if len(sv_df) == 0:
                continue
            stats = self._compute_woe_single_bin(sv_df, total_bad, total_good)
            stats["bin_label"] = _sv_label(sv)
            stats["sv"] = sv
            records.append(stats)
        return pd.DataFrame(records) if records else pd.DataFrame()

    @staticmethod
    def _is_monotone(woe_values: np.ndarray) -> bool:
        if len(woe_values) <= 1:
            return True
        inc = all(woe_values[i] <= woe_values[i+1] for i in range(len(woe_values)-1))
        dec = all(woe_values[i] >= woe_values[i+1] for i in range(len(woe_values)-1))
        return inc or dec

    def _chi2_merge_one(
        self,
        df_normal: pd.DataFrame,
        feat: str,
        edges: list,
        chi2_p: float,
        chi2_init_size: int,
    ) -> list:
        """
        在贪心单调分箱结果的基础上,做卡方后合并。

        算法
        ----
        1. 若普通行数 > chi2_init_size,按 target 比例分层采样 chi2_init_size 行
           用于卡方统计(不改动 edges 本身的全量评估)
        2. 迭代:计算所有相邻箱对的卡方 p 值
           a. 若所有相邻对 p < alpha (= 1 - chi2_p),停止
           b. 否则选 p 值最大(最不显著)的相邻对尝试合并
           c. 合并后检验 WOE 是否仍单调(基于全量普通行)
              - 单调:接受合并,更新 edges
              - 不单调:标记该对为「禁止合并」,跳过后继续
           d. 若所有可合并对均被禁止,停止
        3. 若合并后 edges 剩余箱数 < min_n_bins,停止

        Parameters
        ----------
        df_normal      : 已剔除特殊值的普通行 DataFrame
        feat           : 特征列名
        edges          : 贪心分箱的切割点列表(in-place 不修改,返回新列表)
        chi2_p         : 置信度,如 0.99;alpha = 1 - chi2_p
        chi2_init_size : 采样上限

        Returns
        -------
        new_edges : 卡方合并后的切割点列表
        """
        from scipy.stats import chi2 as chi2_dist

        alpha = 1.0 - chi2_p
        edges = list(edges)   # 不改动原始列表

        # ── 采样(stratified by target)──
        sub_full = df_normal[[feat, self.target_col]].dropna(subset=[feat])
        n_full   = len(sub_full)
        if n_full > chi2_init_size:
            # 按 target 分层采样(用 index 采样避免 groupby 把 target 列变成索引)
            sampled_idx = []
            for tval, grp in sub_full.groupby(self.target_col, sort=False):
                n_take = max(1, int(round(chi2_init_size * len(grp) / n_full)))
                n_take = min(n_take, len(grp))
                sampled_idx.extend(
                    grp.sample(n=n_take, random_state=42).index.tolist()
                )
            sampled = sub_full.loc[sampled_idx]
            # 若分层采样行数不足(极不平衡),补全到 chi2_init_size
            if len(sampled) < chi2_init_size:
                remain = sub_full.drop(sampled.index)
                n_extra = min(chi2_init_size - len(sampled), len(remain))
                if n_extra > 0:
                    extra = remain.sample(n_extra, random_state=42)
                    sampled = pd.concat([sampled, extra])
            df_chi2 = sampled
        else:
            df_chi2 = sub_full

        def _bin_series(df_slice, edge_list):
            """将 df_slice[feat] 按 edge_list 分箱,返回 bin 编号 Series。"""
            if not edge_list:
                return pd.Series(0, index=df_slice.index)
            return pd.cut(
                df_slice[feat],
                bins=[-np.inf] + edge_list + [np.inf],
                labels=False, right=True,
            )

        def _chi2_pval_pair(df_slice, edge_list, bi):
            """
            计算 bi 和 bi+1 箱合并前的卡方 p 值(2x2 列联表)。
            返回 p_value;若某箱样本为 0 则返回 1.0(默认可合并)。
            """
            bins = _bin_series(df_slice, edge_list)
            df_c = df_slice.copy()
            df_c["_bin"] = bins

            grp_i  = df_c[df_c["_bin"] == bi]
            grp_j  = df_c[df_c["_bin"] == bi + 1]

            if len(grp_i) == 0 or len(grp_j) == 0:
                return 1.0  # 空箱,可合并

            bad_i  = float((grp_i[self.target_col] == 1).sum())
            good_i = float((grp_i[self.target_col] == 0).sum())
            bad_j  = float((grp_j[self.target_col] == 1).sum())
            good_j = float((grp_j[self.target_col] == 0).sum())

            # 2×2 列联表: [[bad_i, good_i], [bad_j, good_j]]
            table = np.array([[bad_i, good_i], [bad_j, good_j]])

            # 若任一格期望值为 0,退化:返回 p=0(不合并)
            row_sum = table.sum(axis=1, keepdims=True)
            col_sum = table.sum(axis=0, keepdims=True)
            total   = table.sum()
            if total == 0:
                return 1.0
            expected = row_sum * col_sum / total
            if np.any(expected == 0):
                return 0.0

            # 手动计算卡方(避免 scipy 依赖问题时的稳定性)
            chi2_val = float(np.sum((table - expected) ** 2 / expected))
            # chi2 分布自由度 = (行-1)*(列-1) = 1
            p_val = 1.0 - chi2_dist.cdf(chi2_val, df=1)
            return p_val

        forbidden = set()   # 被禁止合并的 (bi) 索引集合(相对当前 edges)

        for _iter in range(200):
            n_bins = len(edges) + 1
            if n_bins <= self.min_n_bins:
                break

            # 计算所有相邻对的 p 值
            pvals = []
            for bi in range(n_bins - 1):
                p = _chi2_pval_pair(df_chi2, edges, bi)
                pvals.append((bi, p))

            # 过滤已禁止 & p < alpha 的对
            candidates = [(bi, p) for bi, p in pvals
                          if p >= alpha and bi not in forbidden]

            if not candidates:
                break   # 所有相邻对都显著(或被禁),停止

            # 选 p 值最大(最不显著)的对尝试合并
            best_bi, best_p = max(candidates, key=lambda x: x[1])

            # 试合并:移除 edges[best_bi]
            trial_edges = [e for i, e in enumerate(edges) if i != best_bi]

            # 检验合并后 WOE 是否仍单调(基于全量普通行)
            wt_trial, _ = self._compute_woe_table(sub_full, feat, trial_edges)
            woes_trial  = wt_trial.sort_values("bin")["woe"].values

            if self._is_monotone(woes_trial):
                # 接受合并
                edges = trial_edges
                # forbidden 索引需要更新(被合并箱之后的索引都 -1)
                forbidden = {bi - (1 if bi > best_bi else 0)
                             for bi in forbidden if bi != best_bi}
            else:
                # 拒绝:禁止该对后继续
                forbidden.add(best_bi)

        return edges

    def _greedy_fit_one(
        self,
        df: pd.DataFrame,
        feat: str,
        chi2_binning: bool = False,
        chi2_p: float = 0.99,
        chi2_init_size: int = 1000,
    ) -> Dict[str, Any]:
        """
        对单个特征进行贪心单调 WOE 分箱(+ 可选卡方后合并),支持特殊值剔除。
        类别特征(cate_feats)走 _categorical_fit_one,不做区间切分。
        """
        # 0. 类别特征:每个取值直接成箱,直接算 WOE/IV,不做区间切分
        if feat in self._cate_feats_set:
            return self._categorical_fit_one(df, feat)

        # 1. 剔除特殊值,获取普通行和特殊值子集
        df_normal, sv_groups = self._split_special(df, feat)

        # 全量总体(含特殊值)的 bad/good,用于计算 pct_bad/pct_good
        total_bad  = float(df[self.target_col].sum())
        total_good = float((df[self.target_col] == 0).sum())

        # 2. 对普通行进行贪心单调分箱
        col = df_normal[feat].dropna()
        n   = len(col)

        if n < 10:
            # 普通行太少,退化为单箱
            wt, iv = self._compute_woe_table(df_normal, feat, [])
            sv_table = self._compute_sv_table(sv_groups, total_bad, total_good)
            sv_iv = float(sv_table["iv"].sum()) if len(sv_table) > 0 else 0.0
            return dict(edges=[], woe_table=wt, sv_table=sv_table,
                        iv=round(iv + sv_iv, 6),
                        is_monotonic=True, n_bins=max(len(wt), 1))

        min_n = max(int(n * self.min_bin_size), 5)

        # 等频初始分位数边界
        quantiles = np.linspace(0, 100, self.n_init_bins + 1)
        raw_edges = np.unique(np.nanpercentile(col.values, quantiles[1:-1]))

        if len(raw_edges) == 0:
            wt, iv = self._compute_woe_table(df_normal, feat, [])
            sv_table = self._compute_sv_table(sv_groups, total_bad, total_good)
            sv_iv = float(sv_table["iv"].sum()) if len(sv_table) > 0 else 0.0
            return dict(edges=[], woe_table=wt, sv_table=sv_table,
                        iv=round(iv + sv_iv, 6),
                        is_monotonic=True, n_bins=len(wt))

        edges = list(raw_edges)
        wt, iv = self._compute_woe_table(df_normal, feat, edges)

        # 贪心合并
        for _ in range(100):
            woes = wt.sort_values("bin")["woe"].values
            if self._is_monotone(woes):
                break
            if len(edges) < self.min_n_bins - 1:
                break

            inc_vio = [(i, abs(woes[i+1] - woes[i]))
                       for i in range(len(woes)-1) if woes[i] >= woes[i+1]]
            dec_vio = [(i, abs(woes[i+1] - woes[i]))
                       for i in range(len(woes)-1) if woes[i] <= woes[i+1]]
            violations = inc_vio if len(inc_vio) <= len(dec_vio) else dec_vio
            if not violations:
                break

            merge_idx = min(violations, key=lambda x: x[1])[0]
            if merge_idx < len(edges):
                edges.pop(merge_idx)
            wt, iv = self._compute_woe_table(df_normal, feat, edges)

        woes_final = wt.sort_values("bin")["woe"].values

        # ── 卡方后合并(可选)──────────────────────────────────────────────
        if chi2_binning and len(edges) >= 1:
            edges = self._chi2_merge_one(
                df_normal, feat, edges, chi2_p, chi2_init_size
            )
            wt, iv = self._compute_woe_table(df_normal, feat, edges)
            woes_final = wt.sort_values("bin")["woe"].values

        # 计算特殊值箱
        sv_table = self._compute_sv_table(sv_groups, total_bad, total_good)
        sv_iv = float(sv_table["iv"].sum()) if len(sv_table) > 0 else 0.0

        return dict(
            edges        = edges,
            woe_table    = wt,
            sv_table     = sv_table,
            iv           = round(iv + sv_iv, 6),
            is_monotonic = self._is_monotone(woes_final),
            n_bins       = len(wt),
        )

    @staticmethod
    def _sort_categories(cats: list) -> list:
        """对类别取值做稳健排序(同类型自然排序;混合类型回退按字符串排序)。"""
        try:
            return sorted(cats)
        except TypeError:
            return sorted(cats, key=lambda x: str(x))

    def _categorical_fit_one(self, df: pd.DataFrame, feat: str) -> Dict[str, Any]:
        """
        对单个**已离散化的类别特征**直接计算 WOE/IV,不做任何区间切分。

        每个不同的取值各自成一箱,箱标签即取值本身;缺失值(NaN)若存在则单独
        归为 [Missing] 箱(追加进 sv_table,独立计算 WOE)。

        WOE/IV 口径与数值特征保持一致:
          - 普通类别箱:pct_bad/pct_good 以**非缺失**样本的 bad/good 为分母
          - [Missing] 箱:以**全量**样本的 bad/good 为分母(与 _compute_sv_table 一致)
          - 总 IV = 各类别箱 IV 之和 + [Missing] 箱 IV
        """
        sub = df[[feat, self.target_col]]

        nan_mask = sub[feat].isna()
        normal   = sub[~nan_mask]

        # 普通类别箱口径:非缺失样本的总 bad/good
        norm_total_bad  = float(normal[self.target_col].sum())
        norm_total_good = float((normal[self.target_col] == 0).sum())
        # [Missing] 箱口径:全量样本的总 bad/good
        full_total_bad  = float(sub[self.target_col].sum())
        full_total_good = float((sub[self.target_col] == 0).sum())

        cats = self._sort_categories(list(normal[feat].dropna().unique()))

        records = []
        for i, cat in enumerate(cats):
            grp   = normal[normal[feat] == cat]
            stats = self._compute_woe_single_bin(grp, norm_total_bad, norm_total_good)
            stats.update(bin=i, cat_value=cat, bin_label=str(cat))
            records.append(stats)

        cols = ["bin", "cat_value", "bin_label", "n", "bad", "good",
                "bad_rate", "pct_bad", "pct_good", "woe", "iv"]
        woe_table = pd.DataFrame(records, columns=cols) if records \
            else pd.DataFrame(columns=cols)

        normal_iv = float(woe_table["iv"].sum()) if len(woe_table) > 0 else 0.0

        # 缺失值 → [Missing] 箱(复用 sv_table 机制)
        sv_groups = {float("nan"): sub[nan_mask]} if int(nan_mask.sum()) > 0 else {}
        sv_table  = self._compute_sv_table(sv_groups, full_total_bad, full_total_good)
        sv_iv     = float(sv_table["iv"].sum()) if len(sv_table) > 0 else 0.0

        woes = woe_table.sort_values("bin")["woe"].values if len(woe_table) > 0 else np.array([])

        return dict(
            edges          = [],
            woe_table      = woe_table,
            sv_table       = sv_table,
            iv             = round(normal_iv + sv_iv, 6),
            is_monotonic   = self._is_monotone(woes),
            n_bins         = len(woe_table),
            is_categorical = True,
            categories     = list(cats),
        )

    # ─────────────────────────────────────────────────────────────────
    # 公开 API
    # ─────────────────────────────────────────────────────────────────

    def fit(
        self,
        df: pd.DataFrame,
        chi2_binning: bool = False,
        chi2_p: float = 0.99,
        chi2_init_size: int = 1000,
        n_jobs: int = 1,
    ) -> "MonotoneWOEBinner":
        """
        在训练集上拟合所有特征的单调 WOE 分箱。

        Parameters
        ----------
        df             : 训练集 DataFrame,需包含 feature_cols 和 target_col
        chi2_binning   : 是否在贪心单调分箱后再进行卡方后合并,默认 False。
                         True 时:当相邻箱的卡方检验 p > (1 - chi2_p)时,
                         尝试合并该对,并保持 WOE 单调。
        chi2_p         : 卡方检验置信度,默认 0.99。
                         较大的值(如 0.99)表示保留更多箱;
                         较小的值(如 0.90)表示更容易合并。
        chi2_init_size : 卡方计算时的全局 stratified 采样上限,默认 1000。
                         若普通行数 > chi2_init_size,按 target 比例分层采样,
                         避免大数据集下卡方值虚高导致不该合并的箱被强行分开。
        n_jobs         : 并行线程数,默认 1(顺序执行,行为与旧版完全相同)。
                         设为 > 1 时使用指定数量的线程;设为 -1 时使用所有可用
                         CPU 核心。特征数较多(如 3000+)时可显著提速。

        Returns
        -------
        self (支持链式调用)
        """
        # 待拟合的全部特征 = 数值特征 + 类别特征(去重,保持顺序)
        all_fit_feats = list(dict.fromkeys(list(self.feature_cols) + list(self.cate_feats)))

        missing_feats = [f for f in all_fit_feats if f not in df.columns]
        if missing_feats:
            raise ValueError(f"以下特征列不在 DataFrame 中: {missing_feats}")
        if self.target_col not in df.columns:
            raise ValueError(f"目标列 '{self.target_col}' 不在 DataFrame 中")

        # 检查 scipy 可用性
        if chi2_binning:
            try:
                from scipy.stats import chi2 as _chi2_check  # noqa
            except ImportError:
                raise ImportError(
                    "chi2_binning=True 需要 scipy,请先安装: pip install scipy"
                )

        self._train_n        = len(df)
        self._bad_rate       = float(df[self.target_col].mean())
        self._chi2_binning   = chi2_binning
        self._chi2_p         = chi2_p
        self._chi2_init_size = chi2_init_size

        sv_hint   = f", special_values={self.special_values}" if self.special_values else ""
        cate_hint = f", cate_feats={len(self.cate_feats)}个" if self.cate_feats else ""
        chi2_hint = (f", chi2_binning=True (p={chi2_p}, sample={chi2_init_size})"
                     if chi2_binning else "")
        logger.info(f"[MonotoneWOEBinner] 开始拟合 {len(all_fit_feats)} 个特征"
              f"{sv_hint}{cate_hint}{chi2_hint} ...")

        if n_jobs == 0:
            raise ValueError("n_jobs 不能为 0;请使用正整数或 -1(全部核心)")

        def _fit_one(feat):
            try:
                res = self._greedy_fit_one(
                    df, feat,
                    chi2_binning   = chi2_binning,
                    chi2_p         = chi2_p,
                    chi2_init_size = chi2_init_size,
                )
                return feat, res, None
            except Exception as exc:
                import traceback as _tb
                return feat, None, (exc, _tb.format_exc())

        def _log_feat(feat, res):
            mono   = res["is_monotonic"]
            iv     = res["iv"]
            nb     = res["n_bins"]
            nsv    = len(res["sv_table"])
            sv_str = f" | sv_bins={nsv}" if nsv > 0 else ""
            cat_str = " | CATE" if res.get("is_categorical") else ""
            logger.info(f"  ✓ {feat:40s} | n_bins={nb}{sv_str}{cat_str} | IV={iv:.4f} | mono={mono}")

        if n_jobs == 1:
            for feat in all_fit_feats:
                _, res, err = _fit_one(feat)
                if err is not None:
                    logger.info(f"  ✗ {feat}: 拟合失败 — {err[0]}")
                    print(err[1])
                else:
                    self._results[feat] = res
                    _log_feat(feat, res)
        else:
            # ── 多进程并行(ProcessPoolExecutor)──────────────────────────
            # 策略:将特征列表均分为 N 块,每块整体发往一个进程,
            # df 每块只序列化一次(而非每特征一次),大幅降低 IPC 开销。
            max_workers = n_jobs if n_jobs > 0 else None
            n_workers   = max_workers or os.cpu_count() or 1
            chunk_size  = max(1, math.ceil(len(all_fit_feats) / n_workers))
            chunks      = [
                all_fit_feats[i : i + chunk_size]
                for i in range(0, len(all_fit_feats), chunk_size)
            ]
            # 轻量副本:只含配置,不含已有拟合结果,减少序列化体积
            binner_lite = copy.copy(self)
            binner_lite._results   = {}
            binner_lite._is_fitted = False

            feat_ok, feat_err = {}, {}
            with ProcessPoolExecutor(max_workers=max_workers) as executor:
                futures = [
                    executor.submit(
                        _chunk_fit_worker,
                        (binner_lite, df, chunk, chi2_binning, chi2_p, chi2_init_size),
                    )
                    for chunk in chunks
                ]
                for fut in as_completed(futures):
                    ok, err = fut.result()
                    feat_ok.update(ok)
                    feat_err.update(err)
            # 按原始顺序写回并打印日志
            for feat in all_fit_feats:
                if feat in feat_ok:
                    self._results[feat] = feat_ok[feat]
                    _log_feat(feat, feat_ok[feat])
                elif feat in feat_err:
                    exc, tb = feat_err[feat]
                    logger.info(f"  ✗ {feat}: 拟合失败 — {exc}")
                    print(tb)

        self._is_fitted = True
        n_mono = sum(1 for v in self._results.values() if v["is_monotonic"])
        method = "greedy+chi2" if chi2_binning else "greedy"
        logger.info(f"[MonotoneWOEBinner] 拟合完成 ({method}): "
              f"{n_mono}/{len(self._results)} 个特征单调")
        return self

    def _check_fitted(self):
        if not self._is_fitted:
            raise RuntimeError("请先调用 fit() 或 load_woe_bins() 进行初始化")

    def refine_chi2(
        self,
        df: pd.DataFrame,
        features: Optional[List[str]] = None,
        chi2_p: float = 0.99,
        chi2_init_size: int = 1000,
        n_jobs: int = 1,
    ) -> "MonotoneWOEBinner":
        """
        在已有贪心分箱结果的基础上,追加卡方后合并(不重跑贪心分箱)。

        与 fit(chi2_binning=True) 的区别
        ---------------------------------
        - 跳过贪心分箱阶段,直接以 self._results 中已有的 edges 为起点
        - 可在同一份 fit 结果上反复以不同 chi2_p 调参,无需重跑贪心,速度更快
        - 支持只对指定特征子集执行卡方合并
        - 特殊值箱 WOE 不受影响,沿用 fit() 时的计算结果

        Parameters
        ----------
        df             : 原始训练数据(与 fit() 时相同),用于计算卡方统计量
        features       : 需要做卡方合并的特征列表;默认 None 表示所有已拟合特征
        chi2_p         : 卡方检验置信度,默认 0.99;较小值(如 0.90)更容易合并箱
        chi2_init_size : 卡方计算时 stratified 采样上限,默认 1000
        n_jobs         : 并行线程数,默认 1(顺序执行)。设为 > 1 时使用指定数量
                         的线程;设为 -1 时使用所有可用 CPU 核心。

        Returns
        -------
        self(支持链式调用)

        Examples
        --------
        >>> binner = MonotoneWOEBinner(feature_cols=["score"], target_col="is_bad")
        >>> binner.fit(train_df)                                    # 贪心分箱
        >>> binner.refine_chi2(train_df, chi2_p=0.95, n_jobs=8)    # 并行卡方合并
        >>> # 或只对部分特征做卡方合并
        >>> binner.refine_chi2(train_df, features=["score", "income"], chi2_p=0.90)
        """
        self._check_fitted()
        try:
            from scipy.stats import chi2 as _chi2_check  # noqa
        except ImportError:
            raise ImportError(
                "refine_chi2() 需要 scipy,请先安装: pip install scipy"
            )
        if n_jobs == 0:
            raise ValueError("n_jobs 不能为 0;请使用正整数或 -1(全部核心)")

        target_feats = features if features is not None else list(self._results.keys())
        # 类别特征不适用卡方后合并,自动剔除
        _cate_in = [f for f in target_feats if self._results.get(f, {}).get("is_categorical")]
        if _cate_in:
            logger.info(f"[refine_chi2] 跳过 {len(_cate_in)} 个类别特征(不适用卡方合并)")
        target_feats = [f for f in target_feats
                        if not self._results.get(f, {}).get("is_categorical")]
        missing_feats = [f for f in target_feats if f not in self._results]
        if missing_feats:
            raise ValueError(f"以下特征尚未拟合,无法做 chi2 合并: {missing_feats}")
        if self.target_col not in df.columns:
            raise ValueError(f"目标列 '{self.target_col}' 不在 DataFrame 中")

        logger.info(
            f"[refine_chi2] 对 {len(target_feats)} 个特征做卡方后合并 "
            f"(chi2_p={chi2_p}, sample={chi2_init_size}, n_jobs={n_jobs}) ..."
        )

        # 每个特征的计算完全独立,可安全并行
        def _refine_one(feat):
            vr    = self._results[feat]
            edges = list(vr["edges"])
            if len(edges) < 1:
                return feat, None, None   # 标记为"跳过"
            try:
                df_normal, _ = self._split_special(df, feat)
                new_edges = self._chi2_merge_one(
                    df_normal, feat, edges, chi2_p, chi2_init_size
                )
                wt, iv = self._compute_woe_table(df_normal, feat, new_edges)
                woes   = wt.sort_values("bin")["woe"].values
                sv_table = vr.get("sv_table", pd.DataFrame())
                sv_iv    = float(sv_table["iv"].sum()) if len(sv_table) > 0 else 0.0
                update = dict(
                    edges        = new_edges,
                    woe_table    = wt,
                    iv           = round(iv + sv_iv, 6),
                    is_monotonic = self._is_monotone(woes),
                    n_bins       = len(wt),
                )
                return feat, (vr["n_bins"], update), None
            except Exception as exc:
                import traceback as _tb
                return feat, None, (exc, _tb.format_exc())

        def _apply_and_log(feat, ok, err):
            if ok is None and err is None:
                logger.info(f"  - {feat:40s} | 仅 1 箱,跳过卡方合并")
            elif err is not None:
                logger.info(f"  ✗ {feat}: chi2 合并失败 — {err[0]}")
                print(err[1])
            else:
                old_nb, update = ok
                self._results[feat].update(update)
                logger.info(
                    f"  ✓ {feat:40s} | bins: {old_nb}{update['n_bins']} "
                    f"| IV={update['iv']:.4f} | mono={update['is_monotonic']}"
                )

        if n_jobs == 1:
            for feat in target_feats:
                feat, ok, err = _refine_one(feat)
                _apply_and_log(feat, ok, err)
        else:
            # ── 多进程并行(ProcessPoolExecutor)──────────────────────────
            max_workers = n_jobs if n_jobs > 0 else None
            n_workers   = max_workers or os.cpu_count() or 1
            chunk_size  = max(1, math.ceil(len(target_feats) / n_workers))
            chunks      = [
                target_feats[i : i + chunk_size]
                for i in range(0, len(target_feats), chunk_size)
            ]
            binner_lite = copy.copy(self)
            binner_lite._results   = {}
            binner_lite._is_fitted = False
            # 只传各特征的 edges 和 sv_iv(轻量),不传完整 _results
            edges_map  = {f: list(self._results[f]["edges"]) for f in target_feats}
            sv_iv_map  = {
                f: float(self._results[f].get("sv_table", pd.DataFrame())["iv"].sum())
                   if len(self._results[f].get("sv_table", pd.DataFrame())) > 0 else 0.0
                for f in target_feats
            }
            old_nb_map = {f: self._results[f]["n_bins"] for f in target_feats}

            feat_ok, feat_err, feat_skip = {}, {}, set()
            with ProcessPoolExecutor(max_workers=max_workers) as executor:
                futures = [
                    executor.submit(
                        _chunk_chi2_worker,
                        (binner_lite, df, chunk, edges_map, sv_iv_map,
                         chi2_p, chi2_init_size),
                    )
                    for chunk in chunks
                ]
                for fut in as_completed(futures):
                    ok, err = fut.result()
                    for feat, res in ok.items():
                        if res is None:
                            feat_skip.add(feat)
                        else:
                            feat_ok[feat] = res
                    feat_err.update(err)
            # 按原始顺序写回并打印日志
            for feat in target_feats:
                if feat in feat_skip:
                    logger.info(f"  - {feat:40s} | 仅 1 箱,跳过卡方合并")
                elif feat in feat_err:
                    exc, tb = feat_err[feat]
                    logger.info(f"  ✗ {feat}: chi2 合并失败 — {exc}")
                    print(tb)
                elif feat in feat_ok:
                    upd = feat_ok[feat]
                    self._results[feat].update(upd)
                    logger.info(
                        f"  ✓ {feat:40s} | bins: {old_nb_map[feat]}{upd['n_bins']} "
                        f"| IV={upd['iv']:.4f} | mono={upd['is_monotonic']}"
                    )

        self._chi2_binning   = True
        self._chi2_p         = chi2_p
        self._chi2_init_size = chi2_init_size

        n_skipped = sum(
            1 for f in target_feats if len(self._results[f]["edges"]) < 1
        )
        logger.info(
            f"[refine_chi2] 完成,{len(target_feats) - n_skipped}/{len(target_feats)} "
            f"个特征参与合并"
        )
        return self

    # ── refine_dtree ─────────────────────────────────────────────────────────

    @staticmethod
    def _dtree_edges(df_normal: pd.DataFrame, feat: str, target_col: str,
                     max_bins: int, min_samples_leaf) -> list:
        """用决策树找分割点,返回排好序的内部边界列表。"""
        from sklearn.tree import DecisionTreeClassifier
        sub = df_normal[[feat, target_col]].dropna(subset=[feat])
        if len(sub) < 4:
            return []
        X = sub[[feat]].values
        y = sub[target_col].values
        clf = DecisionTreeClassifier(
            max_leaf_nodes   = max_bins,
            min_samples_leaf = min_samples_leaf,
            random_state     = 42,
        )
        clf.fit(X, y)
        tree = clf.tree_
        # threshold == -2 表示叶节点,排除后去重排序
        raw = tree.threshold[tree.feature != -2]
        return sorted(set(float(t) for t in raw))

    @staticmethod
    def _monotone_merge_edges(df_normal: pd.DataFrame, feat: str,
                              target_col: str, edges: list,
                              eps: float) -> list:
        """
        在给定 edges 分箱后,若 WOE 不单调,贪心合并 WOE 方向反转的相邻箱,
        直到单调为止。不改变箱的单调方向(自动判断升/降)。
        """
        import math as _math

        def _woe_seq(edge_list):
            sub = df_normal[[feat, target_col]].dropna(subset=[feat])
            if len(sub) == 0 or len(edge_list) == 0:
                return np.array([])
            bins = pd.cut(sub[feat], bins=[-np.inf] + edge_list + [np.inf],
                          labels=False, right=True)
            sub = sub.copy(); sub["_b"] = bins
            tb = float(sub[target_col].sum()); tg = float((sub[target_col] == 0).sum())
            recs = []
            for b in sorted(sub["_b"].dropna().unique()):
                g = sub[sub["_b"] == b]
                bad = float(g[target_col].sum()); good = float((g[target_col] == 0).sum())
                pb = bad / (tb + eps); pg = good / (tg + eps)
                recs.append(_math.log((pb + eps) / (pg + eps)))
            return np.array(recs)

        def _is_mono(arr):
            if len(arr) <= 1: return True
            return (all(arr[i] <= arr[i+1] for i in range(len(arr)-1)) or
                    all(arr[i] >= arr[i+1] for i in range(len(arr)-1)))

        cur = list(edges)
        for _ in range(200):
            woes = _woe_seq(cur)
            if len(woes) <= 1 or _is_mono(woes):
                break
            # 找第一个方向反转位置(按主方向:第一个差值的符号)
            main_sign = np.sign(woes[1] - woes[0]) if len(woes) > 1 else 0
            for i in range(len(woes) - 1):
                if main_sign == 0:
                    main_sign = np.sign(woes[i+1] - woes[i])
                if main_sign != 0 and np.sign(woes[i+1] - woes[i]) not in (main_sign, 0):
                    # 合并第 i 和 i+1 箱(移除 cur[i])
                    cur = [e for j, e in enumerate(cur) if j != i]
                    break
        return cur

    def refine_dtree(
        self,
        df: pd.DataFrame,
        features: Optional[List[str]] = None,
        max_bins: int = 6,
        min_samples_leaf: float = 0.05,
        monotone: bool = True,
        n_jobs: int = 1,
    ) -> "MonotoneWOEBinner":
        """
        在已有贪心分箱结果的基础上,用决策树重新划定分割点。

        与 refine_chi2 的区别
        ---------------------
        - refine_chi2  : 在现有 edges 上做后合并(只减少箱数)
        - refine_dtree : 用决策树从头找最优分割点(可改变箱的位置和数量),
                         适合需要基于信息增益而非 IV 单调性重新划分的场景

        算法
        ----
        1. 对每个特征的普通行拟合 DecisionTreeClassifier
           (max_leaf_nodes=max_bins, min_samples_leaf=min_samples_leaf)
        2. 提取树的内部阈值作为新 edges
        3. 若 monotone=True,贪心合并 WOE 方向反转的相邻箱,直到 WOE 单调
        4. 重新计算 woe_table / iv / n_bins,写回 self._results

        Parameters
        ----------
        df               : 训练集 DataFrame(与 fit() 时相同)
        features         : 特征子集;默认 None 表示所有已拟合特征
        max_bins         : 决策树最大叶节点数(即分箱上限),默认 6
        min_samples_leaf : 决策树每个叶节点的最小样本占比(0~1)或绝对数(≥1),
                           默认 0.05(5%),用于防止过细分箱
        monotone         : 是否在决策树分箱后强制 WOE 单调,默认 True
        n_jobs           : 并行进程数,默认 1;-1 使用所有 CPU 核心

        Returns
        -------
        self(支持链式调用)

        Examples
        --------
        >>> binner.fit(train_df)
        >>> binner.refine_dtree(train_df, max_bins=5, min_samples_leaf=0.05)
        >>> # 先贪心分箱,再决策树重新划分,再 chi2 后合并
        >>> binner.fit(train_df).refine_dtree(train_df).refine_chi2(train_df, chi2_p=0.95)
        """
        self._check_fitted()
        try:
            from sklearn.tree import DecisionTreeClassifier  # noqa
        except ImportError:
            raise ImportError(
                "refine_dtree() 需要 scikit-learn,请先安装: pip install scikit-learn"
            )
        if n_jobs == 0:
            raise ValueError("n_jobs 不能为 0;请使用正整数或 -1(全部核心)")

        target_feats = features if features is not None else list(self._results.keys())
        # 类别特征不适用决策树重分箱,自动剔除(避免把类别编码当数值切分)
        _cate_in = [f for f in target_feats if self._results.get(f, {}).get("is_categorical")]
        if _cate_in:
            logger.info(f"[refine_dtree] 跳过 {len(_cate_in)} 个类别特征(不适用决策树重分箱)")
        target_feats = [f for f in target_feats
                        if not self._results.get(f, {}).get("is_categorical")]
        missing_feats = [f for f in target_feats if f not in self._results]
        if missing_feats:
            raise ValueError(f"以下特征尚未拟合,无法做 dtree 重分箱: {missing_feats}")
        if self.target_col not in df.columns:
            raise ValueError(f"目标列 '{self.target_col}' 不在 DataFrame 中")

        logger.info(
            f"[refine_dtree] 对 {len(target_feats)} 个特征做决策树重分箱 "
            f"(max_bins={max_bins}, min_samples_leaf={min_samples_leaf}, "
            f"monotone={monotone}, n_jobs={n_jobs}) ..."
        )

        eps = self.eps

        def _refine_one(feat):
            vr = self._results[feat]
            try:
                df_normal, _ = self._split_special(df, feat)
                # Step 1: 决策树找分割点
                new_edges = self._dtree_edges(
                    df_normal, feat, self.target_col, max_bins, min_samples_leaf
                )
                # Step 2: 可选单调合并
                if monotone and len(new_edges) >= 1:
                    new_edges = self._monotone_merge_edges(
                        df_normal, feat, self.target_col, new_edges, eps
                    )
                # Step 3: 重算 WOE 表
                wt, iv = self._compute_woe_table(df_normal, feat, new_edges)
                woes   = wt.sort_values("bin")["woe"].values if len(wt) > 0 else np.array([])
                sv_table = vr.get("sv_table", pd.DataFrame())
                sv_iv    = float(sv_table["iv"].sum()) if len(sv_table) > 0 else 0.0
                update = dict(
                    edges        = new_edges,
                    woe_table    = wt,
                    iv           = round(iv + sv_iv, 6),
                    is_monotonic = self._is_monotone(woes),
                    n_bins       = len(wt),
                )
                return feat, (vr["n_bins"], update), None
            except Exception as exc:
                import traceback as _tb
                return feat, None, (exc, _tb.format_exc())

        def _apply_and_log(feat, ok, err):
            if err is not None:
                logger.info(f"  ✗ {feat}: dtree 重分箱失败 — {err[0]}")
                print(err[1])
            else:
                old_nb, update = ok
                self._results[feat].update(update)
                logger.info(
                    f"  ✓ {feat:40s} | bins: {old_nb}{update['n_bins']} "
                    f"| IV={update['iv']:.4f} | mono={update['is_monotonic']}"
                )

        if n_jobs == 1:
            for feat in target_feats:
                feat, ok, err = _refine_one(feat)
                _apply_and_log(feat, ok, err)
        else:
            # ── 多进程并行(ProcessPoolExecutor)──────────────────────────
            # worker 必须使用模块级函数;Windows/Jupyter 的 spawn 语义无法
            # pickle refine_dtree() 内部定义的局部函数。
            max_workers = n_jobs if n_jobs > 0 else None
            n_workers   = max_workers or os.cpu_count() or 1
            chunk_size  = max(1, math.ceil(len(target_feats) / n_workers))
            chunks      = [
                target_feats[i : i + chunk_size]
                for i in range(0, len(target_feats), chunk_size)
            ]
            binner_lite = copy.copy(self)
            binner_lite._results   = {}
            binner_lite._is_fitted = False
            sv_iv_map = {
                f: float(self._results[f].get("sv_table", pd.DataFrame())["iv"].sum())
                   if len(self._results[f].get("sv_table", pd.DataFrame())) > 0 else 0.0
                for f in target_feats
            }
            old_nb_map = {f: self._results[f]["n_bins"] for f in target_feats}
            feat_ok, feat_err = {}, {}
            with ProcessPoolExecutor(max_workers=max_workers) as executor:
                futures = [
                    executor.submit(
                        _chunk_dtree_worker,
                        (
                            binner_lite, df, chunk, sv_iv_map, max_bins,
                            min_samples_leaf, monotone, eps,
                        ),
                    )
                    for chunk in chunks
                ]
                for fut in as_completed(futures):
                    ok, err = fut.result()
                    feat_ok.update(ok)
                    feat_err.update(err)
            for feat in target_feats:
                if feat in feat_err:
                    exc, tb = feat_err[feat]
                    logger.info(f"  ✗ {feat}: dtree 重分箱失败 — {exc}")
                    print(tb)
                elif feat in feat_ok:
                    upd = feat_ok[feat]
                    self._results[feat].update(upd)
                    logger.info(
                        f"  ✓ {feat:40s} | bins: {old_nb_map[feat]}{upd['n_bins']} "
                        f"| IV={upd['iv']:.4f} | mono={upd['is_monotonic']}"
                    )

        logger.info(f"[refine_dtree] 完成,{len(target_feats)} 个特征处理完毕")
        return self

    # ── refine_cate ──────────────────────────────────────────────────────────

    def _cluster_cate_one(
        self,
        vr: Dict,
        max_bins: int,
        min_bin_size: float,
        badrate_tol: Optional[float],
    ) -> Optional[Dict[str, Any]]:
        """
        对单个类别特征,按坏率(bad rate)做凝聚式(agglomerative)聚类:
        把坏率相近的类别合并成同一箱,直到箱数 ≤ max_bins。

        合并规则(每轮择一执行,直到无可合并):
          1. min_bin_size 优先(稳定性):存在样本占比 < min_bin_size 的箱时,
             先把最小的违例箱并入坏率更接近的相邻箱(忽略 badrate_tol)。
          2. 否则若箱数 > max_bins:合并坏率差最小的相邻箱对;
             若设了 badrate_tol 且最小坏率差 > badrate_tol,则停止
             (剩余相邻箱坏率差异都过大,不再强行合并)。

        合并仅发生在按坏率排序后的相邻箱之间,因此最终各箱坏率严格有序,
        WOE 天然单调。仅用已拟合的每类别计数(woe_table),无需重读原始数据。

        Returns
        -------
        update dict(woe_table / iv / is_monotonic / n_bins / categories),
        若无需聚类则返回 None。
        """
        wt  = vr["woe_table"]
        eps = self.eps
        if len(wt) <= 1:
            return None

        total_bad  = float(wt["bad"].sum())
        total_good = float(wt["good"].sum())
        total_n    = float(wt["n"].sum())

        # 初始:每个(已有)箱作为一个组,保留成员类别与标签
        groups = []
        for _, r in wt.iterrows():
            if "cat_members" in wt.columns and isinstance(r["cat_members"], (list, tuple)):
                members = list(r["cat_members"])
            elif "cat_value" in wt.columns and not pd.isna(r["cat_value"]):
                members = [r["cat_value"]]
            else:
                members = [r["bin_label"]]
            groups.append(dict(
                members = members,
                label   = str(r["bin_label"]),
                n       = float(r["n"]),
                bad     = float(r["bad"]),
                good    = float(r["good"]),
            ))

        def _br(g):
            return g["bad"] / (g["bad"] + g["good"] + eps)

        groups.sort(key=_br)

        def _merge(i):
            """合并相邻 groups[i] 与 groups[i+1]。"""
            a, b = groups[i], groups[i + 1]
            groups[i:i + 2] = [dict(
                members = a["members"] + b["members"],
                label   = a["label"] + _CATE_GROUP_SEP + b["label"],
                n       = a["n"] + b["n"],
                bad     = a["bad"] + b["bad"],
                good    = a["good"] + b["good"],
            )]

        changed = False
        while len(groups) > 1:
            too_small = (
                [i for i, g in enumerate(groups)
                 if g["n"] / (total_n + eps) < min_bin_size]
                if min_bin_size > 0 else []
            )
            if too_small:
                # 把最小的违例箱并入坏率更接近的相邻箱
                i = min(too_small, key=lambda k: groups[k]["n"])
                if i == 0:
                    j = 0
                elif i == len(groups) - 1:
                    j = i - 1
                else:
                    dl = abs(_br(groups[i]) - _br(groups[i - 1]))
                    dr = abs(_br(groups[i]) - _br(groups[i + 1]))
                    j = i - 1 if dl <= dr else i
                _merge(j); changed = True
                continue
            if len(groups) > max_bins:
                gap, mi = min(
                    (abs(_br(groups[i + 1]) - _br(groups[i])), i)
                    for i in range(len(groups) - 1)
                )
                if badrate_tol is not None and gap > badrate_tol:
                    break   # 剩余相邻箱坏率差异都过大,停止合并
                _merge(mi); changed = True
                continue
            break

        if not changed:
            return None

        # 重算各组 WOE/IV,按坏率升序编号(WOE 天然单调)
        groups.sort(key=_br)
        records = []
        for i, g in enumerate(groups):
            bad, good, n = g["bad"], g["good"], g["n"]
            pct_bad  = bad  / (total_bad  + eps)
            pct_good = good / (total_good + eps)
            woe = math.log((pct_bad + eps) / (pct_good + eps))
            iv  = (pct_bad - pct_good) * woe
            records.append(dict(
                bin=i,
                cat_value=(g["members"][0] if len(g["members"]) == 1 else np.nan),
                cat_members=list(g["members"]),
                bin_label=g["label"],
                n=int(n), bad=int(bad), good=int(good),
                bad_rate=bad / (bad + good) if (bad + good) > 0 else 0.0,
                pct_bad=pct_bad, pct_good=pct_good, woe=woe, iv=iv,
            ))
        cols = ["bin", "cat_value", "cat_members", "bin_label", "n", "bad", "good",
                "bad_rate", "pct_bad", "pct_good", "woe", "iv"]
        new_wt = pd.DataFrame(records, columns=cols)

        normal_iv = float(new_wt["iv"].sum())
        sv_table  = vr.get("sv_table", pd.DataFrame())
        sv_iv     = float(sv_table["iv"].sum()) if len(sv_table) > 0 else 0.0

        return dict(
            woe_table    = new_wt,
            iv           = round(normal_iv + sv_iv, 6),
            is_monotonic = self._is_monotone(new_wt["woe"].values),
            n_bins       = len(new_wt),
            categories   = [m for g in groups for m in g["members"]],
        )

    def refine_cate(
        self,
        features: Optional[List[str]] = None,
        max_bins: int = 5,
        min_bin_size: float = 0.0,
        badrate_tol: Optional[float] = None,
    ) -> "MonotoneWOEBinner":
        """
        对已拟合的**类别特征(cate_feats)**按坏率(bad rate)做凝聚式聚类,
        把坏率相近的类别合并成同一箱,降低箱数、提升稳定性。

        与 refine_chi2 / refine_dtree 的关系
        ------------------------------------
        - refine_chi2 / refine_dtree : 只作用于**数值**特征(类别特征自动跳过)
        - refine_cate                : 只作用于**类别**特征(数值特征自动跳过)

        说明
        ----
        - 仅使用 fit() 已算好的每类别计数(woe_table),**无需重新传入 df**,速度极快。
        - 合并按坏率排序后的相邻类别进行,因此结果各箱坏率有序、WOE 天然单调。
        - 合并只会降低或维持 IV(信息合并不会增加 IV),换取更少的箱与更好的泛化。
        - [Missing] 箱不参与聚类,沿用 fit() 的结果。
        - 可重复调用(在已聚类结果上继续合并)。

        Parameters
        ----------
        features     : 需要聚类的类别特征列表;默认 None = 所有已拟合的类别特征。
                       传入数值特征会被自动跳过。
        max_bins     : 聚类后每个特征的最大箱数,默认 5。
        min_bin_size : 每箱最小样本占比(0~1),默认 0.0(关闭)。> 0 时,样本占比
                       低于该阈值的箱会被强制并入坏率最接近的相邻箱(优先于 max_bins,
                       且忽略 badrate_tol)。
        badrate_tol  : 坏率差阈值,默认 None(不启用)。设为正数时,当所有相邻箱的
                       坏率差都 > badrate_tol 时停止按 max_bins 合并,避免把坏率差异
                       很大的类别为了凑箱数而强行合并。

        Returns
        -------
        self(支持链式调用)

        Examples
        --------
        >>> binner = MonotoneWOEBinner(feature_cols=["score"], target_col="is_bad",
        ...                            cate_feats=["city", "industry"])
        >>> binner.fit(df)
        >>> binner.refine_cate(max_bins=5)                       # 全部类别特征聚类
        >>> binner.refine_cate(features=["city"], max_bins=4,    # 仅 city,带约束
        ...                    min_bin_size=0.02, badrate_tol=0.03)
        """
        self._check_fitted()
        if max_bins < 1:
            raise ValueError(f"max_bins 必须 ≥ 1,收到: {max_bins}")

        all_cate = [f for f in self._results if self._results[f].get("is_categorical")]
        if features is None:
            target_feats = all_cate
        else:
            _num_in = [f for f in features
                       if f in self._results and not self._results[f].get("is_categorical")]
            if _num_in:
                logger.info(f"[refine_cate] 跳过 {len(_num_in)} 个非类别特征(仅适用类别特征)")
            target_feats = [f for f in features
                            if self._results.get(f, {}).get("is_categorical")]
            missing_feats = [f for f in features if f not in self._results]
            if missing_feats:
                raise ValueError(f"以下特征尚未拟合,无法做类别聚类: {missing_feats}")

        if not target_feats:
            logger.info("[refine_cate] 无类别特征可聚类(需先 fit 含 cate_feats 的特征)")
            return self

        logger.info(
            f"[refine_cate] 对 {len(target_feats)} 个类别特征按坏率聚类 "
            f"(max_bins={max_bins}, min_bin_size={min_bin_size}, badrate_tol={badrate_tol}) ..."
        )

        for feat in target_feats:
            vr     = self._results[feat]
            old_nb = vr["n_bins"]
            try:
                update = self._cluster_cate_one(vr, max_bins, min_bin_size, badrate_tol)
            except Exception as exc:
                import traceback as _tb
                logger.info(f"  ✗ {feat}: 类别聚类失败 — {exc}")
                print(_tb.format_exc())
                continue
            if update is None:
                logger.info(f"  - {feat:40s} | {old_nb} 箱无需聚类")
                continue
            vr.update(update)
            logger.info(
                f"  ✓ {feat:40s} | bins: {old_nb}{update['n_bins']} "
                f"| IV={update['iv']:.4f} | mono={update['is_monotonic']}"
            )

        logger.info(f"[refine_cate] 完成,{len(target_feats)} 个类别特征处理完毕")
        return self

    @staticmethod
    def _bin_label(edges: list, bin_idx: int, n_bins: int,
                   decimals: Optional[int] = None) -> str:
        """生成普通分箱区间字符串,bin_idx 为 0-based。

        decimals=None  → 使用 .8g(8 位有效数字),确保 load_woe_bins() 反向
                         重建 edges 时精度足够。
        decimals=N     → 使用 :.Nf(固定 N 位小数),便于人工阅读。
        """
        def _fmt(v: float) -> str:
            return f"{v:.{decimals}f}" if decimals is not None else f"{v:.8g}"

        if not edges:
            return "(-∞, +∞)"
        if bin_idx == 0:
            return f"(-∞, {_fmt(float(edges[0]))}]"
        elif bin_idx == n_bins - 1:
            return f"({_fmt(float(edges[-1]))}, +∞)"
        else:
            return f"({_fmt(float(edges[bin_idx-1]))}, {_fmt(float(edges[bin_idx]))}]"

    # ── 1. get_final_bins ────────────────────────────────────────────

    def get_final_bins(self) -> Dict[str, pd.DataFrame]:
        """
        返回每个特征的最终分箱区间 + WOE 明细(含特殊值箱)。

        特殊值箱追加在普通箱之后,bin_no 继续编号,bin_label 为 '[sv=xxx]'。

        Returns
        -------
        dict: {feature_name -> pd.DataFrame}
            DataFrame 列: bin_no | bin_label | n | bad | good |
                          bad_rate | pct_n | lift |
                          pct_bad | pct_good | woe | iv | cumiv
                          is_special (bool, True=特殊值箱)

            其中:
              pct_n    = 该箱样本量 / 所有箱样本量之和(含特殊值箱)
              lift     = 该箱 bad_rate / 全局平均 bad_rate
                         全局 bad_rate 取 self._bad_rate(fit 时记录);
                         若未 fit 则退化为所有箱 bad 之和 / n 之和
        """
        self._check_fitted()
        result = {}
        for feat, vr in self._results.items():
            wt     = vr["woe_table"].copy().sort_values("bin").reset_index(drop=True)
            edges  = vr["edges"]
            n_bins = vr["n_bins"]

            wt["bin_no"]    = wt["bin"] + 1
            if vr.get("is_categorical"):
                # 类别特征:箱标签即类别取值本身,已存于 woe_table,无需重建
                if "bin_label" not in wt.columns:
                    wt["bin_label"] = wt["bin"].astype(str)
            else:
                wt["bin_label"] = [
                    self._bin_label(edges, int(row["bin"]), n_bins,
                                    self.bin_label_decimals)
                    for _, row in wt.iterrows()
                ]
            wt["cumiv"]     = wt["iv"].cumsum()
            wt["is_special"] = False

            # 追加特殊值箱
            sv_table = vr.get("sv_table", pd.DataFrame())
            if len(sv_table) > 0:
                sv_rows = []
                base_bin_no = len(wt) + 1
                running_cumiv = float(wt["cumiv"].iloc[-1]) if len(wt) > 0 else 0.0
                for i, (_, svrow) in enumerate(sv_table.iterrows()):
                    running_cumiv += float(svrow["iv"])
                    sv_rows.append({
                        "bin_no"    : base_bin_no + i,
                        "bin_label" : svrow["bin_label"],
                        "n"         : int(svrow["n"]),
                        "bad"       : int(svrow["bad"]),
                        "good"      : int(svrow["good"]),
                        "bad_rate"  : float(svrow["bad_rate"]),
                        "pct_bad"   : float(svrow["pct_bad"]),
                        "pct_good"  : float(svrow["pct_good"]),
                        "woe"       : float(svrow["woe"]),
                        "iv"        : float(svrow["iv"]),
                        "cumiv"     : round(running_cumiv, 6),
                        "is_special": True,
                    })
                sv_df = pd.DataFrame(sv_rows)
                wt = pd.concat([wt, sv_df], ignore_index=True)

            # ── 计算 pct_n 和 lift ──
            total_n = float(wt["n"].sum())
            # 全局 bad_rate:优先用 fit() 时记录的,否则从分箱数据反推
            avg_bad_rate = getattr(self, "_bad_rate", None)
            if avg_bad_rate is None or avg_bad_rate == 0:
                total_bad_all  = float(wt["bad"].sum())
                total_good_all = float(wt["good"].sum()) if "good" in wt.columns else 0.0
                avg_bad_rate   = total_bad_all / (total_bad_all + total_good_all) if (total_bad_all + total_good_all) > 0 else self.eps

            wt["pct_n"] = wt["n"] / total_n if total_n > 0 else 0.0
            wt["lift"]  = wt["bad_rate"].apply(
                lambda br: round(br / avg_bad_rate, 4) if avg_bad_rate > 0 else 0.0
            )

            # ── 补全可能缺失或 NaN 的列(格式 B 加载时 woe_table 无这些列,
            #    pd.concat 后普通箱行为 NaN)──
            _eps = self.eps
            if "good" not in wt.columns or wt["good"].isna().any():
                wt["good"] = wt["good"].fillna(0)
            if "bad_rate" not in wt.columns or wt["bad_rate"].isna().any():
                g = wt["good"].fillna(0) if "good" in wt.columns else 0
                wt["bad_rate"] = wt["bad"] / (wt["bad"] + g + _eps)
            # pct_bad / pct_good:只对普通箱(non-special)重算;sv 行保持 0.0
            _need_pct = (
                "pct_bad"  not in wt.columns or wt["pct_bad"].isna().any() or
                "pct_good" not in wt.columns or wt["pct_good"].isna().any()
            )
            if _need_pct:
                _normal_mask = ~wt["is_special"].astype(bool) if "is_special" in wt.columns                                else pd.Series(True, index=wt.index)
                _total_bad   = float(wt.loc[_normal_mask, "bad"].sum())
                _total_good  = float(wt.loc[_normal_mask, "good"].sum())
                if "pct_bad" not in wt.columns:
                    wt["pct_bad"]  = 0.0
                if "pct_good" not in wt.columns:
                    wt["pct_good"] = 0.0
                wt.loc[_normal_mask, "pct_bad"]  = (
                    wt.loc[_normal_mask, "bad"]  / (_total_bad  + _eps)
                )
                wt.loc[_normal_mask, "pct_good"] = (
                    wt.loc[_normal_mask, "good"] / (_total_good + _eps)
                )

            cols = ["bin_no", "bin_label", "n", "bad", "good",
                    "bad_rate", "pct_n", "lift",
                    "pct_bad", "pct_good", "woe", "iv", "cumiv", "is_special"]
            result[feat] = wt[[c for c in cols if c in wt.columns]]
        return result

    # ── 1a2. get_bin_edges ────────────────────────────────────────────

    def get_bin_edges(self) -> Dict[str, List[float]]:
        """
        返回每个特征的完整分箱边界列表(含 ±inf 端点),可直接用于
        ``pd.cut``、``get_gains_table`` 等下游函数。

        返回的边界列表与 ``get_final_bins()`` 中的普通箱 bin_label
        一一对应:若边界为 ``[-inf, 1.5, 3.0, inf]``,则对应的三个
        普通箱分别为 ``(-∞, 1.5]``、``(1.5, 3.0]``、``(3.0, +∞)``。

        **注意**:特殊值箱(如 ``[sv=-1]``、``[Missing]``)不包含在
        边界列表中 — 它们独立于普通分箱,由 ``MonotoneWOEBinner``
        在 ``apply_woe()`` 时自动处理。类别特征(``cate_feats``)同样
        不包含在内(无数值边界),其 WOE 映射由 ``apply_woe()`` 直接按取值查表。

        Returns
        -------
        dict: ``{feature_name: [-inf, cut1, cut2, ..., inf]}``
            每个特征的完整分箱边界列表,首尾固定为 ``-np.inf``
            和 ``np.inf``。

        Example
        -------
        >>> binner = MonotoneWOEBinner(feature_cols=["score"], target_col="is_bad")
        >>> binner.fit(df)
        >>> binner.get_bin_edges()
        {'score': [-inf, 450.0, 520.0, 600.0, 680.0, inf]}

        >>> # 可直接用于下游分箱
        >>> edges = binner.get_bin_edges()["score"]
        >>> df["score_bin"] = pd.cut(df["score"], bins=edges, labels=False)
        """
        self._check_fitted()
        result = {}
        for feat, vr in self._results.items():
            if vr.get("is_categorical"):
                # 类别特征无数值边界,不适用 pd.cut,跳过
                continue
            edges = [float(e) for e in vr["edges"]]
            result[feat] = [-np.inf] + edges + [np.inf]
        return result

    # ── 1b. load_woe_bins ────────────────────────────────────────────

    def load_woe_bins(self, bins_dict: dict) -> "MonotoneWOEBinner":
        """
        直接加载已有的分箱结果,跳过 fit()。支持两种输入格式:

        格式 A — get_final_bins() 的输出:
            {feature_name -> DataFrame}
            DataFrame 必须包含列: bin_label | n | bad | woe | iv
            (可含 is_special 列;无则假设全为普通箱)
            类别特征自动识别:若普通箱 bin_label 不是数值区间格式(如 "(-∞, 1.5]"),
            则按类别特征加载,apply_woe 时按取值直接查表。

        格式 B — 训练流水线 woe_results 格式:
            {feature_name -> dict},dict 包含:
              edges        : list,含 ±inf 端点,如 [-inf, 1.5, 3.0, inf]
              woe_map      : {bin_index -> woe_value}
              missing_woe  : float
              bin_df       : DataFrame,含列 b | n | nb | br | woe | pct
              total_iv     : float(可选;若无则从 bin_df 推算)
              n_bins       : int(可选)

        两种格式可在同一个 bins_dict 中混合使用。

        Returns
        -------
        self (支持链式调用)
        """
        self._results = {}

        for feat, payload in bins_dict.items():

            # ── 判断格式 ──────────────────────────────────────────────
            if isinstance(payload, pd.DataFrame):
                # 格式 A(直接是 DataFrame)
                fmt = "A"
                df_bin = payload
            elif isinstance(payload, dict) and "woe_map" in payload:
                # 格式 B(dict with edges / woe_map / bin_df)
                fmt = "B"
            elif isinstance(payload, dict):
                # 格式 A 包在 dict 里(不常见,兼容)
                fmt = "A"
                df_bin = payload.get("bin_df") or payload.get("df")
                if df_bin is None:
                    raise ValueError(
                        f"特征 '{feat}': dict 格式既无 'woe_map' 也无 'bin_df',无法识别格式"
                    )
            else:
                raise ValueError(
                    f"特征 '{feat}': 不支持的类型 {type(payload)},"
                    "期望 DataFrame 或含 woe_map 的 dict"
                )

            # 类别特征标记(格式 A 自动识别;格式 B 暂不支持类别特征)
            is_categorical = False

            # ════════════════════════════════════════════════════════
            # 格式 A 处理路径
            # ════════════════════════════════════════════════════════
            if fmt == "A":
                required_cols = {"bin_label", "n", "bad", "woe", "iv"}
                missing = required_cols - set(df_bin.columns)
                if missing:
                    raise ValueError(f"特征 '{feat}' 的分箱表缺少列: {missing}")

                df_bin = df_bin.copy().reset_index(drop=True)

                if "is_special" in df_bin.columns:
                    sv_mask   = df_bin["is_special"].astype(bool)
                    df_normal = df_bin[~sv_mask].copy()
                    df_sv     = df_bin[sv_mask].copy()
                else:
                    df_normal = df_bin.copy()
                    df_sv     = pd.DataFrame()

                # 自动识别类别特征:普通箱标签不全是数值区间格式 → 类别特征
                _norm_labels = df_normal["bin_label"].astype(str).tolist()
                is_categorical = (
                    len(_norm_labels) > 0
                    and not all(self._looks_like_interval(l) for l in _norm_labels)
                )

                woe_table = df_normal.copy()
                woe_table["bin"] = range(len(df_normal))
                if is_categorical:
                    edges = []   # 类别特征无数值边界
                    # 还原成员类别:支持 refine_cate 合并后的 "A | B | C" 标签
                    # 每个成员 int → float → 原字符串,供 apply_woe 精确匹配
                    _members = [
                        [self._infer_cat_value(p) for p in lbl.split(_CATE_GROUP_SEP)]
                        for lbl in _norm_labels
                    ]
                    woe_table["cat_members"] = _members
                    woe_table["cat_value"]   = [
                        ms[0] if len(ms) == 1 else np.nan for ms in _members
                    ]
                else:
                    edges = self._reconstruct_edges(_norm_labels)
                sv_table  = df_sv.copy() if len(df_sv) > 0 else pd.DataFrame()
                total_iv  = float(df_bin["iv"].sum())
                n_bins    = len(df_normal)
                woes      = df_normal["woe"].values if len(df_normal) > 0 else np.array([])
                missing_woe = 0.0   # 格式 A 无此字段,用中性 WOE

            # ════════════════════════════════════════════════════════
            # 格式 B 处理路径
            # ════════════════════════════════════════════════════════
            else:  # fmt == "B"
                raw_edges   = list(payload["edges"])   # 含首尾 ±inf
                woe_map     = payload["woe_map"]       # {int -> float}
                missing_woe = float(payload.get("missing_woe", 0.0))
                bin_df      = payload.get("bin_df", pd.DataFrame())
                total_iv    = float(payload.get("total_iv", 0.0))

                # edges:去掉首尾 ±inf,只保留内部切割点
                import math as _math
                edges = [
                    float(e) for e in raw_edges
                    if not (_math.isinf(float(e)) or _math.isnan(float(e)))
                ]

                n_bins = len(woe_map)

                # 构建 woe_table(与格式 A 的 woe_table 列对齐)
                if len(bin_df) > 0:
                    bdf = bin_df.copy().reset_index(drop=True)
                    # 列名映射:bin_df 用 b/nb/br/pct,woe_table 用 bin/bad/bad_rate/pct_n
                    rename_map = {}
                    if "b"  in bdf.columns and "bin" not in bdf.columns:
                        rename_map["b"]   = "bin"
                    if "nb" in bdf.columns and "bad" not in bdf.columns:
                        rename_map["nb"]  = "bad"
                    if "br" in bdf.columns and "bad_rate" not in bdf.columns:
                        rename_map["br"]  = "bad_rate"
                    if "pct" in bdf.columns and "pct_n" not in bdf.columns:
                        rename_map["pct"] = "pct_n"
                    bdf = bdf.rename(columns=rename_map)

                    # 确保有 woe 列(用 woe_map 覆盖,保证精度一致)
                    bdf["woe"] = bdf["bin"].map({int(k): float(v)
                                                 for k, v in woe_map.items()})

                    # 补充 good 列(若缺)
                    if "good" not in bdf.columns:
                        bdf["good"] = 0

                    # 补充 iv 列(若缺)
                    if "iv" not in bdf.columns:
                        total_bad  = bdf["bad"].sum()
                        total_good = bdf["good"].sum() if "good" in bdf.columns else 0
                        eps = self.eps
                        def _iv_row(r):
                            pb = r["bad"]  / (total_bad  + eps)
                            pg = r["good"] / (total_good + eps) if total_good > 0 else eps
                            return (pb - pg) * r["woe"]
                        bdf["iv"] = bdf.apply(_iv_row, axis=1)
                        if total_iv == 0.0:
                            total_iv = float(bdf["iv"].sum())

                    # 确保有 bin_label 列(从 edges 生成)
                    if "bin_label" not in bdf.columns:
                        labels = self._make_bin_labels(edges, n_bins, self.bin_label_decimals)
                        bdf["bin_label"] = labels[: len(bdf)]

                    woe_table = bdf.copy()
                else:
                    # bin_df 缺失,从 woe_map + edges 最小化构建
                    labels = self._make_bin_labels(edges, n_bins)
                    woe_table = pd.DataFrame({
                        "bin":       list(range(n_bins)),
                        "bin_label": labels,
                        "woe":       [float(woe_map[k]) for k in sorted(woe_map)],
                        "n":         [0] * n_bins,
                        "bad":       [0] * n_bins,
                        "good":      [0] * n_bins,
                        "bad_rate":  [0.0] * n_bins,
                        "pct_n":     [0.0] * n_bins,
                        "iv":        [0.0] * n_bins,
                    })

                woes = np.array([float(woe_map[k]) for k in sorted(woe_map)])

                # ── 根据 self.special_values 自动构建 sv_table ──
                # 格式 B 没有 sv 的统计数据,但有 missing_woe;
                # 用 missing_woe 作为 WOE,n/bad/good 等统计量置为 0(占位)。
                sv_rows = []
                for sv_val in (self.special_values or []):
                    import math as _math2
                    is_nan_sv = (sv_val is None or
                                 (isinstance(sv_val, float) and _math2.isnan(sv_val)))
                    lbl = "[Missing]" if is_nan_sv else f"[sv={sv_val}]"
                    sv_rows.append({
                        "bin_label": lbl,
                        "sv":        "__nan__" if is_nan_sv else sv_val,
                        "n":         0,
                        "bad":       0,
                        "good":      0,
                        "bad_rate":  0.0,
                        "pct_bad":   0.0,
                        "pct_good":  0.0,
                        "woe":       missing_woe,
                        "iv":        0.0,
                    })
                sv_table = pd.DataFrame(sv_rows) if sv_rows else pd.DataFrame()

            # ── 写入 _results ─────────────────────────────────────────
            res = dict(
                edges        = edges,
                woe_table    = woe_table,
                sv_table     = sv_table,
                iv           = round(total_iv, 6),
                missing_woe  = missing_woe,
                is_monotonic = self._is_monotone(woes) if len(woes) > 1 else True,
                n_bins       = n_bins,
            )
            if is_categorical:
                res["is_categorical"] = True
                res["categories"] = (
                    [m for ms in woe_table["cat_members"] for m in ms]
                    if "cat_members" in woe_table.columns else []
                )
            self._results[feat] = res

        # 同步 feature_cols
        existing = set(self.feature_cols)
        for feat in bins_dict:
            if feat not in existing:
                self.feature_cols.append(feat)

        self._is_fitted = True
        logger.info(f"[load_woe_bins] 加载完成: {len(self._results)} 个特征")
        return self

    @staticmethod
    def _make_bin_labels(edges: List[float], n_bins: int,
                         decimals: Optional[int] = None) -> List[str]:
        """
        从内部切割点 edges(不含 ±inf)生成 bin_label 字符串列表。
        例如 edges=[1.5, 3.0], n_bins=3 →
            ["(-∞, 1.5]", "(1.5, 3.0]", "(3.0, +∞)"]

        decimals=None → :.8g;decimals=N → :.Nf(固定 N 位小数)。
        """
        def _fmt(v: float) -> str:
            return f"{v:.{decimals}f}" if decimals is not None else f"{v:.8g}"

        labels = []
        all_edges = [-float("inf")] + list(edges) + [float("inf")]
        for i in range(n_bins):
            lo = all_edges[i]
            hi = all_edges[i + 1]
            lo_s = "-∞" if lo == -float("inf") else _fmt(lo)
            hi_s = "+∞" if hi ==  float("inf") else _fmt(hi)
            if i == 0:
                labels.append(f"(-∞, {hi_s}]")
            elif i == n_bins - 1:
                labels.append(f"({lo_s}, +∞)")
            else:
                labels.append(f"({lo_s}, {hi_s}]")
        return labels

    @staticmethod
    def _reconstruct_edges(bin_labels: List[str]) -> List[float]:
        """
        从 bin_label 列表反向推断切割点 edges。
        例如 ["(-∞, 1.5]", "(1.5, 3.0]", "(3.0, +∞)"] → [1.5, 3.0]
        若解析失败则返回空列表。
        """
        import re
        edges = []
        for lbl in bin_labels[:-1]:   # 最后一箱没有右边界可提取
            # 匹配 "(xxx, yyy]" 或 "(-∞, yyy]" 格式的右端点
            m = re.search(r",\s*([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)\s*\]", lbl)
            if m:
                try:
                    edges.append(float(m.group(1)))
                except ValueError:
                    pass
        return edges

    @staticmethod
    def _looks_like_interval(label: str) -> bool:
        """判断 bin_label 是否为数值区间格式,如 (-∞, 1.5] / (1.5, 3] / (3, +∞)。

        用于 load_woe_bins 区分数值特征与类别特征:类别特征的 bin_label 是
        类别取值本身(任意字符串),不符合该区间格式。
        """
        import re
        _num = r"(?:[+-]?∞|[+-]?inf|[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)"
        return bool(re.match(rf"^\(\s*{_num}\s*,\s*{_num}\s*[\]\)]$", str(label).strip()))

    @staticmethod
    def _infer_cat_value(label):
        """从 bin_label 还原类别原始取值:能转 int 则 int,能转 float 则 float,否则原字符串。"""
        s = str(label)
        try:
            f = float(s)
        except (ValueError, OverflowError):
            return s
        i = int(f)
        return i if i == f else f

    # ── 2. apply_woe ─────────────────────────────────────────────────

    def apply_woe(
        self,
        data: pd.DataFrame,
        suffix: str = "_woe",
        inplace: bool = False,
    ) -> pd.DataFrame:
        """
        将 data 中的特征原始数值转换为 WOE 值,添加 *_woe 列。

        特殊值处理:
          - 若某值在 special_values 中,直接查 sv_table 获取对应 WOE
          - NaN:若 nan 在 special_values 中则查 sv_table;否则填 missing_woe
          - 普通值:按 edges 做 pd.cut,然后查 woe_table

        类别特征(cate_feats)处理:
          - 按取值直接查表取 WOE(不做区间切分)
          - NaN → [Missing] 箱 WOE(若 fit 时存在缺失),否则 missing_woe
          - 训练时未出现过的新类别 → missing_woe(中性)

        Parameters
        ----------
        data    : 含原始特征列的 DataFrame
        suffix  : WOE 列后缀,默认 "_woe"
        inplace : 是否在原 DataFrame 上操作(False = 返回副本)

        Returns
        -------
        DataFrame,新增 {feat}{suffix} 列
        """
        self._check_fitted()
        df = data if inplace else data.copy()
        woe_outputs: Dict[str, np.ndarray] = {}

        for feat, vr in self._results.items():
            if feat not in df.columns:
                logger.info(f"  [WARN] '{feat}' 不在 data 中,跳过")
                continue

            sv_table    = vr.get("sv_table", pd.DataFrame())
            woe_col     = feat + suffix
            # 优先使用 _results 中存储的 per-feature missing_woe(格式 B 加载时设置)
            feat_missing_woe = float(vr.get("missing_woe", self.missing_woe))

            series = df[feat]

            # 构建特殊值 → WOE 映射(数值/类别特征通用,主要用于 NaN/[Missing])
            sv_woe_map: Dict = {}
            if len(sv_table) > 0 and "bin_label" in sv_table.columns:
                for _, svrow in sv_table.iterrows():
                    lbl = svrow["bin_label"]
                    sv_woe_val = float(svrow["woe"])
                    # 解析 bin_label 还原特殊值
                    if lbl == "[Missing]":
                        sv_woe_map["__nan__"] = sv_woe_val
                    else:
                        import re
                        m = re.match(r"\[sv=(.*)\]$", lbl)
                        if m:
                            raw = m.group(1)
                            try:
                                sv_woe_map[float(raw)] = sv_woe_val
                                sv_woe_map[int(float(raw))] = sv_woe_val
                            except (ValueError, OverflowError):
                                sv_woe_map[raw] = sv_woe_val

            # ── 类别特征:按取值直接查 WOE,不做区间切分 ──
            if vr.get("is_categorical"):
                wt = vr["woe_table"]
                # 原始取值 → WOE(fit 路径,精确匹配;int/float 由 dict 等价性兼容)
                # refine_cate 聚类后,一个箱含多个类别(cat_members);逐成员展开建表
                cat_woe_map: Dict = {}
                cat_woe_map_str: Dict = {}
                for _, r in wt.iterrows():
                    woe_v = float(r["woe"])
                    if "cat_members" in wt.columns and isinstance(r["cat_members"], (list, tuple)):
                        members = r["cat_members"]
                    elif "cat_value" in wt.columns and not pd.isna(r["cat_value"]):
                        members = [r["cat_value"]]
                    else:
                        members = []
                    for cv in members:
                        if pd.isna(cv):
                            continue
                        cat_woe_map[cv]            = woe_v   # 精确匹配
                        cat_woe_map_str[str(cv)]   = woe_v   # 类型不一致时回退匹配
                    # 整箱标签也登记一次(兜底;通常不会命中真实类别)
                    if "bin_label" in wt.columns:
                        cat_woe_map_str.setdefault(str(r["bin_label"]), woe_v)
                nan_woe = float(sv_woe_map.get("__nan__", feat_missing_woe))
                missing_mask = series.isna()
                if cat_woe_map:
                    mapped = series.map(cat_woe_map)
                else:
                    mapped = pd.Series(np.nan, index=series.index, dtype=float)

                fallback_mask = mapped.isna() & ~missing_mask
                if cat_woe_map_str and fallback_mask.any():
                    mapped.loc[fallback_mask] = (
                        series.loc[fallback_mask].astype(str).map(cat_woe_map_str)
                    )

                out = np.full(len(series), feat_missing_woe, dtype=float)
                missing_arr = missing_mask.to_numpy()
                if missing_arr.any():
                    out[missing_arr] = nan_woe
                hit_arr = mapped.notna().to_numpy() & ~missing_arr
                if hit_arr.any():
                    out[hit_arr] = mapped.to_numpy(dtype=float)[hit_arr]

                woe_outputs[woe_col] = out.astype(float, copy=False)
                continue


            # ── 数值特征:按 edges 做 bin 查找 ──
            edges  = [float(e) for e in vr["edges"]]
            wt_map = vr["woe_table"].set_index("bin")["woe"].to_dict()

            out = np.full(len(series), feat_missing_woe, dtype=float)

            is_missing = series.isna().to_numpy()
            if is_missing.any():
                out[is_missing] = float(sv_woe_map.get("__nan__", feat_missing_woe))

            special_mask = np.zeros(len(series), dtype=bool)
            for sv_val, sv_woe in sv_woe_map.items():
                if sv_val == "__nan__":
                    continue
                try:
                    mask = series.eq(sv_val).to_numpy(dtype=bool, na_value=False)
                except TypeError:
                    mask = series.astype(object).eq(sv_val).to_numpy(dtype=bool, na_value=False)
                if mask.any():
                    out[mask] = float(sv_woe)
                    special_mask |= mask

            normal_mask = ~(is_missing | special_mask)
            if normal_mask.any():
                if not edges:
                    out[normal_mask] = float(wt_map.get(0, feat_missing_woe))
                else:
                    try:
                        values_arr = series.to_numpy(dtype=float, copy=False, na_value=np.nan)
                    except (TypeError, ValueError):
                        values_arr = pd.to_numeric(series, errors="coerce").to_numpy(dtype=float)
                    normal_values = values_arr[normal_mask]
                    valid_values = ~np.isnan(normal_values)
                    if valid_values.any():
                        normal_pos = np.flatnonzero(normal_mask)
                        valid_pos = normal_pos[valid_values]
                        bin_idx = np.searchsorted(
                            np.asarray(edges, dtype=float),
                            normal_values[valid_values],
                            side="right",
                        )
                        woe_values = np.full(len(edges) + 1, feat_missing_woe, dtype=float)
                        for bin_key, woe_val in wt_map.items():
                            try:
                                bin_i = int(bin_key)
                            except (TypeError, ValueError):
                                continue
                            if 0 <= bin_i < len(woe_values):
                                woe_values[bin_i] = float(woe_val)
                        out[valid_pos] = woe_values[bin_idx]

            woe_outputs[woe_col] = out.astype(float, copy=False)
            continue

        if not woe_outputs:
            return df
        woe_df = pd.DataFrame(woe_outputs, index=df.index)
        if inplace:
            df.loc[:, list(woe_df.columns)] = woe_df
            return df
        existing = [col for col in woe_df.columns if col in df.columns]
        if existing:
            df = df.drop(columns=existing)
        return pd.concat([df, woe_df], axis=1)

    # ── 3. export_woe_report ─────────────────────────────────────────

    def export_woe_report(self, report_path: str) -> None:
        """
        将所有特征的分箱结果输出为 Excel 报告(使用 SuperModelingFactory
        的 ExcelMaster 工具包写入)。

        Sheet 列表
        ----------
        Sheet 1 「WOE分箱明细」: 汇总表 + 逐特征明细(含特殊值箱,紫色标注)
        Sheet 2 「WOE分箱图」  : 每个特征嵌入整体 WOE 图

        Parameters
        ----------
        report_path : 输出路径,如 "woe_report.xlsx"
        """
        self._check_fitted()
        from ExcelMaster.ExcelMaster import ExcelMaster

        bins_dict = self.get_final_bins()
        os.makedirs(os.path.dirname(os.path.abspath(report_path)), exist_ok=True)

        em = ExcelMaster(report_path, verbose=False, gap_number=1)
        wb = em.workbook   # 底层 xlsxwriter workbook,用于自定义数字 / 颜色格式

        # 自定义单元格格式(set_cell_format 可直接接受 format 对象)
        _base    = {"border": 1, "align": "center", "valign": "vcenter",
                    "font_name": "Calibri", "font_size": 9}
        fmt_pct  = wb.add_format({**_base, "num_format": "0.00%"})
        fmt_num4 = wb.add_format({**_base, "num_format": "0.0000"})
        fmt_num2 = wb.add_format({**_base, "num_format": "0.00"})
        # 特殊值行:仅叠加紫底紫字(与上面的数字格式叠加生效)
        fmt_sv   = wb.add_format({"bg_color": "#E8D5F5",
                                  "font_color": "#5B2C6F", "bold": True})

        # ═══════════════════════════════════════════════════════════════
        # Sheet 1: WOE分箱明细
        # ═══════════════════════════════════════════════════════════════
        ws = em.add_worksheet("WOE分箱明细")

        # 顶部总标题
        em.merge_col(ws, ncols=13, text="各特征 WOE 分箱明细", cformat="BLUE_H1")

        # ── 汇总表 ──
        summary_rows = []
        for i, (feat, vr) in enumerate(self._results.items(), 1):
            wt   = vr["woe_table"]
            sv_t = vr.get("sv_table", pd.DataFrame())
            woes = wt.sort_values("bin")["woe"].values if len(wt) > 0 else np.array([])
            if vr.get("is_categorical"):
                direction = "类别"
            else:
                direction = "↑ 递增" if (len(woes) >= 2 and woes[-1] > woes[0]) else "↓ 递减"
            summary_rows.append({
                "序号": i, "特征名": feat, "普通箱数": vr["n_bins"],
                "特殊值箱数": len(sv_t) if len(sv_t) > 0 else 0,
                "总IV值": round(float(vr["iv"]), 4),
                "WOE方向": direction,
                "是否单调": "✓" if vr["is_monotonic"] else "✗",
            })
        summary_df = pd.DataFrame(summary_rows)
        em.write_dataframe(ws, summary_df, title="▌ 汇总:各特征 IV 一览",
                           index=False, header=True)

        # ── 逐特征明细 ──
        col_rename = {
            "bin_no": "分箱编号", "bin_label": "分箱区间", "n": "样本量",
            "bad": "坏样本数", "good": "好样本数", "bad_rate": "箱内坏样本率",
            "pct_n": "样本占比", "lift": "Lift", "pct_bad": "坏件分布占比",
            "pct_good": "好件分布占比", "woe": "WOE值", "iv": "IV贡献", "cumiv": "累计IV",
        }
        order   = list(col_rename.keys())
        pct_cn  = {"箱内坏样本率", "样本占比", "坏件分布占比", "好件分布占比"}
        num4_cn = {"WOE值", "IV贡献", "累计IV"}
        num2_cn = {"Lift"}

        for seq, (feat, wt_df) in enumerate(bins_dict.items(), 1):
            vr   = self._results[feat]
            cols = [c for c in order if c in wt_df.columns]
            ddf  = wt_df[cols].rename(columns=col_rename)

            sv_mask = (wt_df["is_special"].astype(bool).tolist()
                       if "is_special" in wt_df.columns else [False] * len(wt_df))
            n_normal = vr["n_bins"]
            sv_hint  = f"   |   特殊值箱={sum(sv_mask)}" if any(sv_mask) else ""
            title = (f"  [{seq:02d}] {feat}   |   IV={vr['iv']:.4f}   "
                     f"|   普通箱={vr['n_bins']}{sv_hint}   "
                     f"|   单调={'✓' if vr['is_monotonic'] else '✗'}")

            loc = em.write_dataframe(ws, ddf, title=title, index=False,
                                     header=True, titleformat="BLUE_H4",
                                     retCellRange="value")
            r0, c0, r1, c1 = loc
            data_r0 = r0 + 2          # 跳过 title(1) + header(1)
            data_r1 = r1
            colpos  = {name: c0 + idx for idx, name in enumerate(ddf.columns)}

            # 列数字格式
            for cn, fmt in ([(c, fmt_pct)  for c in pct_cn]
                            + [(c, fmt_num4) for c in num4_cn]
                            + [(c, fmt_num2) for c in num2_cn]):
                if cn in colpos:
                    cc = colpos[cn]
                    em.set_cell_format(ws, [data_r0, cc, data_r1, cc], fmt)

            # WOE / Lift 列色阶(仅普通箱行,避免特殊值极端值干扰色阶)
            if n_normal > 0:
                nb_r1 = data_r0 + n_normal - 1
                if "WOE值" in colpos:
                    cc = colpos["WOE值"]
                    em.set_color_scale(ws, [data_r0, cc, nb_r1, cc],
                                       colors=("#F4B183", "#FFFFFF", "#A9D08E"))
                if "Lift" in colpos:
                    cc = colpos["Lift"]
                    em.set_color_scale(ws, [data_r0, cc, nb_r1, cc],
                                       colors=("#9DC3E6", "#FFFFFF", "#F4B183"))

            # 特殊值行整行紫色(叠加在数字格式之上)
            for ri, is_sv in enumerate(sv_mask):
                if is_sv:
                    rr = data_r0 + ri
                    em.set_cell_format(ws, [rr, c0, rr, c1], fmt_sv)

            # 特殊值图例注释
            if any(sv_mask):
                em.merge_col(ws, ncols=13,
                             text="  ★ 紫色行为特殊值独立分箱,WOE 独立计算,不参与单调约束",
                             cformat="TEXT_ITALIC")

        # ═══════════════════════════════════════════════════════════════
        # Sheet 2: WOE分箱图(每个特征嵌入整体 WOE 图)
        # ═══════════════════════════════════════════════════════════════
        ws2 = em.add_worksheet("WOE分箱图")
        em.merge_col(ws2, ncols=11, text="各特征 WOE 分箱图(整体)", cformat="BLUE_H1")

        # 注意: xlsxwriter 的 insert_image 延迟到 close 时才读取图片文件,
        #       因此 close_workbook() 必须在 tempdir 仍存活时调用。
        with tempfile.TemporaryDirectory() as tmpdir:
            for feat_idx, (feat, wt_df) in enumerate(bins_dict.items()):
                vr        = self._results[feat]
                normal_df = (wt_df[~wt_df["is_special"].astype(bool)]
                             if "is_special" in wt_df.columns else wt_df)
                sv_df     = (wt_df[wt_df["is_special"].astype(bool)]
                             if "is_special" in wt_df.columns else pd.DataFrame())

                # 渲染整体 WOE 图并落盘(insert_image 需要文件路径)
                img_buf   = self._render_woe_chart(
                    feat, normal_df, sv_df, vr, dpi=120, figsize=(9, 4.5),
                )
                safe_feat = feat.replace("/", "_").replace("\\", "_")
                img_path  = os.path.join(tmpdir, f"{safe_feat}.png")
                with open(img_path, "wb") as f:
                    f.write(img_buf.getbuffer())

                # 特征标题
                em.merge_col(
                    ws2, ncols=11,
                    text=(f"  [{feat_idx+1:02d}] {feat}   |   IV={vr['iv']:.4f}   "
                          f"|   普通箱={vr['n_bins']}   "
                          f"|   单调={'✓' if vr['is_monotonic'] else '✗'}"
                          + (f"   |   特殊值箱={len(sv_df)}" if len(sv_df) > 0 else "")),
                    cformat="BLUE_H4",
                )
                # 插入图片(缩放到合适大小)
                em.insert_image(ws2, figPath=img_path, figScale=(0.62, 0.62),
                                skipby="row")

            em.close_workbook()

        logger.info(f"[export_woe_report] 报告已保存至: {report_path}  "
                    f"(ExcelMaster, 含图片Sheet)")

    def _render_woe_chart(
        self,
        feat: str,
        normal_df: pd.DataFrame,
        sv_df: pd.DataFrame,
        vr: Dict,
        dpi: int = 120,
        figsize: tuple = (9, 4.5),
    ) -> io.BytesIO:
        """
        渲染单个特征的 WOE 复合图,返回 BytesIO(PNG 格式)。
        普通箱:stacked 柱图 + WOE 折线 + 标注框
        特殊值箱:独立虚线柱(右侧追加)+ 标注框,使用不同颜色
        """
        GOOD_COLOR = "#5BBCD6"
        BAD_COLOR  = "#F4856A"
        WOE_COLOR  = "#2E75B6"
        SV_GOOD    = "#A8D8A8"   # 特殊值箱好样本(浅绿)
        SV_BAD     = "#F7B7A3"   # 特殊值箱坏样本(浅橙)
        SV_WOE     = "#8E44AD"   # 特殊值箱 WOE 线(紫)

        n_normal = len(normal_df)
        n_sv     = len(sv_df)
        n_total  = n_normal + n_sv

        if n_total == 0:
            fig, ax = plt.subplots(figsize=figsize)
            ax.text(0.5, 0.5, "No data", ha="center", va="center")
            buf = io.BytesIO()
            plt.savefig(buf, format="png", dpi=dpi, bbox_inches="tight")
            plt.close(fig)
            buf.seek(0)
            return buf

        fig, ax_bar = plt.subplots(figsize=figsize)
        ax_woe = ax_bar.twinx()

        x_normal = np.arange(n_normal)
        x_sv     = np.arange(n_normal, n_total)
        x_all    = np.arange(n_total)

        # ── 普通箱柱图 ──
        pct_bad_n  = normal_df["pct_bad"].values  if n_normal > 0 else np.array([])
        pct_good_n = normal_df["pct_good"].values if n_normal > 0 else np.array([])
        if n_normal > 0:
            ax_bar.bar(x_normal, pct_good_n, color=GOOD_COLOR, alpha=0.85,
                       label="0 (Good)", width=0.6, zorder=2)
            ax_bar.bar(x_normal, pct_bad_n, bottom=pct_good_n, color=BAD_COLOR,
                       alpha=0.85, label="1 (Bad)", width=0.6, zorder=2)

        # ── 特殊值箱柱图(虚边框区分)──
        pct_bad_sv  = sv_df["pct_bad"].values  if n_sv > 0 else np.array([])
        pct_good_sv = sv_df["pct_good"].values if n_sv > 0 else np.array([])
        if n_sv > 0:
            ax_bar.bar(x_sv, pct_good_sv, color=SV_GOOD, alpha=0.85,
                       width=0.6, zorder=2, edgecolor="#888", linewidth=1.2,
                       linestyle="--", label="0 (sv)")
            ax_bar.bar(x_sv, pct_bad_sv, bottom=pct_good_sv, color=SV_BAD,
                       alpha=0.85, width=0.6, zorder=2, edgecolor="#888",
                       linewidth=1.2, linestyle="--", label="1 (sv)")

            # 特殊值箱分隔线(用数据坐标,避免 bbox_inches='tight' 拉伸)
            ax_bar.axvline(x=n_normal - 0.5, color="#888", linewidth=1.2,
                           linestyle=":", zorder=3, label="_nolegend_")
            ax_bar.text(n_normal - 0.35, 0.93, "Special",
                        fontsize=7.5, color="#8E44AD", va="top",
                        transform=ax_bar.transData)

        # ── 普通箱 WOE 线 ──
        woe_n   = normal_df["woe"].values  if n_normal > 0 else np.array([])
        br_n    = normal_df["bad_rate"].values if n_normal > 0 else np.array([])
        if n_normal > 0:
            ax_woe.plot(x_normal, woe_n, color=WOE_COLOR, marker="o",
                        linewidth=2, markersize=6, zorder=5, label="WOE (normal)")

        # ── 特殊值箱 WOE 线(断开,虚线)──
        woe_sv  = sv_df["woe"].values  if n_sv > 0 else np.array([])
        br_sv   = sv_df["bad_rate"].values if n_sv > 0 else np.array([])
        if n_sv > 0:
            ax_woe.plot(x_sv, woe_sv, color=SV_WOE, marker="D",
                        linewidth=1.5, markersize=6, linestyle="--",
                        zorder=5, label="WOE (special)")

        # ── 标注框(普通箱)──
        bar_ylim_max = 1.0
        label_offset = 0.04
        label_margin = 0.02

        def _annotate(ax_b, ax_w, xi, wv, br, pt_good, pt_bad,
                      lift=None, pct_n=None, fc="white", ec="black"):
            lines = [f"WOE: {wv:.3f}", f"BR: {br:.2%}"]
            if lift is not None:
                lines.append(f"Lift: {lift:.2f}x  |  {pct_n:.1%}"
                             if pct_n is not None else f"Lift: {lift:.2f}x")
            label_txt = "\n".join(lines)
            bar_top   = pt_good + pt_bad
            y_above   = bar_top + label_offset
            if y_above + label_margin <= bar_ylim_max:
                y_text  = y_above
                va_text = "bottom"
            else:
                y_text  = min(bar_ylim_max - label_margin, bar_top) - 0.02
                va_text = "top"
            wv_clamped = max(-1.0, min(1.0, wv))
            ax_b.annotate(
                label_txt,
                xy=(xi, wv_clamped), xycoords=("data", ax_w.transData),
                xytext=(xi, y_text),
                textcoords=("data", ax_b.transData),
                fontsize=6.5, va=va_text, ha="center",
                bbox=dict(boxstyle="round,pad=0.3", fc=fc, ec=ec, lw=0.7),
                arrowprops=dict(arrowstyle="-", color=ec, lw=0.7),
            )

        lift_n  = normal_df["lift"].values  if "lift"  in normal_df.columns and n_normal > 0 else [None]*n_normal
        pct_n_n = normal_df["pct_n"].values if "pct_n" in normal_df.columns and n_normal > 0 else [None]*n_normal

        for xi, (wv, br, pg, pb, lv, pn) in enumerate(
                zip(woe_n, br_n, pct_good_n, pct_bad_n, lift_n, pct_n_n)):
            _annotate(ax_bar, ax_woe, xi, wv, br, pg, pb, lift=lv, pct_n=pn)

        # 特殊值箱标注(紫色,复用 _annotate)
        lift_sv  = sv_df["lift"].values  if "lift"  in sv_df.columns and n_sv > 0 else [None]*n_sv
        pct_n_sv = sv_df["pct_n"].values if "pct_n" in sv_df.columns and n_sv > 0 else [None]*n_sv
        for i, (xi, wv, br, pg, pb, lv, pn) in enumerate(
                zip(x_sv, woe_sv, br_sv, pct_good_sv, pct_bad_sv, lift_sv, pct_n_sv)):
            _annotate(ax_bar, ax_woe, xi, wv, br, pg, pb,
                      lift=lv, pct_n=pn, fc="#F5EEF8", ec="#8E44AD")

        # ── 轴格式 ──
        all_labels = (
            [str(b) for b in normal_df["bin_label"]]
            + ([str(b) for b in sv_df["bin_label"]] if n_sv > 0 else [])
        )
        ax_bar.set_xlim(-0.5, n_total - 0.5)
        ax_bar.set_ylim(0, 1.0)
        ax_woe.set_ylim(-1.0, 1.0)
        ax_woe.axhline(0, color="gray", linewidth=0.6, linestyle="--", zorder=1)

        ax_bar.set_xticks(x_all)
        ax_bar.set_xticklabels(
            [textwrap.fill(lb, width=13) for lb in all_labels],
            fontsize=7.5, rotation=30, ha="right",
        )
        ax_bar.set_ylabel("Proportion", fontsize=9)
        ax_bar.yaxis.set_major_formatter(mticker.PercentFormatter(xmax=1, decimals=0))
        ax_bar.tick_params(axis="y", labelsize=8)
        ax_woe.set_ylabel("WOE", fontsize=9, color="#333")
        ax_woe.tick_params(axis="y", labelsize=8)
        ax_bar.grid(axis="y", alpha=0.3, zorder=0)
        ax_bar.set_axisbelow(True)

        # 图例定位策略:
        # 有 sv 时:两个 legend 合并放在 special 区域内当前最右一个 sv 笔的正上方(y=1.0 上边界)
        # 无 sv 时:Target legend 放右上角
        handles, labels = ax_bar.get_legend_handles_labels()
        if n_sv > 0:
            # 合并 bar 和 woe 的全部句柄 → 一个 legend
            woe_handles = [l for l in ax_woe.get_lines()
                           if not l.get_label().startswith("_")]
            all_handles = handles + woe_handles
            all_labels  = labels + [l.get_label() for l in woe_handles]
            # 锚点在最右 sv bin 的中心 x, y=1.0(ax_bar 上边界)
            anchor_x = n_total - 1.0   # 最右一个 bin 的 x
            ax_bar.legend(all_handles, all_labels,
                          loc="upper right",
                          bbox_to_anchor=(anchor_x, 1.0),
                          bbox_transform=ax_bar.transData,
                          fontsize=7.0, framealpha=0.88,
                          ncol=2, borderpad=0.35, handlelength=1.2)
        else:
            ax_bar.legend(handles, labels,
                          loc="upper right",
                          fontsize=7.0, framealpha=0.85,
                          title="Target", title_fontsize=7.0,
                          ncol=2, borderpad=0.35, handlelength=1.2)

        iv_total = vr["iv"]
        plt.title(f"{feat}:  IV={iv_total:.3f}", fontsize=11, fontweight="bold", pad=8)
        plt.tight_layout()

        buf = io.BytesIO()
        plt.savefig(buf, format="png", dpi=dpi, bbox_inches="tight")
        plt.close(fig)
        buf.seek(0)
        return buf

    # ── 4. plot_woe_graph ────────────────────────────────────────────

    def plot_woe_graph(
        self,
        graph_path: str,
        group_name: Optional[str] = None,
        _df_for_group: Optional[pd.DataFrame] = None,
        dpi: int = 150,
        figsize: tuple = (9, 6),
        bar_mode: str = "clustered",
    ) -> None:
        """
        为每个特征绘制复合图(线图 + Stack 柱图),保存到 graph_path 目录。

        整体图(group_name=None):
          - 普通箱 stacked 柱图 + WOE 折线 + 标注框
          - 若有特殊值箱,追加在右侧(虚边框 + 紫色标注)
          - 标题:"{feat}:  IV={iv:.3f}"

        分组图(group_name 不为 None):每个 group 一条 WOE 折线(仅普通箱),
        柱图样式由 bar_mode 控制:
          - "pooled"          : 单套柱,全量好坏占比(占全量样本)
          - "clustered"       : 每个箱位置并排各组柱,柱高=占【该组】总样本(默认)
          - "small_multiples" : 每个 group 一个子图 panel,各画该组组内占比柱
                                + 该组 WOE 线(WOE y 轴跨 panel 统一,便于对比)
          - 标题:"{feat}:  IV_range={min}−{max}"

        Parameters
        ----------
        graph_path     : 图片保存目录(自动创建)
        group_name     : 分组列名(如 "month"),None = 画整体图
        _df_for_group  : 含原始特征+target+group_name 的 DataFrame(group 模式必填)
        dpi            : 图片分辨率,默认 150
        figsize        : 图片尺寸,默认 (9, 6)。small_multiples 模式下为单个 panel
                         的基准尺寸,整图按子图网格自动放大
        bar_mode       : 分组图柱样式,"pooled" | "clustered" | "small_multiples",
                         默认 "clustered"。group_name=None(整体图)时此参数忽略
        """
        self._check_fitted()
        _valid_bar_modes = {"pooled", "clustered", "small_multiples"}
        if bar_mode not in _valid_bar_modes:
            raise ValueError(
                f"bar_mode 必须是 {_valid_bar_modes} 之一,收到: {bar_mode!r}"
            )
        os.makedirs(graph_path, exist_ok=True)
        bins_dict = self.get_final_bins()

        GOOD_COLOR = "#5BBCD6"
        BAD_COLOR  = "#F4856A"
        WOE_COLOR_OVERALL = "#2E75B6"
        SV_GOOD    = "#A8D8A8"
        SV_BAD     = "#F7B7A3"
        SV_WOE     = "#8E44AD"

        for feat, wt_df in bins_dict.items():
            vr = self._results[feat]
            edges  = [float(e) for e in vr["edges"]]

            # 分离普通箱和特殊值箱
            if "is_special" in wt_df.columns:
                normal_df = wt_df[~wt_df["is_special"].astype(bool)].copy()
                sv_df     = wt_df[wt_df["is_special"].astype(bool)].copy()
            else:
                normal_df = wt_df.copy()
                sv_df     = pd.DataFrame()

            n_normal  = len(normal_df)
            n_sv      = len(sv_df)
            n_total   = n_normal + n_sv
            iv_overall = vr["iv"]

            x_normal = np.arange(n_normal)
            x_sv     = np.arange(n_normal, n_total)
            x_all    = np.arange(n_total)

            # ── small_multiples 独立路径:每组一个子图,自建多子图 figure ──
            if group_name is not None and bar_mode == "small_multiples":
                self._plot_feat_small_multiples(
                    feat, normal_df, sv_df,
                    n_normal, n_sv, n_total, x_normal, x_sv, x_all,
                    group_name, _df_for_group, graph_path, dpi, figsize,
                    GOOD_COLOR, BAD_COLOR, SV_GOOD, SV_BAD, SV_WOE,
                )
                continue

            fig, ax_bar = plt.subplots(figsize=figsize)
            ax_woe = ax_bar.twinx()

            pct_bad_n  = normal_df["pct_bad"].values  if n_normal > 0 else np.array([])
            pct_good_n = normal_df["pct_good"].values if n_normal > 0 else np.array([])
            pct_bad_sv  = sv_df["pct_bad"].values  if n_sv > 0 else np.array([])
            pct_good_sv = sv_df["pct_good"].values if n_sv > 0 else np.array([])

            if group_name is None:
                # ── 整体图 ──
                if n_normal > 0:
                    ax_bar.bar(x_normal, pct_good_n, color=GOOD_COLOR,
                               alpha=0.85, label="0", width=0.6, zorder=2)
                    ax_bar.bar(x_normal, pct_bad_n, bottom=pct_good_n,
                               color=BAD_COLOR, alpha=0.85, label="1",
                               width=0.6, zorder=2)

                if n_sv > 0:
                    ax_bar.bar(x_sv, pct_good_sv, color=SV_GOOD, alpha=0.85,
                               width=0.6, zorder=2, edgecolor="#888",
                               linewidth=1.2, linestyle="--")
                    ax_bar.bar(x_sv, pct_bad_sv, bottom=pct_good_sv, color=SV_BAD,
                               alpha=0.85, width=0.6, zorder=2, edgecolor="#888",
                               linewidth=1.2, linestyle="--")
                    ax_bar.axvline(x=n_normal - 0.5, color="#888",
                                   linewidth=1.2, linestyle=":", zorder=3)
                    # 注意: 用数据坐标而非 get_xaxis_transform(),避免 bbox_inches='tight' 拉伸
                    ax_bar.text(n_normal - 0.35, 0.93, "Special",
                                fontsize=8, color=SV_WOE, va="top",
                                transform=ax_bar.transData)

                # WOE 线(普通箱)
                woe_n  = normal_df["woe"].values  if n_normal > 0 else np.array([])
                br_n   = normal_df["bad_rate"].values if n_normal > 0 else np.array([])
                if n_normal > 0:
                    ax_woe.plot(x_normal, woe_n, color=WOE_COLOR_OVERALL,
                                marker="o", linewidth=2, markersize=6, zorder=5)

                # WOE 线(特殊值箱)
                woe_sv = sv_df["woe"].values  if n_sv > 0 else np.array([])
                br_sv  = sv_df["bad_rate"].values if n_sv > 0 else np.array([])
                if n_sv > 0:
                    ax_woe.plot(x_sv, woe_sv, color=SV_WOE, marker="D",
                                linewidth=1.5, markersize=6, linestyle="--", zorder=5)

                # 标注框(普通箱)
                bar_ylim_max = 1.0
                label_offset = 0.04
                label_margin = 0.02

                lift_nn  = normal_df["lift"].values  if "lift"  in normal_df.columns and n_normal > 0 else [None]*n_normal
                pct_n_nn = normal_df["pct_n"].values if "pct_n" in normal_df.columns and n_normal > 0 else [None]*n_normal
                for xi, (wv, br, lv, pn) in enumerate(zip(woe_n, br_n, lift_nn, pct_n_nn)):
                    lines_txt = [f"WOE: {wv:.3f}", f"BR: {br:.2%}"]
                    if lv is not None:
                        lines_txt.append(f"Lift: {lv:.2f}x  |  {pn:.1%}"
                                         if pn is not None else f"Lift: {lv:.2f}x")
                    label_txt = "\n".join(lines_txt)
                    bar_top   = pct_good_n[xi] + pct_bad_n[xi]
                    y_above   = bar_top + label_offset
                    if y_above + label_margin <= bar_ylim_max:
                        y_text, va_text = y_above, "bottom"
                    else:
                        y_text = min(bar_ylim_max - label_margin, bar_top) - 0.02
                        va_text = "top"
                    ax_bar.annotate(
                        label_txt,
                        xy=(xi, wv), xycoords=("data", ax_woe.transData),
                        xytext=(xi, y_text),
                        textcoords=("data", ax_bar.transData),
                        fontsize=7.0, va=va_text, ha="center",
                        zorder=10,
                        bbox=dict(boxstyle="round,pad=0.3", fc="white",
                                  ec="black", lw=0.8, zorder=10),
                        arrowprops=dict(arrowstyle="-", color="black", lw=0.8),
                    )

                # 标注框(特殊值箱,紫色)
                lift_sv2  = sv_df["lift"].values  if "lift"  in sv_df.columns and n_sv > 0 else [None]*n_sv
                pct_n_sv2 = sv_df["pct_n"].values if "pct_n" in sv_df.columns and n_sv > 0 else [None]*n_sv
                for xi, (wv, br, pg, pb, lv, pn) in enumerate(
                        zip(woe_sv, br_sv, pct_good_sv, pct_bad_sv, lift_sv2, pct_n_sv2)):
                    xi_abs = n_normal + xi
                    lines_sv = [f"WOE: {wv:.3f}", f"BR: {br:.2%}"]
                    if lv is not None:
                        lines_sv.append(f"Lift: {lv:.2f}x  |  {pn:.1%}"
                                        if pn is not None else f"Lift: {lv:.2f}x")
                    label_txt = "\n".join(lines_sv)
                    bar_top   = pg + pb
                    y_above   = bar_top + label_offset
                    if y_above + label_margin <= bar_ylim_max:
                        y_text, va_text = y_above, "bottom"
                    else:
                        y_text = min(bar_ylim_max - label_margin, bar_top) - 0.02
                        va_text = "top"
                    ax_bar.annotate(
                        label_txt,
                        xy=(xi_abs, wv), xycoords=("data", ax_woe.transData),
                        xytext=(xi_abs, y_text),
                        textcoords=("data", ax_bar.transData),
                        fontsize=7.0, va=va_text, ha="center",
                        zorder=10,
                        bbox=dict(boxstyle="round,pad=0.3", fc="#F5EEF8",
                                  ec=SV_WOE, lw=0.9, zorder=10),
                        arrowprops=dict(arrowstyle="-", color=SV_WOE, lw=0.8),
                    )

                # Legend: sv 区域右上角内部,有 sv 时合并两个 legend
                bar_handles, bar_labels = ax_bar.get_legend_handles_labels()
                if n_sv > 0:
                    woe_handles2 = [l for l in ax_woe.get_lines()
                                    if not l.get_label().startswith("_")]
                    all_h = bar_handles + woe_handles2
                    all_l = bar_labels + [l.get_label() for l in woe_handles2]
                    anchor_x2 = n_total - 1.0
                    ax_bar.legend(all_h, all_l,
                                  loc="upper right",
                                  bbox_to_anchor=(anchor_x2, 1.0),
                                  bbox_transform=ax_bar.transData,
                                  fontsize=8.0, framealpha=0.88,
                                  ncol=2, borderpad=0.35, handlelength=1.2)
                else:
                    ax_bar.legend(bar_handles, bar_labels,
                                  loc="upper right",
                                  fontsize=8.0, framealpha=0.88,
                                  title="Target", title_fontsize=8.0,
                                  ncol=2, borderpad=0.35)
                ax_woe.set_ylabel("WOE (TargetRate)", fontsize=9, color="#333")
                title = f"{feat}:  IV={iv_overall:.3f}"

            else:
                # ── By-group 图 ──
                if _df_for_group is None:
                    logger.info(f"  [WARN] group_name='{group_name}' 需要传入 _df_for_group,跳过 {feat}")
                    plt.close(fig)
                    continue
                if group_name not in _df_for_group.columns or feat not in _df_for_group.columns:
                    logger.info(f"  [WARN] group '{group_name}' 或 feature '{feat}' 不在 DataFrame 中")
                    plt.close(fig)
                    continue

                # ── 用拟合好的 edges 对各 group 分别分箱 ──
                fitted_edges = list(vr["edges"])
                eps = self.eps

                groups   = sorted(_df_for_group[group_name].dropna().unique())
                n_groups = len(groups)
                # tab10 调色板,最多 10 种颜色循环
                cmap_colors = plt.cm.tab10(np.linspace(0, 0.9, min(max(n_groups,1), 10)))
                group_ivs = []

                # WOE 基准:全量 total_bad / total_good(各组 WOE 相对全量,保证跨组可比)
                all_normal_df, all_sv_groups = self._split_special_for_plot(_df_for_group, feat, vr)
                all_normal_sub = all_normal_df[[feat, self.target_col]].dropna(subset=[feat]).copy()
                all_normal_sub["_bin"] = self._assign_normal_bins(
                    all_normal_sub, feat, vr, fitted_edges)
                all_normal_sub = all_normal_sub[all_normal_sub["_bin"].notna()]
                all_total_bad  = float(all_normal_sub[self.target_col].sum())
                all_total_good = float((all_normal_sub[self.target_col] == 0).sum())

                # ── 柱图模式:pooled(全量单套柱)vs clustered(各组并排柱)──
                if bar_mode == "pooled":
                    # 全量普通箱比例(分母 = 全量普通行数)
                    all_n_full = len(all_normal_sub)
                    pct_good_n_grp = np.zeros(n_normal)
                    pct_bad_n_grp  = np.zeros(n_normal)
                    for b in range(n_normal):
                        grp_b  = all_normal_sub[all_normal_sub["_bin"] == b]
                        bad_b  = float(grp_b[self.target_col].sum())
                        good_b = float((grp_b[self.target_col] == 0).sum())
                        pct_good_n_grp[b] = good_b / (all_n_full + eps) if all_n_full > 0 else 0.0
                        pct_bad_n_grp[b]  = bad_b  / (all_n_full + eps) if all_n_full > 0 else 0.0
                    # 全量特殊值箱比例(分母 = 全量行数)
                    all_sv_n = len(_df_for_group)
                    pct_good_sv_grp = np.zeros(n_sv)
                    pct_bad_sv_grp  = np.zeros(n_sv)
                    if n_sv > 0:
                        for si, sv_row in enumerate(sv_df.itertuples()):
                            matched_sv_df = None
                            for sv_key, sv_sub in all_sv_groups.items():
                                if _sv_label(sv_key) == sv_row.bin_label:
                                    matched_sv_df = sv_sub
                                    break
                            if matched_sv_df is not None and len(matched_sv_df) > 0:
                                pct_good_sv_grp[si] = float((matched_sv_df[self.target_col] == 0).sum()) / (all_sv_n + eps)
                                pct_bad_sv_grp[si]  = float(matched_sv_df[self.target_col].sum()) / (all_sv_n + eps)
                    # 画全量单套柱
                    if n_normal > 0:
                        ax_bar.bar(x_normal, pct_good_n_grp, color=GOOD_COLOR,
                                   alpha=0.45, width=0.6, zorder=2)
                        ax_bar.bar(x_normal, pct_bad_n_grp, bottom=pct_good_n_grp,
                                   color=BAD_COLOR, alpha=0.45, width=0.6, zorder=2)
                    if n_sv > 0:
                        ax_bar.bar(x_sv, pct_good_sv_grp, color=SV_GOOD, alpha=0.35,
                                   width=0.6, zorder=2, edgecolor="#888",
                                   linewidth=1.0, linestyle="--")
                        ax_bar.bar(x_sv, pct_bad_sv_grp, bottom=pct_good_sv_grp,
                                   color=SV_BAD, alpha=0.35, width=0.6, zorder=2,
                                   edgecolor="#888", linewidth=1.0, linestyle="--")
                else:  # clustered:每个箱位置并排 n_groups 根柱,柱宽均分簇宽
                    cluster_w = 0.8                       # 每个箱簇占据的总宽度
                    bar_w     = cluster_w / max(n_groups, 1)

                # 特殊值分隔线 + 标注(pooled / clustered 公共)
                if n_sv > 0:
                    ax_bar.axvline(x=n_normal - 0.5, color="#888",
                                   linewidth=1.0, linestyle=":", zorder=3)
                    ax_bar.text(n_normal + 0.05, 0.93, "Special",
                                fontsize=8, color=SV_WOE, va="top",
                                transform=ax_bar.transData)

                # 逐组:算 WOE 折线(clustered 时另画该组组内占比柱)
                for gi, grp_val in enumerate(groups):
                    grp_df_full = _df_for_group[_df_for_group[group_name] == grp_val]
                    n_grp = len(grp_df_full)
                    tr    = grp_df_full[self.target_col].mean() if n_grp > 0 else 0.0
                    clr   = cmap_colors[gi % len(cmap_colors)]

                    # 分离该组的特殊值与普通行,并按 edges/类别取值分箱
                    grp_normal_df, grp_sv_groups = self._split_special_for_plot(grp_df_full, feat, vr)
                    grp_sub = grp_normal_df[[feat, self.target_col]].dropna(subset=[feat]).copy()
                    grp_sub["_bin"] = self._assign_normal_bins(grp_sub, feat, vr, fitted_edges)
                    grp_sub = grp_sub[grp_sub["_bin"].notna()]

                    # 普通箱:组内占比(分母=该组总样本 n_grp)+ WOE(相对全量基准)
                    pct_good_n_g = np.zeros(n_normal)
                    pct_bad_n_g  = np.zeros(n_normal)
                    grp_woe = []
                    grp_iv  = 0.0
                    for b in range(n_normal):
                        bin_rows = grp_sub[grp_sub["_bin"] == b]
                        bad_b  = float(bin_rows[self.target_col].sum())
                        good_b = float((bin_rows[self.target_col] == 0).sum())
                        pct_good_n_g[b] = good_b / (n_grp + eps)
                        pct_bad_n_g[b]  = bad_b  / (n_grp + eps)
                        if len(bin_rows) == 0:
                            grp_woe.append(np.nan)
                            continue
                        pct_bad_w  = bad_b  / (all_total_bad  + eps)
                        pct_good_w = good_b / (all_total_good + eps)
                        woe_b = math.log((pct_bad_w + eps) / (pct_good_w + eps))
                        grp_iv += (pct_bad_w - pct_good_w) * woe_b
                        grp_woe.append(woe_b)

                    # ── clustered:画该组组内占比柱(边框用组色,与 WOE 折线对应)──
                    if bar_mode == "clustered":
                        x_off      = -cluster_w / 2 + bar_w * (gi + 0.5)
                        x_normal_g = x_normal + x_off
                        x_sv_g     = x_sv + x_off

                        pct_good_sv_g = np.zeros(n_sv)
                        pct_bad_sv_g  = np.zeros(n_sv)
                        if n_sv > 0:
                            for si, sv_row in enumerate(sv_df.itertuples()):
                                matched_sv_df = None
                                for sv_key, sv_sub in grp_sv_groups.items():
                                    if _sv_label(sv_key) == sv_row.bin_label:
                                        matched_sv_df = sv_sub
                                        break
                                if matched_sv_df is not None and len(matched_sv_df) > 0:
                                    pct_good_sv_g[si] = float((matched_sv_df[self.target_col] == 0).sum()) / (n_grp + eps)
                                    pct_bad_sv_g[si]  = float(matched_sv_df[self.target_col].sum()) / (n_grp + eps)

                        if n_normal > 0:
                            ax_bar.bar(x_normal_g, pct_good_n_g, color=GOOD_COLOR,
                                       alpha=0.55, width=bar_w, zorder=2,
                                       edgecolor=clr, linewidth=0.8)
                            ax_bar.bar(x_normal_g, pct_bad_n_g, bottom=pct_good_n_g,
                                       color=BAD_COLOR, alpha=0.55, width=bar_w, zorder=2,
                                       edgecolor=clr, linewidth=0.8)
                        if n_sv > 0:
                            ax_bar.bar(x_sv_g, pct_good_sv_g, color=SV_GOOD,
                                       alpha=0.5, width=bar_w, zorder=2,
                                       edgecolor=clr, linewidth=0.8, linestyle="--")
                            ax_bar.bar(x_sv_g, pct_bad_sv_g, bottom=pct_good_sv_g,
                                       color=SV_BAD, alpha=0.5, width=bar_w, zorder=2,
                                       edgecolor=clr, linewidth=0.8, linestyle="--")

                    # ── 画该组 WOE 折线(画在箱中心 x_normal,便于跨组对齐对比)──
                    if n_grp < 5 or grp_df_full[self.target_col].nunique() < 2:
                        group_ivs.append(0.0)
                        lbl = f"{grp_val}  N={n_grp:,}  TR={tr:.1%}  IV=0.000"
                        ax_woe.plot(x_normal, [np.nan] * n_normal,
                                    color=clr, linewidth=1.5, marker="o",
                                    markersize=4, zorder=5, label=lbl)
                    else:
                        group_ivs.append(round(grp_iv, 4))
                        lbl = f"{grp_val}  N={n_grp:,}  TR={tr:.1%}  IV={grp_iv:.3f}"
                        ax_woe.plot(x_normal, grp_woe, color=clr,
                                    linewidth=1.5, marker="o", markersize=4,
                                    zorder=5, label=lbl)

                # Legend: 所有条目合并,放坐标轴右侧外部(更靠右,避免遮挡 WOE y轴标题)
                _bar_desc   = "pooled %" if bar_mode == "pooled" else "in-group %"
                dummy_good  = plt.Rectangle((0,0),1,1, color=GOOD_COLOR, alpha=0.6)
                dummy_bad   = plt.Rectangle((0,0),1,1, color=BAD_COLOR,  alpha=0.6)
                woe_lines_h = [l for l in ax_woe.get_lines()
                               if not l.get_label().startswith("_")]
                woe_labels_h = [l.get_label() for l in woe_lines_h]
                all_handles  = [dummy_good, dummy_bad] + woe_lines_h
                all_labels_l = ["0 (Good)", "1 (Bad)"] + woe_labels_h
                ax_bar.legend(all_handles, all_labels_l,
                              loc="center left",
                              bbox_to_anchor=(1.18, 0.5),
                              bbox_transform=ax_bar.transAxes,
                              fontsize=7.5, framealpha=0.92,
                              ncol=1, borderpad=0.5, handlelength=1.5,
                              title=f"Group WOE (bar={_bar_desc})", title_fontsize=8.0)

                iv_vals  = [v for v in group_ivs if v > 0]
                iv_range = (f"{min(iv_vals):.3f}-{max(iv_vals):.3f}"
                            if iv_vals else "0.000-0.000")
                title = f"{feat}:  IV_range={iv_range}"
                ax_woe.set_ylabel("WOE", fontsize=9, color="#333")

            # ── 通用轴格式 ──
            all_labels = (
                [str(b) for b in normal_df["bin_label"]]
                + ([str(b) for b in sv_df["bin_label"]] if n_sv > 0 else [])
            )
            ax_bar.set_xlim(-0.5, n_total - 0.5)
            ax_bar.set_ylim(0, 1.0)

            # ── 动态计算 WOE y 轴范围(避免折线超出坐标轴)──
            # 收集所有已绘制折线上的有效 WOE 值
            _all_woe_pts = []
            for _line in ax_woe.get_lines():
                _yd = np.array(_line.get_ydata(), dtype=float)
                _all_woe_pts.extend(_yd[~np.isnan(_yd)].tolist())
            if _all_woe_pts:
                _woe_min = min(_all_woe_pts)
                _woe_max = max(_all_woe_pts)
                # padding: 15% of span, 最少 ±0.1 的绝对余量
                _span   = max(_woe_max - _woe_min, 0.2)
                _pad    = max(_span * 0.15, 0.1)
                _y_lo   = _woe_min - _pad
                _y_hi   = _woe_max + _pad
                # 至少覆盖 [-0.5, 0.5],且 0 刻度要在范围内
                _y_lo   = min(_y_lo, -0.5)
                _y_hi   = max(_y_hi,  0.5)
            else:
                _y_lo, _y_hi = -1.0, 1.0
            ax_woe.set_ylim(_y_lo, _y_hi)
            ax_woe.axhline(0, color="gray", linewidth=0.6, linestyle="--", zorder=1)

            ax_bar.set_xticks(x_all)
            ax_bar.set_xticklabels(
                [textwrap.fill(lb, width=14) for lb in all_labels],
                fontsize=8, rotation=30, ha="right",
            )
            ax_bar.set_ylabel("Proportion", fontsize=9)
            ax_bar.yaxis.set_major_formatter(mticker.PercentFormatter(xmax=1, decimals=0))
            ax_bar.tick_params(axis="y", labelsize=8)
            ax_woe.tick_params(axis="y", labelsize=8)
            ax_bar.grid(axis="y", alpha=0.3, zorder=0)
            ax_bar.set_axisbelow(True)

            plt.title(title, fontsize=11, fontweight="bold", pad=10)
            if group_name is not None:
                # by-group 模式:legend 在右侧外,预留右边空间(含 IV 文字,留更多右边距)
                plt.tight_layout(rect=[0, 0, 0.78, 1])
            else:
                plt.tight_layout()

            safe_feat  = feat.replace("/", "_").replace("\\", "_")
            suffix_str = f"_by_{group_name}" if group_name else ""
            out_file   = os.path.join(graph_path, f"{safe_feat}{suffix_str}.png")
            plt.savefig(out_file, dpi=dpi, bbox_inches="tight")
            plt.close(fig)
            logger.info(f"  [plot_woe_graph] {out_file}")

        logger.info(f"[plot_woe_graph] 全部图表已保存至: {graph_path}")

    def _plot_feat_small_multiples(
        self, feat, normal_df, sv_df,
        n_normal, n_sv, n_total, x_normal, x_sv, x_all,
        group_name, _df_for_group, graph_path, dpi, figsize,
        GOOD_COLOR, BAD_COLOR, SV_GOOD, SV_BAD, SV_WOE,
    ):
        """small_multiples 模式:每个 group 一个子图 panel。

        - 柱高 = 该箱样本 / 该组总样本(组内占比),good/bad 堆叠,含特殊值箱
        - WOE 相对全量基准计算;WOE y 轴范围跨全部 panel 统一,便于横向对比
        - 文件名后缀 _by_{group_name},与 pooled / clustered 模式一致
        """
        # ── guard(与单图路径一致)──
        if _df_for_group is None:
            logger.info(f"  [WARN] group_name='{group_name}' 需要传入 _df_for_group,跳过 {feat}")
            return
        if group_name not in _df_for_group.columns or feat not in _df_for_group.columns:
            logger.info(f"  [WARN] group '{group_name}' 或 feature '{feat}' 不在 DataFrame 中")
            return

        vr = self._results[feat]
        fitted_edges = list(vr["edges"])
        eps = self.eps

        all_labels = (
            [str(b) for b in normal_df["bin_label"]]
            + ([str(b) for b in sv_df["bin_label"]] if n_sv > 0 else [])
        )

        # WOE 基准:全量 total_bad / total_good
        all_normal_df, _ = self._split_special_for_plot(_df_for_group, feat, vr)
        all_normal_sub = all_normal_df[[feat, self.target_col]].dropna(subset=[feat]).copy()
        all_normal_sub["_bin"] = self._assign_normal_bins(
            all_normal_sub, feat, vr, fitted_edges)
        all_normal_sub = all_normal_sub[all_normal_sub["_bin"].notna()]
        all_total_bad  = float(all_normal_sub[self.target_col].sum())
        all_total_good = float((all_normal_sub[self.target_col] == 0).sum())

        groups   = sorted(_df_for_group[group_name].dropna().unique())
        n_groups = len(groups)
        if n_groups == 0:
            logger.info(f"  [WARN] group '{group_name}' 无有效取值,跳过 {feat}")
            return

        # 子图网格:最多 3 列
        ncols = min(n_groups, 3)
        nrows = math.ceil(n_groups / ncols)
        fig, axes = plt.subplots(
            nrows, ncols,
            figsize=(figsize[0] * 0.62 * ncols, figsize[1] * 0.62 * nrows),
            squeeze=False,
        )
        axes_flat = axes.flatten()

        group_ivs   = []
        woe_axes    = []
        all_woe_pts = []

        for gi, grp_val in enumerate(groups):
            ax_bar = axes_flat[gi]
            ax_woe = ax_bar.twinx()
            woe_axes.append(ax_woe)

            grp_df_full = _df_for_group[_df_for_group[group_name] == grp_val]
            n_grp = len(grp_df_full)
            tr    = grp_df_full[self.target_col].mean() if n_grp > 0 else 0.0

            grp_normal_df, grp_sv_groups = self._split_special_for_plot(grp_df_full, feat, vr)
            grp_sub = grp_normal_df[[feat, self.target_col]].dropna(subset=[feat]).copy()
            grp_sub["_bin"] = self._assign_normal_bins(grp_sub, feat, vr, fitted_edges)
            grp_sub = grp_sub[grp_sub["_bin"].notna()]

            # 普通箱:组内占比 + 组内 bad_rate + WOE(相对全量基准)
            pct_good_n_g = np.zeros(n_normal)
            pct_bad_n_g  = np.zeros(n_normal)
            grp_woe = []
            grp_br  = []      # 各箱组内 bad_rate(用于数据标签)
            grp_iv  = 0.0
            for b in range(n_normal):
                bin_rows = grp_sub[grp_sub["_bin"] == b]
                bad_b  = float(bin_rows[self.target_col].sum())
                good_b = float((bin_rows[self.target_col] == 0).sum())
                pct_good_n_g[b] = good_b / (n_grp + eps)
                pct_bad_n_g[b]  = bad_b  / (n_grp + eps)
                if len(bin_rows) == 0:
                    grp_woe.append(np.nan)
                    grp_br.append(np.nan)
                    continue
                grp_br.append(bad_b / (bad_b + good_b + eps))
                pct_bad_w  = bad_b  / (all_total_bad  + eps)
                pct_good_w = good_b / (all_total_good + eps)
                woe_b = math.log((pct_bad_w + eps) / (pct_good_w + eps))
                grp_iv += (pct_bad_w - pct_good_w) * woe_b
                grp_woe.append(woe_b)

            # 特殊值箱:组内占比 + WOE(相对全量基准)+ 组内 bad_rate
            pct_good_sv_g = np.zeros(n_sv)
            pct_bad_sv_g  = np.zeros(n_sv)
            sv_woe = [np.nan] * n_sv
            sv_br  = [np.nan] * n_sv
            if n_sv > 0:
                for si, sv_row in enumerate(sv_df.itertuples()):
                    matched_sv_df = None
                    for sv_key, sv_sub in grp_sv_groups.items():
                        if _sv_label(sv_key) == sv_row.bin_label:
                            matched_sv_df = sv_sub
                            break
                    if matched_sv_df is not None and len(matched_sv_df) > 0:
                        sv_bad_i  = float(matched_sv_df[self.target_col].sum())
                        sv_good_i = float((matched_sv_df[self.target_col] == 0).sum())
                        pct_good_sv_g[si] = sv_good_i / (n_grp + eps)
                        pct_bad_sv_g[si]  = sv_bad_i  / (n_grp + eps)
                        sv_br[si] = sv_bad_i / (sv_bad_i + sv_good_i + eps)
                        _pb = sv_bad_i  / (all_total_bad  + eps)
                        _pg = sv_good_i / (all_total_good + eps)
                        sv_woe[si] = math.log((_pb + eps) / (_pg + eps))

            # 柱(单套,good 下 bad 上)
            if n_normal > 0:
                ax_bar.bar(x_normal, pct_good_n_g, color=GOOD_COLOR,
                           alpha=0.85, width=0.6, zorder=2, label="0")
                ax_bar.bar(x_normal, pct_bad_n_g, bottom=pct_good_n_g,
                           color=BAD_COLOR, alpha=0.85, width=0.6, zorder=2, label="1")
            if n_sv > 0:
                ax_bar.bar(x_sv, pct_good_sv_g, color=SV_GOOD, alpha=0.85,
                           width=0.6, zorder=2, edgecolor="#888",
                           linewidth=1.0, linestyle="--")
                ax_bar.bar(x_sv, pct_bad_sv_g, bottom=pct_good_sv_g, color=SV_BAD,
                           alpha=0.85, width=0.6, zorder=2, edgecolor="#888",
                           linewidth=1.0, linestyle="--")
                ax_bar.axvline(x=n_normal - 0.5, color="#888",
                               linewidth=1.0, linestyle=":", zorder=3)
                ax_bar.text(n_normal + 0.05, 0.93, "Special",
                            fontsize=7, color=SV_WOE, va="top",
                            transform=ax_bar.transData)

            # WOE 折线(单色;范围统一在循环后设置)
            if n_grp < 5 or grp_df_full[self.target_col].nunique() < 2:
                group_ivs.append(0.0)
                iv_disp = 0.0
                ax_woe.plot(x_normal, [np.nan] * n_normal, color="#2E75B6",
                            linewidth=1.8, marker="o", markersize=5, zorder=5)
            else:
                group_ivs.append(round(grp_iv, 4))
                iv_disp = grp_iv
                ax_woe.plot(x_normal, grp_woe, color="#2E75B6",
                            linewidth=1.8, marker="o", markersize=5, zorder=5)
                all_woe_pts.extend([w for w in grp_woe if not np.isnan(w)])

                # 数据标签框(WOE / BR / Lift | 组内占比),仅普通箱有效点
                # lift 基准 = 该组整体 bad_rate (tr),每张小图自洽
                _ylim_max = 1.0
                for xi in range(n_normal):
                    wv = grp_woe[xi]
                    if np.isnan(wv):
                        continue
                    br = grp_br[xi]
                    pn = pct_good_n_g[xi] + pct_bad_n_g[xi]    # 组内占比 = 柱高
                    lv = br / (tr + eps) if tr > 0 else None
                    lines_txt = [f"WOE: {wv:.3f}", f"BR: {br:.2%}"]
                    lines_txt.append(f"Lift: {lv:.2f}x | {pn:.1%}"
                                     if lv is not None else f"{pn:.1%}")
                    bar_top = pn
                    y_above = bar_top + 0.04
                    if y_above + 0.02 <= _ylim_max:
                        y_text, va_text = y_above, "bottom"
                    else:
                        y_text  = min(_ylim_max - 0.02, bar_top) - 0.02
                        va_text = "top"
                    ax_bar.annotate(
                        "\n".join(lines_txt),
                        xy=(xi, wv), xycoords=("data", ax_woe.transData),
                        xytext=(xi, y_text), textcoords=("data", ax_bar.transData),
                        fontsize=5.5, va=va_text, ha="center", zorder=10,
                        bbox=dict(boxstyle="round,pad=0.2", fc="white",
                                  ec="#888", lw=0.6, zorder=10),
                        arrowprops=dict(arrowstyle="-", color="#888", lw=0.6),
                    )

                # 特殊值箱:紫色数据标签框(贴柱顶,含 WOE/BR/Lift|占比)
                # 不画 WOE 点、不纳入统一 y 轴,避免极端 sv WOE 压平普通折线
                for si in range(n_sv):
                    if np.isnan(sv_woe[si]):
                        continue
                    xi_abs = n_normal + si
                    br = sv_br[si]
                    pn = pct_good_sv_g[si] + pct_bad_sv_g[si]    # 组内占比 = 柱高
                    lv = br / (tr + eps) if tr > 0 else None
                    lines_sv = [f"WOE: {sv_woe[si]:.3f}", f"BR: {br:.2%}"]
                    lines_sv.append(f"Lift: {lv:.2f}x | {pn:.1%}"
                                    if lv is not None else f"{pn:.1%}")
                    y_above = pn + 0.04
                    if y_above + 0.02 <= _ylim_max:
                        y_text, va_text = y_above, "bottom"
                    else:
                        y_text  = min(_ylim_max - 0.02, pn) - 0.02
                        va_text = "top"
                    ax_bar.annotate(
                        "\n".join(lines_sv),
                        xy=(xi_abs, pn), xycoords="data",
                        xytext=(xi_abs, y_text), textcoords="data",
                        fontsize=5.5, va=va_text, ha="center", zorder=10,
                        bbox=dict(boxstyle="round,pad=0.2", fc="#F5EEF8",
                                  ec=SV_WOE, lw=0.7, zorder=10),
                        arrowprops=dict(arrowstyle="-", color=SV_WOE, lw=0.6),
                    )

            # panel 轴格式
            ax_bar.set_title(f"{grp_val}   N={n_grp:,}  TR={tr:.1%}  IV={iv_disp:.3f}",
                             fontsize=9, fontweight="bold")
            ax_bar.set_xlim(-0.5, n_total - 0.5)
            ax_bar.set_ylim(0, 1.0)
            ax_bar.set_xticks(x_all)
            ax_bar.set_xticklabels(
                [textwrap.fill(lb, width=12) for lb in all_labels],
                fontsize=6.5, rotation=30, ha="right",
            )
            ax_bar.set_ylabel("Proportion", fontsize=8)
            ax_bar.yaxis.set_major_formatter(mticker.PercentFormatter(xmax=1, decimals=0))
            ax_bar.tick_params(axis="y", labelsize=7)
            ax_woe.tick_params(axis="y", labelsize=7)
            ax_woe.set_ylabel("WOE", fontsize=8, color="#333")
            ax_bar.grid(axis="y", alpha=0.3, zorder=0)
            ax_bar.set_axisbelow(True)

        # 统一 WOE y 轴范围(跨 panel 可比)
        if all_woe_pts:
            _woe_min, _woe_max = min(all_woe_pts), max(all_woe_pts)
            _span = max(_woe_max - _woe_min, 0.2)
            _pad  = max(_span * 0.15, 0.1)
            _y_lo = min(_woe_min - _pad, -0.5)
            _y_hi = max(_woe_max + _pad,  0.5)
        else:
            _y_lo, _y_hi = -1.0, 1.0
        for axw in woe_axes:
            axw.set_ylim(_y_lo, _y_hi)
            axw.axhline(0, color="gray", linewidth=0.6, linestyle="--", zorder=1)

        # 隐藏多余空 panel
        for j in range(n_groups, nrows * ncols):
            axes_flat[j].axis("off")

        iv_vals  = [v for v in group_ivs if v > 0]
        iv_range = (f"{min(iv_vals):.3f}-{max(iv_vals):.3f}"
                    if iv_vals else "0.000-0.000")
        fig.suptitle(f"{feat}:  IV_range={iv_range}  (bar=in-group %)",
                     fontsize=12, fontweight="bold")

        fig.tight_layout(rect=[0, 0, 1, 0.97])
        safe_feat = feat.replace("/", "_").replace("\\", "_")
        out_file  = os.path.join(graph_path, f"{safe_feat}_by_{group_name}.png")
        fig.savefig(out_file, dpi=dpi, bbox_inches="tight")
        plt.close(fig)
        logger.info(f"  [plot_woe_graph] {out_file}")

    # ─────────────────────────────────────────────────────────────────
    # 便捷属性
    # ─────────────────────────────────────────────────────────────────

    @property
    def iv_summary(self) -> pd.DataFrame:
        """返回所有特征的 IV 汇总 DataFrame,按 IV 降序排列。"""
        self._check_fitted()
        rows = [
            {"feature": feat, "iv": vr["iv"],
             "n_bins": vr["n_bins"],
             "n_sv_bins": len(vr.get("sv_table", pd.DataFrame())),
             "is_monotonic": vr["is_monotonic"],
             "is_categorical": vr.get("is_categorical", False)}
            for feat, vr in self._results.items()
        ]
        return pd.DataFrame(rows).sort_values("iv", ascending=False).reset_index(drop=True)

    def __repr__(self) -> str:
        fitted = "fitted" if self._is_fitted else "not fitted"
        sv_hint  = f", special_values={self.special_values}" if self.special_values else ""
        cate_hint = f", cate_feats={len(self.cate_feats)}" if self.cate_feats else ""
        dec_hint = (f", bin_label_decimals={self.bin_label_decimals}"
                    if self.bin_label_decimals is not None else "")
        return (f"MonotoneWOEBinner({fitted}, "
                f"features={len(self.feature_cols)}, "
                f"n_init_bins={self.n_init_bins}{sv_hint}{cate_hint}{dec_hint})")

fit

fit(df: DataFrame, chi2_binning: bool = False, chi2_p: float = 0.99, chi2_init_size: int = 1000, n_jobs: int = 1) -> 'MonotoneWOEBinner'

在训练集上拟合所有特征的单调 WOE 分箱。

参数:

名称 类型 描述 默认
df DataFrame
必需
chi2_binning bool
         True 时:当相邻箱的卡方检验 p > (1 - chi2_p)时,
         尝试合并该对,并保持 WOE 单调。
False
chi2_p float
         较大的值(如 0.99)表示保留更多箱;
         较小的值(如 0.90)表示更容易合并。
0.99
chi2_init_size 卡方计算时的全局 stratified 采样上限,默认 1000。
         若普通行数 > chi2_init_size,按 target 比例分层采样,
         避免大数据集下卡方值虚高导致不该合并的箱被强行分开。
1000
n_jobs int
         设为 > 1 时使用指定数量的线程;设为 -1 时使用所有可用
         CPU 核心。特征数较多(如 3000+)时可显著提速。
1

返回:

类型 描述
self(支持链式调用)
源代码位于: Modeling_Tool/WOE/WOE_Monotone_Binner.py
def fit(
    self,
    df: pd.DataFrame,
    chi2_binning: bool = False,
    chi2_p: float = 0.99,
    chi2_init_size: int = 1000,
    n_jobs: int = 1,
) -> "MonotoneWOEBinner":
    """
    在训练集上拟合所有特征的单调 WOE 分箱。

    Parameters
    ----------
    df             : 训练集 DataFrame,需包含 feature_cols 和 target_col
    chi2_binning   : 是否在贪心单调分箱后再进行卡方后合并,默认 False。
                     True 时:当相邻箱的卡方检验 p > (1 - chi2_p)时,
                     尝试合并该对,并保持 WOE 单调。
    chi2_p         : 卡方检验置信度,默认 0.99。
                     较大的值(如 0.99)表示保留更多箱;
                     较小的值(如 0.90)表示更容易合并。
    chi2_init_size : 卡方计算时的全局 stratified 采样上限,默认 1000。
                     若普通行数 > chi2_init_size,按 target 比例分层采样,
                     避免大数据集下卡方值虚高导致不该合并的箱被强行分开。
    n_jobs         : 并行线程数,默认 1(顺序执行,行为与旧版完全相同)。
                     设为 > 1 时使用指定数量的线程;设为 -1 时使用所有可用
                     CPU 核心。特征数较多(如 3000+)时可显著提速。

    Returns
    -------
    self (支持链式调用)
    """
    # 待拟合的全部特征 = 数值特征 + 类别特征(去重,保持顺序)
    all_fit_feats = list(dict.fromkeys(list(self.feature_cols) + list(self.cate_feats)))

    missing_feats = [f for f in all_fit_feats if f not in df.columns]
    if missing_feats:
        raise ValueError(f"以下特征列不在 DataFrame 中: {missing_feats}")
    if self.target_col not in df.columns:
        raise ValueError(f"目标列 '{self.target_col}' 不在 DataFrame 中")

    # 检查 scipy 可用性
    if chi2_binning:
        try:
            from scipy.stats import chi2 as _chi2_check  # noqa
        except ImportError:
            raise ImportError(
                "chi2_binning=True 需要 scipy,请先安装: pip install scipy"
            )

    self._train_n        = len(df)
    self._bad_rate       = float(df[self.target_col].mean())
    self._chi2_binning   = chi2_binning
    self._chi2_p         = chi2_p
    self._chi2_init_size = chi2_init_size

    sv_hint   = f", special_values={self.special_values}" if self.special_values else ""
    cate_hint = f", cate_feats={len(self.cate_feats)}个" if self.cate_feats else ""
    chi2_hint = (f", chi2_binning=True (p={chi2_p}, sample={chi2_init_size})"
                 if chi2_binning else "")
    logger.info(f"[MonotoneWOEBinner] 开始拟合 {len(all_fit_feats)} 个特征"
          f"{sv_hint}{cate_hint}{chi2_hint} ...")

    if n_jobs == 0:
        raise ValueError("n_jobs 不能为 0;请使用正整数或 -1(全部核心)")

    def _fit_one(feat):
        try:
            res = self._greedy_fit_one(
                df, feat,
                chi2_binning   = chi2_binning,
                chi2_p         = chi2_p,
                chi2_init_size = chi2_init_size,
            )
            return feat, res, None
        except Exception as exc:
            import traceback as _tb
            return feat, None, (exc, _tb.format_exc())

    def _log_feat(feat, res):
        mono   = res["is_monotonic"]
        iv     = res["iv"]
        nb     = res["n_bins"]
        nsv    = len(res["sv_table"])
        sv_str = f" | sv_bins={nsv}" if nsv > 0 else ""
        cat_str = " | CATE" if res.get("is_categorical") else ""
        logger.info(f"  ✓ {feat:40s} | n_bins={nb}{sv_str}{cat_str} | IV={iv:.4f} | mono={mono}")

    if n_jobs == 1:
        for feat in all_fit_feats:
            _, res, err = _fit_one(feat)
            if err is not None:
                logger.info(f"  ✗ {feat}: 拟合失败 — {err[0]}")
                print(err[1])
            else:
                self._results[feat] = res
                _log_feat(feat, res)
    else:
        # ── 多进程并行(ProcessPoolExecutor)──────────────────────────
        # 策略:将特征列表均分为 N 块,每块整体发往一个进程,
        # df 每块只序列化一次(而非每特征一次),大幅降低 IPC 开销。
        max_workers = n_jobs if n_jobs > 0 else None
        n_workers   = max_workers or os.cpu_count() or 1
        chunk_size  = max(1, math.ceil(len(all_fit_feats) / n_workers))
        chunks      = [
            all_fit_feats[i : i + chunk_size]
            for i in range(0, len(all_fit_feats), chunk_size)
        ]
        # 轻量副本:只含配置,不含已有拟合结果,减少序列化体积
        binner_lite = copy.copy(self)
        binner_lite._results   = {}
        binner_lite._is_fitted = False

        feat_ok, feat_err = {}, {}
        with ProcessPoolExecutor(max_workers=max_workers) as executor:
            futures = [
                executor.submit(
                    _chunk_fit_worker,
                    (binner_lite, df, chunk, chi2_binning, chi2_p, chi2_init_size),
                )
                for chunk in chunks
            ]
            for fut in as_completed(futures):
                ok, err = fut.result()
                feat_ok.update(ok)
                feat_err.update(err)
        # 按原始顺序写回并打印日志
        for feat in all_fit_feats:
            if feat in feat_ok:
                self._results[feat] = feat_ok[feat]
                _log_feat(feat, feat_ok[feat])
            elif feat in feat_err:
                exc, tb = feat_err[feat]
                logger.info(f"  ✗ {feat}: 拟合失败 — {exc}")
                print(tb)

    self._is_fitted = True
    n_mono = sum(1 for v in self._results.values() if v["is_monotonic"])
    method = "greedy+chi2" if chi2_binning else "greedy"
    logger.info(f"[MonotoneWOEBinner] 拟合完成 ({method}): "
          f"{n_mono}/{len(self._results)} 个特征单调")
    return self

refine_chi2

refine_chi2(df: DataFrame, features: Optional[List[str]] = None, chi2_p: float = 0.99, chi2_init_size: int = 1000, n_jobs: int = 1) -> 'MonotoneWOEBinner'

在已有贪心分箱结果的基础上,追加卡方后合并(不重跑贪心分箱)。

与 fit(chi2_binning=True) 的区别
  • 跳过贪心分箱阶段,直接以 self._results 中已有的 edges 为起点
  • 可在同一份 fit 结果上反复以不同 chi2_p 调参,无需重跑贪心,速度更快
  • 支持只对指定特征子集执行卡方合并
  • 特殊值箱 WOE 不受影响,沿用 fit() 时的计算结果

参数:

名称 类型 描述 默认
df DataFrame
必需
features Optional[List[str]]
None
chi2_p float
0.99
chi2_init_size 卡方计算时 stratified 采样上限,默认 1000
1000
n_jobs int
         的线程;设为 -1 时使用所有可用 CPU 核心。
1

返回:

类型 描述
self(支持链式调用)

示例:

>>> binner = MonotoneWOEBinner(feature_cols=["score"], target_col="is_bad")
>>> binner.fit(train_df)                                    # 贪心分箱
>>> binner.refine_chi2(train_df, chi2_p=0.95, n_jobs=8)    # 并行卡方合并
>>> # 或只对部分特征做卡方合并
>>> binner.refine_chi2(train_df, features=["score", "income"], chi2_p=0.90)
源代码位于: Modeling_Tool/WOE/WOE_Monotone_Binner.py
def refine_chi2(
    self,
    df: pd.DataFrame,
    features: Optional[List[str]] = None,
    chi2_p: float = 0.99,
    chi2_init_size: int = 1000,
    n_jobs: int = 1,
) -> "MonotoneWOEBinner":
    """
    在已有贪心分箱结果的基础上,追加卡方后合并(不重跑贪心分箱)。

    与 fit(chi2_binning=True) 的区别
    ---------------------------------
    - 跳过贪心分箱阶段,直接以 self._results 中已有的 edges 为起点
    - 可在同一份 fit 结果上反复以不同 chi2_p 调参,无需重跑贪心,速度更快
    - 支持只对指定特征子集执行卡方合并
    - 特殊值箱 WOE 不受影响,沿用 fit() 时的计算结果

    Parameters
    ----------
    df             : 原始训练数据(与 fit() 时相同),用于计算卡方统计量
    features       : 需要做卡方合并的特征列表;默认 None 表示所有已拟合特征
    chi2_p         : 卡方检验置信度,默认 0.99;较小值(如 0.90)更容易合并箱
    chi2_init_size : 卡方计算时 stratified 采样上限,默认 1000
    n_jobs         : 并行线程数,默认 1(顺序执行)。设为 > 1 时使用指定数量
                     的线程;设为 -1 时使用所有可用 CPU 核心。

    Returns
    -------
    self(支持链式调用)

    Examples
    --------
    >>> binner = MonotoneWOEBinner(feature_cols=["score"], target_col="is_bad")
    >>> binner.fit(train_df)                                    # 贪心分箱
    >>> binner.refine_chi2(train_df, chi2_p=0.95, n_jobs=8)    # 并行卡方合并
    >>> # 或只对部分特征做卡方合并
    >>> binner.refine_chi2(train_df, features=["score", "income"], chi2_p=0.90)
    """
    self._check_fitted()
    try:
        from scipy.stats import chi2 as _chi2_check  # noqa
    except ImportError:
        raise ImportError(
            "refine_chi2() 需要 scipy,请先安装: pip install scipy"
        )
    if n_jobs == 0:
        raise ValueError("n_jobs 不能为 0;请使用正整数或 -1(全部核心)")

    target_feats = features if features is not None else list(self._results.keys())
    # 类别特征不适用卡方后合并,自动剔除
    _cate_in = [f for f in target_feats if self._results.get(f, {}).get("is_categorical")]
    if _cate_in:
        logger.info(f"[refine_chi2] 跳过 {len(_cate_in)} 个类别特征(不适用卡方合并)")
    target_feats = [f for f in target_feats
                    if not self._results.get(f, {}).get("is_categorical")]
    missing_feats = [f for f in target_feats if f not in self._results]
    if missing_feats:
        raise ValueError(f"以下特征尚未拟合,无法做 chi2 合并: {missing_feats}")
    if self.target_col not in df.columns:
        raise ValueError(f"目标列 '{self.target_col}' 不在 DataFrame 中")

    logger.info(
        f"[refine_chi2] 对 {len(target_feats)} 个特征做卡方后合并 "
        f"(chi2_p={chi2_p}, sample={chi2_init_size}, n_jobs={n_jobs}) ..."
    )

    # 每个特征的计算完全独立,可安全并行
    def _refine_one(feat):
        vr    = self._results[feat]
        edges = list(vr["edges"])
        if len(edges) < 1:
            return feat, None, None   # 标记为"跳过"
        try:
            df_normal, _ = self._split_special(df, feat)
            new_edges = self._chi2_merge_one(
                df_normal, feat, edges, chi2_p, chi2_init_size
            )
            wt, iv = self._compute_woe_table(df_normal, feat, new_edges)
            woes   = wt.sort_values("bin")["woe"].values
            sv_table = vr.get("sv_table", pd.DataFrame())
            sv_iv    = float(sv_table["iv"].sum()) if len(sv_table) > 0 else 0.0
            update = dict(
                edges        = new_edges,
                woe_table    = wt,
                iv           = round(iv + sv_iv, 6),
                is_monotonic = self._is_monotone(woes),
                n_bins       = len(wt),
            )
            return feat, (vr["n_bins"], update), None
        except Exception as exc:
            import traceback as _tb
            return feat, None, (exc, _tb.format_exc())

    def _apply_and_log(feat, ok, err):
        if ok is None and err is None:
            logger.info(f"  - {feat:40s} | 仅 1 箱,跳过卡方合并")
        elif err is not None:
            logger.info(f"  ✗ {feat}: chi2 合并失败 — {err[0]}")
            print(err[1])
        else:
            old_nb, update = ok
            self._results[feat].update(update)
            logger.info(
                f"  ✓ {feat:40s} | bins: {old_nb}{update['n_bins']} "
                f"| IV={update['iv']:.4f} | mono={update['is_monotonic']}"
            )

    if n_jobs == 1:
        for feat in target_feats:
            feat, ok, err = _refine_one(feat)
            _apply_and_log(feat, ok, err)
    else:
        # ── 多进程并行(ProcessPoolExecutor)──────────────────────────
        max_workers = n_jobs if n_jobs > 0 else None
        n_workers   = max_workers or os.cpu_count() or 1
        chunk_size  = max(1, math.ceil(len(target_feats) / n_workers))
        chunks      = [
            target_feats[i : i + chunk_size]
            for i in range(0, len(target_feats), chunk_size)
        ]
        binner_lite = copy.copy(self)
        binner_lite._results   = {}
        binner_lite._is_fitted = False
        # 只传各特征的 edges 和 sv_iv(轻量),不传完整 _results
        edges_map  = {f: list(self._results[f]["edges"]) for f in target_feats}
        sv_iv_map  = {
            f: float(self._results[f].get("sv_table", pd.DataFrame())["iv"].sum())
               if len(self._results[f].get("sv_table", pd.DataFrame())) > 0 else 0.0
            for f in target_feats
        }
        old_nb_map = {f: self._results[f]["n_bins"] for f in target_feats}

        feat_ok, feat_err, feat_skip = {}, {}, set()
        with ProcessPoolExecutor(max_workers=max_workers) as executor:
            futures = [
                executor.submit(
                    _chunk_chi2_worker,
                    (binner_lite, df, chunk, edges_map, sv_iv_map,
                     chi2_p, chi2_init_size),
                )
                for chunk in chunks
            ]
            for fut in as_completed(futures):
                ok, err = fut.result()
                for feat, res in ok.items():
                    if res is None:
                        feat_skip.add(feat)
                    else:
                        feat_ok[feat] = res
                feat_err.update(err)
        # 按原始顺序写回并打印日志
        for feat in target_feats:
            if feat in feat_skip:
                logger.info(f"  - {feat:40s} | 仅 1 箱,跳过卡方合并")
            elif feat in feat_err:
                exc, tb = feat_err[feat]
                logger.info(f"  ✗ {feat}: chi2 合并失败 — {exc}")
                print(tb)
            elif feat in feat_ok:
                upd = feat_ok[feat]
                self._results[feat].update(upd)
                logger.info(
                    f"  ✓ {feat:40s} | bins: {old_nb_map[feat]}{upd['n_bins']} "
                    f"| IV={upd['iv']:.4f} | mono={upd['is_monotonic']}"
                )

    self._chi2_binning   = True
    self._chi2_p         = chi2_p
    self._chi2_init_size = chi2_init_size

    n_skipped = sum(
        1 for f in target_feats if len(self._results[f]["edges"]) < 1
    )
    logger.info(
        f"[refine_chi2] 完成,{len(target_feats) - n_skipped}/{len(target_feats)} "
        f"个特征参与合并"
    )
    return self

refine_dtree

refine_dtree(df: DataFrame, features: Optional[List[str]] = None, max_bins: int = 6, min_samples_leaf: float = 0.05, monotone: bool = True, n_jobs: int = 1) -> 'MonotoneWOEBinner'

在已有贪心分箱结果的基础上,用决策树重新划定分割点。

与 refine_chi2 的区别
  • refine_chi2 : 在现有 edges 上做后合并(只减少箱数)
  • refine_dtree : 用决策树从头找最优分割点(可改变箱的位置和数量), 适合需要基于信息增益而非 IV 单调性重新划分的场景
算法
  1. 对每个特征的普通行拟合 DecisionTreeClassifier (max_leaf_nodes=max_bins, min_samples_leaf=min_samples_leaf)
  2. 提取树的内部阈值作为新 edges
  3. 若 monotone=True,贪心合并 WOE 方向反转的相邻箱,直到 WOE 单调
  4. 重新计算 woe_table / iv / n_bins,写回 self._results

参数:

名称 类型 描述 默认
df DataFrame
必需
features Optional[List[str]]
None
max_bins int
6
min_samples_leaf 决策树每个叶节点的最小样本占比(0~1)或绝对数(≥1),
           默认 0.05(5%),用于防止过细分箱
0.05
monotone bool
True
n_jobs int
1

返回:

类型 描述
self(支持链式调用)

示例:

>>> binner.fit(train_df)
>>> binner.refine_dtree(train_df, max_bins=5, min_samples_leaf=0.05)
>>> # 先贪心分箱,再决策树重新划分,再 chi2 后合并
>>> binner.fit(train_df).refine_dtree(train_df).refine_chi2(train_df, chi2_p=0.95)
源代码位于: Modeling_Tool/WOE/WOE_Monotone_Binner.py
def refine_dtree(
    self,
    df: pd.DataFrame,
    features: Optional[List[str]] = None,
    max_bins: int = 6,
    min_samples_leaf: float = 0.05,
    monotone: bool = True,
    n_jobs: int = 1,
) -> "MonotoneWOEBinner":
    """
    在已有贪心分箱结果的基础上,用决策树重新划定分割点。

    与 refine_chi2 的区别
    ---------------------
    - refine_chi2  : 在现有 edges 上做后合并(只减少箱数)
    - refine_dtree : 用决策树从头找最优分割点(可改变箱的位置和数量),
                     适合需要基于信息增益而非 IV 单调性重新划分的场景

    算法
    ----
    1. 对每个特征的普通行拟合 DecisionTreeClassifier
       (max_leaf_nodes=max_bins, min_samples_leaf=min_samples_leaf)
    2. 提取树的内部阈值作为新 edges
    3. 若 monotone=True,贪心合并 WOE 方向反转的相邻箱,直到 WOE 单调
    4. 重新计算 woe_table / iv / n_bins,写回 self._results

    Parameters
    ----------
    df               : 训练集 DataFrame(与 fit() 时相同)
    features         : 特征子集;默认 None 表示所有已拟合特征
    max_bins         : 决策树最大叶节点数(即分箱上限),默认 6
    min_samples_leaf : 决策树每个叶节点的最小样本占比(0~1)或绝对数(≥1),
                       默认 0.05(5%),用于防止过细分箱
    monotone         : 是否在决策树分箱后强制 WOE 单调,默认 True
    n_jobs           : 并行进程数,默认 1;-1 使用所有 CPU 核心

    Returns
    -------
    self(支持链式调用)

    Examples
    --------
    >>> binner.fit(train_df)
    >>> binner.refine_dtree(train_df, max_bins=5, min_samples_leaf=0.05)
    >>> # 先贪心分箱,再决策树重新划分,再 chi2 后合并
    >>> binner.fit(train_df).refine_dtree(train_df).refine_chi2(train_df, chi2_p=0.95)
    """
    self._check_fitted()
    try:
        from sklearn.tree import DecisionTreeClassifier  # noqa
    except ImportError:
        raise ImportError(
            "refine_dtree() 需要 scikit-learn,请先安装: pip install scikit-learn"
        )
    if n_jobs == 0:
        raise ValueError("n_jobs 不能为 0;请使用正整数或 -1(全部核心)")

    target_feats = features if features is not None else list(self._results.keys())
    # 类别特征不适用决策树重分箱,自动剔除(避免把类别编码当数值切分)
    _cate_in = [f for f in target_feats if self._results.get(f, {}).get("is_categorical")]
    if _cate_in:
        logger.info(f"[refine_dtree] 跳过 {len(_cate_in)} 个类别特征(不适用决策树重分箱)")
    target_feats = [f for f in target_feats
                    if not self._results.get(f, {}).get("is_categorical")]
    missing_feats = [f for f in target_feats if f not in self._results]
    if missing_feats:
        raise ValueError(f"以下特征尚未拟合,无法做 dtree 重分箱: {missing_feats}")
    if self.target_col not in df.columns:
        raise ValueError(f"目标列 '{self.target_col}' 不在 DataFrame 中")

    logger.info(
        f"[refine_dtree] 对 {len(target_feats)} 个特征做决策树重分箱 "
        f"(max_bins={max_bins}, min_samples_leaf={min_samples_leaf}, "
        f"monotone={monotone}, n_jobs={n_jobs}) ..."
    )

    eps = self.eps

    def _refine_one(feat):
        vr = self._results[feat]
        try:
            df_normal, _ = self._split_special(df, feat)
            # Step 1: 决策树找分割点
            new_edges = self._dtree_edges(
                df_normal, feat, self.target_col, max_bins, min_samples_leaf
            )
            # Step 2: 可选单调合并
            if monotone and len(new_edges) >= 1:
                new_edges = self._monotone_merge_edges(
                    df_normal, feat, self.target_col, new_edges, eps
                )
            # Step 3: 重算 WOE 表
            wt, iv = self._compute_woe_table(df_normal, feat, new_edges)
            woes   = wt.sort_values("bin")["woe"].values if len(wt) > 0 else np.array([])
            sv_table = vr.get("sv_table", pd.DataFrame())
            sv_iv    = float(sv_table["iv"].sum()) if len(sv_table) > 0 else 0.0
            update = dict(
                edges        = new_edges,
                woe_table    = wt,
                iv           = round(iv + sv_iv, 6),
                is_monotonic = self._is_monotone(woes),
                n_bins       = len(wt),
            )
            return feat, (vr["n_bins"], update), None
        except Exception as exc:
            import traceback as _tb
            return feat, None, (exc, _tb.format_exc())

    def _apply_and_log(feat, ok, err):
        if err is not None:
            logger.info(f"  ✗ {feat}: dtree 重分箱失败 — {err[0]}")
            print(err[1])
        else:
            old_nb, update = ok
            self._results[feat].update(update)
            logger.info(
                f"  ✓ {feat:40s} | bins: {old_nb}{update['n_bins']} "
                f"| IV={update['iv']:.4f} | mono={update['is_monotonic']}"
            )

    if n_jobs == 1:
        for feat in target_feats:
            feat, ok, err = _refine_one(feat)
            _apply_and_log(feat, ok, err)
    else:
        # ── 多进程并行(ProcessPoolExecutor)──────────────────────────
        # worker 必须使用模块级函数;Windows/Jupyter 的 spawn 语义无法
        # pickle refine_dtree() 内部定义的局部函数。
        max_workers = n_jobs if n_jobs > 0 else None
        n_workers   = max_workers or os.cpu_count() or 1
        chunk_size  = max(1, math.ceil(len(target_feats) / n_workers))
        chunks      = [
            target_feats[i : i + chunk_size]
            for i in range(0, len(target_feats), chunk_size)
        ]
        binner_lite = copy.copy(self)
        binner_lite._results   = {}
        binner_lite._is_fitted = False
        sv_iv_map = {
            f: float(self._results[f].get("sv_table", pd.DataFrame())["iv"].sum())
               if len(self._results[f].get("sv_table", pd.DataFrame())) > 0 else 0.0
            for f in target_feats
        }
        old_nb_map = {f: self._results[f]["n_bins"] for f in target_feats}
        feat_ok, feat_err = {}, {}
        with ProcessPoolExecutor(max_workers=max_workers) as executor:
            futures = [
                executor.submit(
                    _chunk_dtree_worker,
                    (
                        binner_lite, df, chunk, sv_iv_map, max_bins,
                        min_samples_leaf, monotone, eps,
                    ),
                )
                for chunk in chunks
            ]
            for fut in as_completed(futures):
                ok, err = fut.result()
                feat_ok.update(ok)
                feat_err.update(err)
        for feat in target_feats:
            if feat in feat_err:
                exc, tb = feat_err[feat]
                logger.info(f"  ✗ {feat}: dtree 重分箱失败 — {exc}")
                print(tb)
            elif feat in feat_ok:
                upd = feat_ok[feat]
                self._results[feat].update(upd)
                logger.info(
                    f"  ✓ {feat:40s} | bins: {old_nb_map[feat]}{upd['n_bins']} "
                    f"| IV={upd['iv']:.4f} | mono={upd['is_monotonic']}"
                )

    logger.info(f"[refine_dtree] 完成,{len(target_feats)} 个特征处理完毕")
    return self

refine_cate

refine_cate(features: Optional[List[str]] = None, max_bins: int = 5, min_bin_size: float = 0.0, badrate_tol: Optional[float] = None) -> 'MonotoneWOEBinner'

对已拟合的类别特征(cate_feats)按坏率(bad rate)做凝聚式聚类, 把坏率相近的类别合并成同一箱,降低箱数、提升稳定性。

与 refine_chi2 / refine_dtree 的关系
  • refine_chi2 / refine_dtree : 只作用于数值特征(类别特征自动跳过)
  • refine_cate : 只作用于类别特征(数值特征自动跳过)
说明
  • 仅使用 fit() 已算好的每类别计数(woe_table),无需重新传入 df,速度极快。
  • 合并按坏率排序后的相邻类别进行,因此结果各箱坏率有序、WOE 天然单调。
  • 合并只会降低或维持 IV(信息合并不会增加 IV),换取更少的箱与更好的泛化。
  • [Missing] 箱不参与聚类,沿用 fit() 的结果。
  • 可重复调用(在已聚类结果上继续合并)。

参数:

名称 类型 描述 默认
features Optional[List[str]]
       传入数值特征会被自动跳过。
None
max_bins int
5
min_bin_size 每箱最小样本占比(0~1),默认 0.0(关闭)。> 0 时,样本占比
       低于该阈值的箱会被强制并入坏率最接近的相邻箱(优先于 max_bins,
       且忽略 badrate_tol)。
0.0
badrate_tol Optional[float]
       坏率差都 > badrate_tol 时停止按 max_bins 合并,避免把坏率差异
       很大的类别为了凑箱数而强行合并。
None

返回:

类型 描述
self(支持链式调用)

示例:

>>> binner = MonotoneWOEBinner(feature_cols=["score"], target_col="is_bad",
...                            cate_feats=["city", "industry"])
>>> binner.fit(df)
>>> binner.refine_cate(max_bins=5)                       # 全部类别特征聚类
>>> binner.refine_cate(features=["city"], max_bins=4,    # 仅 city,带约束
...                    min_bin_size=0.02, badrate_tol=0.03)
源代码位于: Modeling_Tool/WOE/WOE_Monotone_Binner.py
def refine_cate(
    self,
    features: Optional[List[str]] = None,
    max_bins: int = 5,
    min_bin_size: float = 0.0,
    badrate_tol: Optional[float] = None,
) -> "MonotoneWOEBinner":
    """
    对已拟合的**类别特征(cate_feats)**按坏率(bad rate)做凝聚式聚类,
    把坏率相近的类别合并成同一箱,降低箱数、提升稳定性。

    与 refine_chi2 / refine_dtree 的关系
    ------------------------------------
    - refine_chi2 / refine_dtree : 只作用于**数值**特征(类别特征自动跳过)
    - refine_cate                : 只作用于**类别**特征(数值特征自动跳过)

    说明
    ----
    - 仅使用 fit() 已算好的每类别计数(woe_table),**无需重新传入 df**,速度极快。
    - 合并按坏率排序后的相邻类别进行,因此结果各箱坏率有序、WOE 天然单调。
    - 合并只会降低或维持 IV(信息合并不会增加 IV),换取更少的箱与更好的泛化。
    - [Missing] 箱不参与聚类,沿用 fit() 的结果。
    - 可重复调用(在已聚类结果上继续合并)。

    Parameters
    ----------
    features     : 需要聚类的类别特征列表;默认 None = 所有已拟合的类别特征。
                   传入数值特征会被自动跳过。
    max_bins     : 聚类后每个特征的最大箱数,默认 5。
    min_bin_size : 每箱最小样本占比(0~1),默认 0.0(关闭)。> 0 时,样本占比
                   低于该阈值的箱会被强制并入坏率最接近的相邻箱(优先于 max_bins,
                   且忽略 badrate_tol)。
    badrate_tol  : 坏率差阈值,默认 None(不启用)。设为正数时,当所有相邻箱的
                   坏率差都 > badrate_tol 时停止按 max_bins 合并,避免把坏率差异
                   很大的类别为了凑箱数而强行合并。

    Returns
    -------
    self(支持链式调用)

    Examples
    --------
    >>> binner = MonotoneWOEBinner(feature_cols=["score"], target_col="is_bad",
    ...                            cate_feats=["city", "industry"])
    >>> binner.fit(df)
    >>> binner.refine_cate(max_bins=5)                       # 全部类别特征聚类
    >>> binner.refine_cate(features=["city"], max_bins=4,    # 仅 city,带约束
    ...                    min_bin_size=0.02, badrate_tol=0.03)
    """
    self._check_fitted()
    if max_bins < 1:
        raise ValueError(f"max_bins 必须 ≥ 1,收到: {max_bins}")

    all_cate = [f for f in self._results if self._results[f].get("is_categorical")]
    if features is None:
        target_feats = all_cate
    else:
        _num_in = [f for f in features
                   if f in self._results and not self._results[f].get("is_categorical")]
        if _num_in:
            logger.info(f"[refine_cate] 跳过 {len(_num_in)} 个非类别特征(仅适用类别特征)")
        target_feats = [f for f in features
                        if self._results.get(f, {}).get("is_categorical")]
        missing_feats = [f for f in features if f not in self._results]
        if missing_feats:
            raise ValueError(f"以下特征尚未拟合,无法做类别聚类: {missing_feats}")

    if not target_feats:
        logger.info("[refine_cate] 无类别特征可聚类(需先 fit 含 cate_feats 的特征)")
        return self

    logger.info(
        f"[refine_cate] 对 {len(target_feats)} 个类别特征按坏率聚类 "
        f"(max_bins={max_bins}, min_bin_size={min_bin_size}, badrate_tol={badrate_tol}) ..."
    )

    for feat in target_feats:
        vr     = self._results[feat]
        old_nb = vr["n_bins"]
        try:
            update = self._cluster_cate_one(vr, max_bins, min_bin_size, badrate_tol)
        except Exception as exc:
            import traceback as _tb
            logger.info(f"  ✗ {feat}: 类别聚类失败 — {exc}")
            print(_tb.format_exc())
            continue
        if update is None:
            logger.info(f"  - {feat:40s} | {old_nb} 箱无需聚类")
            continue
        vr.update(update)
        logger.info(
            f"  ✓ {feat:40s} | bins: {old_nb}{update['n_bins']} "
            f"| IV={update['iv']:.4f} | mono={update['is_monotonic']}"
        )

    logger.info(f"[refine_cate] 完成,{len(target_feats)} 个类别特征处理完毕")
    return self

get_final_bins

get_final_bins() -> Dict[str, DataFrame]

返回每个特征的最终分箱区间 + WOE 明细(含特殊值箱)。

特殊值箱追加在普通箱之后,bin_no 继续编号,bin_label 为 '[sv=xxx]'。

返回:

名称 类型 描述
dict {feature_name -> pd.DataFrame}

DataFrame 列: bin_no | bin_label | n | bad | good | bad_rate | pct_n | lift | pct_bad | pct_good | woe | iv | cumiv is_special (bool, True=特殊值箱)

其中: pct_n = 该箱样本量 / 所有箱样本量之和(含特殊值箱) lift = 该箱 bad_rate / 全局平均 bad_rate 全局 bad_rate 取 self._bad_rate(fit 时记录); 若未 fit 则退化为所有箱 bad 之和 / n 之和

源代码位于: Modeling_Tool/WOE/WOE_Monotone_Binner.py
def get_final_bins(self) -> Dict[str, pd.DataFrame]:
    """
    返回每个特征的最终分箱区间 + WOE 明细(含特殊值箱)。

    特殊值箱追加在普通箱之后,bin_no 继续编号,bin_label 为 '[sv=xxx]'。

    Returns
    -------
    dict: {feature_name -> pd.DataFrame}
        DataFrame 列: bin_no | bin_label | n | bad | good |
                      bad_rate | pct_n | lift |
                      pct_bad | pct_good | woe | iv | cumiv
                      is_special (bool, True=特殊值箱)

        其中:
          pct_n    = 该箱样本量 / 所有箱样本量之和(含特殊值箱)
          lift     = 该箱 bad_rate / 全局平均 bad_rate
                     全局 bad_rate 取 self._bad_rate(fit 时记录);
                     若未 fit 则退化为所有箱 bad 之和 / n 之和
    """
    self._check_fitted()
    result = {}
    for feat, vr in self._results.items():
        wt     = vr["woe_table"].copy().sort_values("bin").reset_index(drop=True)
        edges  = vr["edges"]
        n_bins = vr["n_bins"]

        wt["bin_no"]    = wt["bin"] + 1
        if vr.get("is_categorical"):
            # 类别特征:箱标签即类别取值本身,已存于 woe_table,无需重建
            if "bin_label" not in wt.columns:
                wt["bin_label"] = wt["bin"].astype(str)
        else:
            wt["bin_label"] = [
                self._bin_label(edges, int(row["bin"]), n_bins,
                                self.bin_label_decimals)
                for _, row in wt.iterrows()
            ]
        wt["cumiv"]     = wt["iv"].cumsum()
        wt["is_special"] = False

        # 追加特殊值箱
        sv_table = vr.get("sv_table", pd.DataFrame())
        if len(sv_table) > 0:
            sv_rows = []
            base_bin_no = len(wt) + 1
            running_cumiv = float(wt["cumiv"].iloc[-1]) if len(wt) > 0 else 0.0
            for i, (_, svrow) in enumerate(sv_table.iterrows()):
                running_cumiv += float(svrow["iv"])
                sv_rows.append({
                    "bin_no"    : base_bin_no + i,
                    "bin_label" : svrow["bin_label"],
                    "n"         : int(svrow["n"]),
                    "bad"       : int(svrow["bad"]),
                    "good"      : int(svrow["good"]),
                    "bad_rate"  : float(svrow["bad_rate"]),
                    "pct_bad"   : float(svrow["pct_bad"]),
                    "pct_good"  : float(svrow["pct_good"]),
                    "woe"       : float(svrow["woe"]),
                    "iv"        : float(svrow["iv"]),
                    "cumiv"     : round(running_cumiv, 6),
                    "is_special": True,
                })
            sv_df = pd.DataFrame(sv_rows)
            wt = pd.concat([wt, sv_df], ignore_index=True)

        # ── 计算 pct_n 和 lift ──
        total_n = float(wt["n"].sum())
        # 全局 bad_rate:优先用 fit() 时记录的,否则从分箱数据反推
        avg_bad_rate = getattr(self, "_bad_rate", None)
        if avg_bad_rate is None or avg_bad_rate == 0:
            total_bad_all  = float(wt["bad"].sum())
            total_good_all = float(wt["good"].sum()) if "good" in wt.columns else 0.0
            avg_bad_rate   = total_bad_all / (total_bad_all + total_good_all) if (total_bad_all + total_good_all) > 0 else self.eps

        wt["pct_n"] = wt["n"] / total_n if total_n > 0 else 0.0
        wt["lift"]  = wt["bad_rate"].apply(
            lambda br: round(br / avg_bad_rate, 4) if avg_bad_rate > 0 else 0.0
        )

        # ── 补全可能缺失或 NaN 的列(格式 B 加载时 woe_table 无这些列,
        #    pd.concat 后普通箱行为 NaN)──
        _eps = self.eps
        if "good" not in wt.columns or wt["good"].isna().any():
            wt["good"] = wt["good"].fillna(0)
        if "bad_rate" not in wt.columns or wt["bad_rate"].isna().any():
            g = wt["good"].fillna(0) if "good" in wt.columns else 0
            wt["bad_rate"] = wt["bad"] / (wt["bad"] + g + _eps)
        # pct_bad / pct_good:只对普通箱(non-special)重算;sv 行保持 0.0
        _need_pct = (
            "pct_bad"  not in wt.columns or wt["pct_bad"].isna().any() or
            "pct_good" not in wt.columns or wt["pct_good"].isna().any()
        )
        if _need_pct:
            _normal_mask = ~wt["is_special"].astype(bool) if "is_special" in wt.columns                                else pd.Series(True, index=wt.index)
            _total_bad   = float(wt.loc[_normal_mask, "bad"].sum())
            _total_good  = float(wt.loc[_normal_mask, "good"].sum())
            if "pct_bad" not in wt.columns:
                wt["pct_bad"]  = 0.0
            if "pct_good" not in wt.columns:
                wt["pct_good"] = 0.0
            wt.loc[_normal_mask, "pct_bad"]  = (
                wt.loc[_normal_mask, "bad"]  / (_total_bad  + _eps)
            )
            wt.loc[_normal_mask, "pct_good"] = (
                wt.loc[_normal_mask, "good"] / (_total_good + _eps)
            )

        cols = ["bin_no", "bin_label", "n", "bad", "good",
                "bad_rate", "pct_n", "lift",
                "pct_bad", "pct_good", "woe", "iv", "cumiv", "is_special"]
        result[feat] = wt[[c for c in cols if c in wt.columns]]
    return result

get_bin_edges

get_bin_edges() -> Dict[str, List[float]]

返回每个特征的完整分箱边界列表(含 ±inf 端点),可直接用于 pd.cutget_gains_table 等下游函数。

返回的边界列表与 get_final_bins() 中的普通箱 bin_label 一一对应:若边界为 [-inf, 1.5, 3.0, inf],则对应的三个 普通箱分别为 (-∞, 1.5](1.5, 3.0](3.0, +∞)

注意:特殊值箱(如 [sv=-1][Missing])不包含在 边界列表中 — 它们独立于普通分箱,由 MonotoneWOEBinnerapply_woe() 时自动处理。类别特征(cate_feats)同样 不包含在内(无数值边界),其 WOE 映射由 apply_woe() 直接按取值查表。

返回:

名称 类型 描述
dict ``{feature_name: [-inf, cut1, cut2, ..., inf]}``

每个特征的完整分箱边界列表,首尾固定为 -np.infnp.inf

Example

binner = MonotoneWOEBinner(feature_cols=["score"], target_col="is_bad") binner.fit(df) binner.get_bin_edges()

可直接用于下游分箱

edges = binner.get_bin_edges()["score"] df["score_bin"] = pd.cut(df["score"], bins=edges, labels=False)

源代码位于: Modeling_Tool/WOE/WOE_Monotone_Binner.py
def get_bin_edges(self) -> Dict[str, List[float]]:
    """
    返回每个特征的完整分箱边界列表(含 ±inf 端点),可直接用于
    ``pd.cut``、``get_gains_table`` 等下游函数。

    返回的边界列表与 ``get_final_bins()`` 中的普通箱 bin_label
    一一对应:若边界为 ``[-inf, 1.5, 3.0, inf]``,则对应的三个
    普通箱分别为 ``(-∞, 1.5]``、``(1.5, 3.0]``、``(3.0, +∞)``。

    **注意**:特殊值箱(如 ``[sv=-1]``、``[Missing]``)不包含在
    边界列表中 — 它们独立于普通分箱,由 ``MonotoneWOEBinner``
    在 ``apply_woe()`` 时自动处理。类别特征(``cate_feats``)同样
    不包含在内(无数值边界),其 WOE 映射由 ``apply_woe()`` 直接按取值查表。

    Returns
    -------
    dict: ``{feature_name: [-inf, cut1, cut2, ..., inf]}``
        每个特征的完整分箱边界列表,首尾固定为 ``-np.inf``
        和 ``np.inf``。

    Example
    -------
    >>> binner = MonotoneWOEBinner(feature_cols=["score"], target_col="is_bad")
    >>> binner.fit(df)
    >>> binner.get_bin_edges()
    {'score': [-inf, 450.0, 520.0, 600.0, 680.0, inf]}

    >>> # 可直接用于下游分箱
    >>> edges = binner.get_bin_edges()["score"]
    >>> df["score_bin"] = pd.cut(df["score"], bins=edges, labels=False)
    """
    self._check_fitted()
    result = {}
    for feat, vr in self._results.items():
        if vr.get("is_categorical"):
            # 类别特征无数值边界,不适用 pd.cut,跳过
            continue
        edges = [float(e) for e in vr["edges"]]
        result[feat] = [-np.inf] + edges + [np.inf]
    return result

load_woe_bins

load_woe_bins(bins_dict: dict) -> 'MonotoneWOEBinner'

直接加载已有的分箱结果,跳过 fit()。支持两种输入格式:

格式 A — get_final_bins() 的输出: {feature_name -> DataFrame} DataFrame 必须包含列: bin_label | n | bad | woe | iv (可含 is_special 列;无则假设全为普通箱) 类别特征自动识别:若普通箱 bin_label 不是数值区间格式(如 "(-∞, 1.5]"), 则按类别特征加载,apply_woe 时按取值直接查表。

格式 B — 训练流水线 woe_results 格式: {feature_name -> dict},dict 包含: edges : list,含 ±inf 端点,如 [-inf, 1.5, 3.0, inf] woe_map : {bin_index -> woe_value} missing_woe : float bin_df : DataFrame,含列 b | n | nb | br | woe | pct total_iv : float(可选;若无则从 bin_df 推算) n_bins : int(可选)

两种格式可在同一个 bins_dict 中混合使用。

返回:

类型 描述
self(支持链式调用)
源代码位于: Modeling_Tool/WOE/WOE_Monotone_Binner.py
def load_woe_bins(self, bins_dict: dict) -> "MonotoneWOEBinner":
    """
    直接加载已有的分箱结果,跳过 fit()。支持两种输入格式:

    格式 A — get_final_bins() 的输出:
        {feature_name -> DataFrame}
        DataFrame 必须包含列: bin_label | n | bad | woe | iv
        (可含 is_special 列;无则假设全为普通箱)
        类别特征自动识别:若普通箱 bin_label 不是数值区间格式(如 "(-∞, 1.5]"),
        则按类别特征加载,apply_woe 时按取值直接查表。

    格式 B — 训练流水线 woe_results 格式:
        {feature_name -> dict},dict 包含:
          edges        : list,含 ±inf 端点,如 [-inf, 1.5, 3.0, inf]
          woe_map      : {bin_index -> woe_value}
          missing_woe  : float
          bin_df       : DataFrame,含列 b | n | nb | br | woe | pct
          total_iv     : float(可选;若无则从 bin_df 推算)
          n_bins       : int(可选)

    两种格式可在同一个 bins_dict 中混合使用。

    Returns
    -------
    self (支持链式调用)
    """
    self._results = {}

    for feat, payload in bins_dict.items():

        # ── 判断格式 ──────────────────────────────────────────────
        if isinstance(payload, pd.DataFrame):
            # 格式 A(直接是 DataFrame)
            fmt = "A"
            df_bin = payload
        elif isinstance(payload, dict) and "woe_map" in payload:
            # 格式 B(dict with edges / woe_map / bin_df)
            fmt = "B"
        elif isinstance(payload, dict):
            # 格式 A 包在 dict 里(不常见,兼容)
            fmt = "A"
            df_bin = payload.get("bin_df") or payload.get("df")
            if df_bin is None:
                raise ValueError(
                    f"特征 '{feat}': dict 格式既无 'woe_map' 也无 'bin_df',无法识别格式"
                )
        else:
            raise ValueError(
                f"特征 '{feat}': 不支持的类型 {type(payload)},"
                "期望 DataFrame 或含 woe_map 的 dict"
            )

        # 类别特征标记(格式 A 自动识别;格式 B 暂不支持类别特征)
        is_categorical = False

        # ════════════════════════════════════════════════════════
        # 格式 A 处理路径
        # ════════════════════════════════════════════════════════
        if fmt == "A":
            required_cols = {"bin_label", "n", "bad", "woe", "iv"}
            missing = required_cols - set(df_bin.columns)
            if missing:
                raise ValueError(f"特征 '{feat}' 的分箱表缺少列: {missing}")

            df_bin = df_bin.copy().reset_index(drop=True)

            if "is_special" in df_bin.columns:
                sv_mask   = df_bin["is_special"].astype(bool)
                df_normal = df_bin[~sv_mask].copy()
                df_sv     = df_bin[sv_mask].copy()
            else:
                df_normal = df_bin.copy()
                df_sv     = pd.DataFrame()

            # 自动识别类别特征:普通箱标签不全是数值区间格式 → 类别特征
            _norm_labels = df_normal["bin_label"].astype(str).tolist()
            is_categorical = (
                len(_norm_labels) > 0
                and not all(self._looks_like_interval(l) for l in _norm_labels)
            )

            woe_table = df_normal.copy()
            woe_table["bin"] = range(len(df_normal))
            if is_categorical:
                edges = []   # 类别特征无数值边界
                # 还原成员类别:支持 refine_cate 合并后的 "A | B | C" 标签
                # 每个成员 int → float → 原字符串,供 apply_woe 精确匹配
                _members = [
                    [self._infer_cat_value(p) for p in lbl.split(_CATE_GROUP_SEP)]
                    for lbl in _norm_labels
                ]
                woe_table["cat_members"] = _members
                woe_table["cat_value"]   = [
                    ms[0] if len(ms) == 1 else np.nan for ms in _members
                ]
            else:
                edges = self._reconstruct_edges(_norm_labels)
            sv_table  = df_sv.copy() if len(df_sv) > 0 else pd.DataFrame()
            total_iv  = float(df_bin["iv"].sum())
            n_bins    = len(df_normal)
            woes      = df_normal["woe"].values if len(df_normal) > 0 else np.array([])
            missing_woe = 0.0   # 格式 A 无此字段,用中性 WOE

        # ════════════════════════════════════════════════════════
        # 格式 B 处理路径
        # ════════════════════════════════════════════════════════
        else:  # fmt == "B"
            raw_edges   = list(payload["edges"])   # 含首尾 ±inf
            woe_map     = payload["woe_map"]       # {int -> float}
            missing_woe = float(payload.get("missing_woe", 0.0))
            bin_df      = payload.get("bin_df", pd.DataFrame())
            total_iv    = float(payload.get("total_iv", 0.0))

            # edges:去掉首尾 ±inf,只保留内部切割点
            import math as _math
            edges = [
                float(e) for e in raw_edges
                if not (_math.isinf(float(e)) or _math.isnan(float(e)))
            ]

            n_bins = len(woe_map)

            # 构建 woe_table(与格式 A 的 woe_table 列对齐)
            if len(bin_df) > 0:
                bdf = bin_df.copy().reset_index(drop=True)
                # 列名映射:bin_df 用 b/nb/br/pct,woe_table 用 bin/bad/bad_rate/pct_n
                rename_map = {}
                if "b"  in bdf.columns and "bin" not in bdf.columns:
                    rename_map["b"]   = "bin"
                if "nb" in bdf.columns and "bad" not in bdf.columns:
                    rename_map["nb"]  = "bad"
                if "br" in bdf.columns and "bad_rate" not in bdf.columns:
                    rename_map["br"]  = "bad_rate"
                if "pct" in bdf.columns and "pct_n" not in bdf.columns:
                    rename_map["pct"] = "pct_n"
                bdf = bdf.rename(columns=rename_map)

                # 确保有 woe 列(用 woe_map 覆盖,保证精度一致)
                bdf["woe"] = bdf["bin"].map({int(k): float(v)
                                             for k, v in woe_map.items()})

                # 补充 good 列(若缺)
                if "good" not in bdf.columns:
                    bdf["good"] = 0

                # 补充 iv 列(若缺)
                if "iv" not in bdf.columns:
                    total_bad  = bdf["bad"].sum()
                    total_good = bdf["good"].sum() if "good" in bdf.columns else 0
                    eps = self.eps
                    def _iv_row(r):
                        pb = r["bad"]  / (total_bad  + eps)
                        pg = r["good"] / (total_good + eps) if total_good > 0 else eps
                        return (pb - pg) * r["woe"]
                    bdf["iv"] = bdf.apply(_iv_row, axis=1)
                    if total_iv == 0.0:
                        total_iv = float(bdf["iv"].sum())

                # 确保有 bin_label 列(从 edges 生成)
                if "bin_label" not in bdf.columns:
                    labels = self._make_bin_labels(edges, n_bins, self.bin_label_decimals)
                    bdf["bin_label"] = labels[: len(bdf)]

                woe_table = bdf.copy()
            else:
                # bin_df 缺失,从 woe_map + edges 最小化构建
                labels = self._make_bin_labels(edges, n_bins)
                woe_table = pd.DataFrame({
                    "bin":       list(range(n_bins)),
                    "bin_label": labels,
                    "woe":       [float(woe_map[k]) for k in sorted(woe_map)],
                    "n":         [0] * n_bins,
                    "bad":       [0] * n_bins,
                    "good":      [0] * n_bins,
                    "bad_rate":  [0.0] * n_bins,
                    "pct_n":     [0.0] * n_bins,
                    "iv":        [0.0] * n_bins,
                })

            woes = np.array([float(woe_map[k]) for k in sorted(woe_map)])

            # ── 根据 self.special_values 自动构建 sv_table ──
            # 格式 B 没有 sv 的统计数据,但有 missing_woe;
            # 用 missing_woe 作为 WOE,n/bad/good 等统计量置为 0(占位)。
            sv_rows = []
            for sv_val in (self.special_values or []):
                import math as _math2
                is_nan_sv = (sv_val is None or
                             (isinstance(sv_val, float) and _math2.isnan(sv_val)))
                lbl = "[Missing]" if is_nan_sv else f"[sv={sv_val}]"
                sv_rows.append({
                    "bin_label": lbl,
                    "sv":        "__nan__" if is_nan_sv else sv_val,
                    "n":         0,
                    "bad":       0,
                    "good":      0,
                    "bad_rate":  0.0,
                    "pct_bad":   0.0,
                    "pct_good":  0.0,
                    "woe":       missing_woe,
                    "iv":        0.0,
                })
            sv_table = pd.DataFrame(sv_rows) if sv_rows else pd.DataFrame()

        # ── 写入 _results ─────────────────────────────────────────
        res = dict(
            edges        = edges,
            woe_table    = woe_table,
            sv_table     = sv_table,
            iv           = round(total_iv, 6),
            missing_woe  = missing_woe,
            is_monotonic = self._is_monotone(woes) if len(woes) > 1 else True,
            n_bins       = n_bins,
        )
        if is_categorical:
            res["is_categorical"] = True
            res["categories"] = (
                [m for ms in woe_table["cat_members"] for m in ms]
                if "cat_members" in woe_table.columns else []
            )
        self._results[feat] = res

    # 同步 feature_cols
    existing = set(self.feature_cols)
    for feat in bins_dict:
        if feat not in existing:
            self.feature_cols.append(feat)

    self._is_fitted = True
    logger.info(f"[load_woe_bins] 加载完成: {len(self._results)} 个特征")
    return self

apply_woe

apply_woe(data: DataFrame, suffix: str = '_woe', inplace: bool = False) -> DataFrame

将 data 中的特征原始数值转换为 WOE 值,添加 *_woe 列。

特殊值处理: - 若某值在 special_values 中,直接查 sv_table 获取对应 WOE - NaN:若 nan 在 special_values 中则查 sv_table;否则填 missing_woe - 普通值:按 edges 做 pd.cut,然后查 woe_table

类别特征(cate_feats)处理: - 按取值直接查表取 WOE(不做区间切分) - NaN → [Missing] 箱 WOE(若 fit 时存在缺失),否则 missing_woe - 训练时未出现过的新类别 → missing_woe(中性)

参数:

名称 类型 描述 默认
data DataFrame
必需
suffix str
'_woe'
inplace 是否在原 DataFrame 上操作(False = 返回副本)
False

返回:

类型 描述
DataFrame,新增 {feat}{suffix} 列
源代码位于: Modeling_Tool/WOE/WOE_Monotone_Binner.py
def apply_woe(
    self,
    data: pd.DataFrame,
    suffix: str = "_woe",
    inplace: bool = False,
) -> pd.DataFrame:
    """
    将 data 中的特征原始数值转换为 WOE 值,添加 *_woe 列。

    特殊值处理:
      - 若某值在 special_values 中,直接查 sv_table 获取对应 WOE
      - NaN:若 nan 在 special_values 中则查 sv_table;否则填 missing_woe
      - 普通值:按 edges 做 pd.cut,然后查 woe_table

    类别特征(cate_feats)处理:
      - 按取值直接查表取 WOE(不做区间切分)
      - NaN → [Missing] 箱 WOE(若 fit 时存在缺失),否则 missing_woe
      - 训练时未出现过的新类别 → missing_woe(中性)

    Parameters
    ----------
    data    : 含原始特征列的 DataFrame
    suffix  : WOE 列后缀,默认 "_woe"
    inplace : 是否在原 DataFrame 上操作(False = 返回副本)

    Returns
    -------
    DataFrame,新增 {feat}{suffix} 列
    """
    self._check_fitted()
    df = data if inplace else data.copy()
    woe_outputs: Dict[str, np.ndarray] = {}

    for feat, vr in self._results.items():
        if feat not in df.columns:
            logger.info(f"  [WARN] '{feat}' 不在 data 中,跳过")
            continue

        sv_table    = vr.get("sv_table", pd.DataFrame())
        woe_col     = feat + suffix
        # 优先使用 _results 中存储的 per-feature missing_woe(格式 B 加载时设置)
        feat_missing_woe = float(vr.get("missing_woe", self.missing_woe))

        series = df[feat]

        # 构建特殊值 → WOE 映射(数值/类别特征通用,主要用于 NaN/[Missing])
        sv_woe_map: Dict = {}
        if len(sv_table) > 0 and "bin_label" in sv_table.columns:
            for _, svrow in sv_table.iterrows():
                lbl = svrow["bin_label"]
                sv_woe_val = float(svrow["woe"])
                # 解析 bin_label 还原特殊值
                if lbl == "[Missing]":
                    sv_woe_map["__nan__"] = sv_woe_val
                else:
                    import re
                    m = re.match(r"\[sv=(.*)\]$", lbl)
                    if m:
                        raw = m.group(1)
                        try:
                            sv_woe_map[float(raw)] = sv_woe_val
                            sv_woe_map[int(float(raw))] = sv_woe_val
                        except (ValueError, OverflowError):
                            sv_woe_map[raw] = sv_woe_val

        # ── 类别特征:按取值直接查 WOE,不做区间切分 ──
        if vr.get("is_categorical"):
            wt = vr["woe_table"]
            # 原始取值 → WOE(fit 路径,精确匹配;int/float 由 dict 等价性兼容)
            # refine_cate 聚类后,一个箱含多个类别(cat_members);逐成员展开建表
            cat_woe_map: Dict = {}
            cat_woe_map_str: Dict = {}
            for _, r in wt.iterrows():
                woe_v = float(r["woe"])
                if "cat_members" in wt.columns and isinstance(r["cat_members"], (list, tuple)):
                    members = r["cat_members"]
                elif "cat_value" in wt.columns and not pd.isna(r["cat_value"]):
                    members = [r["cat_value"]]
                else:
                    members = []
                for cv in members:
                    if pd.isna(cv):
                        continue
                    cat_woe_map[cv]            = woe_v   # 精确匹配
                    cat_woe_map_str[str(cv)]   = woe_v   # 类型不一致时回退匹配
                # 整箱标签也登记一次(兜底;通常不会命中真实类别)
                if "bin_label" in wt.columns:
                    cat_woe_map_str.setdefault(str(r["bin_label"]), woe_v)
            nan_woe = float(sv_woe_map.get("__nan__", feat_missing_woe))
            missing_mask = series.isna()
            if cat_woe_map:
                mapped = series.map(cat_woe_map)
            else:
                mapped = pd.Series(np.nan, index=series.index, dtype=float)

            fallback_mask = mapped.isna() & ~missing_mask
            if cat_woe_map_str and fallback_mask.any():
                mapped.loc[fallback_mask] = (
                    series.loc[fallback_mask].astype(str).map(cat_woe_map_str)
                )

            out = np.full(len(series), feat_missing_woe, dtype=float)
            missing_arr = missing_mask.to_numpy()
            if missing_arr.any():
                out[missing_arr] = nan_woe
            hit_arr = mapped.notna().to_numpy() & ~missing_arr
            if hit_arr.any():
                out[hit_arr] = mapped.to_numpy(dtype=float)[hit_arr]

            woe_outputs[woe_col] = out.astype(float, copy=False)
            continue


        # ── 数值特征:按 edges 做 bin 查找 ──
        edges  = [float(e) for e in vr["edges"]]
        wt_map = vr["woe_table"].set_index("bin")["woe"].to_dict()

        out = np.full(len(series), feat_missing_woe, dtype=float)

        is_missing = series.isna().to_numpy()
        if is_missing.any():
            out[is_missing] = float(sv_woe_map.get("__nan__", feat_missing_woe))

        special_mask = np.zeros(len(series), dtype=bool)
        for sv_val, sv_woe in sv_woe_map.items():
            if sv_val == "__nan__":
                continue
            try:
                mask = series.eq(sv_val).to_numpy(dtype=bool, na_value=False)
            except TypeError:
                mask = series.astype(object).eq(sv_val).to_numpy(dtype=bool, na_value=False)
            if mask.any():
                out[mask] = float(sv_woe)
                special_mask |= mask

        normal_mask = ~(is_missing | special_mask)
        if normal_mask.any():
            if not edges:
                out[normal_mask] = float(wt_map.get(0, feat_missing_woe))
            else:
                try:
                    values_arr = series.to_numpy(dtype=float, copy=False, na_value=np.nan)
                except (TypeError, ValueError):
                    values_arr = pd.to_numeric(series, errors="coerce").to_numpy(dtype=float)
                normal_values = values_arr[normal_mask]
                valid_values = ~np.isnan(normal_values)
                if valid_values.any():
                    normal_pos = np.flatnonzero(normal_mask)
                    valid_pos = normal_pos[valid_values]
                    bin_idx = np.searchsorted(
                        np.asarray(edges, dtype=float),
                        normal_values[valid_values],
                        side="right",
                    )
                    woe_values = np.full(len(edges) + 1, feat_missing_woe, dtype=float)
                    for bin_key, woe_val in wt_map.items():
                        try:
                            bin_i = int(bin_key)
                        except (TypeError, ValueError):
                            continue
                        if 0 <= bin_i < len(woe_values):
                            woe_values[bin_i] = float(woe_val)
                    out[valid_pos] = woe_values[bin_idx]

        woe_outputs[woe_col] = out.astype(float, copy=False)
        continue

    if not woe_outputs:
        return df
    woe_df = pd.DataFrame(woe_outputs, index=df.index)
    if inplace:
        df.loc[:, list(woe_df.columns)] = woe_df
        return df
    existing = [col for col in woe_df.columns if col in df.columns]
    if existing:
        df = df.drop(columns=existing)
    return pd.concat([df, woe_df], axis=1)

export_woe_report

export_woe_report(report_path: str) -> None

将所有特征的分箱结果输出为 Excel 报告(使用 SuperModelingFactory 的 ExcelMaster 工具包写入)。

Sheet 列表

Sheet 1 「WOE分箱明细」: 汇总表 + 逐特征明细(含特殊值箱,紫色标注) Sheet 2 「WOE分箱图」 : 每个特征嵌入整体 WOE 图

参数:

名称 类型 描述 默认
report_path 输出路径,如 "woe_report.xlsx"
必需
源代码位于: Modeling_Tool/WOE/WOE_Monotone_Binner.py
def export_woe_report(self, report_path: str) -> None:
    """
    将所有特征的分箱结果输出为 Excel 报告(使用 SuperModelingFactory
    的 ExcelMaster 工具包写入)。

    Sheet 列表
    ----------
    Sheet 1 「WOE分箱明细」: 汇总表 + 逐特征明细(含特殊值箱,紫色标注)
    Sheet 2 「WOE分箱图」  : 每个特征嵌入整体 WOE 图

    Parameters
    ----------
    report_path : 输出路径,如 "woe_report.xlsx"
    """
    self._check_fitted()
    from ExcelMaster.ExcelMaster import ExcelMaster

    bins_dict = self.get_final_bins()
    os.makedirs(os.path.dirname(os.path.abspath(report_path)), exist_ok=True)

    em = ExcelMaster(report_path, verbose=False, gap_number=1)
    wb = em.workbook   # 底层 xlsxwriter workbook,用于自定义数字 / 颜色格式

    # 自定义单元格格式(set_cell_format 可直接接受 format 对象)
    _base    = {"border": 1, "align": "center", "valign": "vcenter",
                "font_name": "Calibri", "font_size": 9}
    fmt_pct  = wb.add_format({**_base, "num_format": "0.00%"})
    fmt_num4 = wb.add_format({**_base, "num_format": "0.0000"})
    fmt_num2 = wb.add_format({**_base, "num_format": "0.00"})
    # 特殊值行:仅叠加紫底紫字(与上面的数字格式叠加生效)
    fmt_sv   = wb.add_format({"bg_color": "#E8D5F5",
                              "font_color": "#5B2C6F", "bold": True})

    # ═══════════════════════════════════════════════════════════════
    # Sheet 1: WOE分箱明细
    # ═══════════════════════════════════════════════════════════════
    ws = em.add_worksheet("WOE分箱明细")

    # 顶部总标题
    em.merge_col(ws, ncols=13, text="各特征 WOE 分箱明细", cformat="BLUE_H1")

    # ── 汇总表 ──
    summary_rows = []
    for i, (feat, vr) in enumerate(self._results.items(), 1):
        wt   = vr["woe_table"]
        sv_t = vr.get("sv_table", pd.DataFrame())
        woes = wt.sort_values("bin")["woe"].values if len(wt) > 0 else np.array([])
        if vr.get("is_categorical"):
            direction = "类别"
        else:
            direction = "↑ 递增" if (len(woes) >= 2 and woes[-1] > woes[0]) else "↓ 递减"
        summary_rows.append({
            "序号": i, "特征名": feat, "普通箱数": vr["n_bins"],
            "特殊值箱数": len(sv_t) if len(sv_t) > 0 else 0,
            "总IV值": round(float(vr["iv"]), 4),
            "WOE方向": direction,
            "是否单调": "✓" if vr["is_monotonic"] else "✗",
        })
    summary_df = pd.DataFrame(summary_rows)
    em.write_dataframe(ws, summary_df, title="▌ 汇总:各特征 IV 一览",
                       index=False, header=True)

    # ── 逐特征明细 ──
    col_rename = {
        "bin_no": "分箱编号", "bin_label": "分箱区间", "n": "样本量",
        "bad": "坏样本数", "good": "好样本数", "bad_rate": "箱内坏样本率",
        "pct_n": "样本占比", "lift": "Lift", "pct_bad": "坏件分布占比",
        "pct_good": "好件分布占比", "woe": "WOE值", "iv": "IV贡献", "cumiv": "累计IV",
    }
    order   = list(col_rename.keys())
    pct_cn  = {"箱内坏样本率", "样本占比", "坏件分布占比", "好件分布占比"}
    num4_cn = {"WOE值", "IV贡献", "累计IV"}
    num2_cn = {"Lift"}

    for seq, (feat, wt_df) in enumerate(bins_dict.items(), 1):
        vr   = self._results[feat]
        cols = [c for c in order if c in wt_df.columns]
        ddf  = wt_df[cols].rename(columns=col_rename)

        sv_mask = (wt_df["is_special"].astype(bool).tolist()
                   if "is_special" in wt_df.columns else [False] * len(wt_df))
        n_normal = vr["n_bins"]
        sv_hint  = f"   |   特殊值箱={sum(sv_mask)}" if any(sv_mask) else ""
        title = (f"  [{seq:02d}] {feat}   |   IV={vr['iv']:.4f}   "
                 f"|   普通箱={vr['n_bins']}{sv_hint}   "
                 f"|   单调={'✓' if vr['is_monotonic'] else '✗'}")

        loc = em.write_dataframe(ws, ddf, title=title, index=False,
                                 header=True, titleformat="BLUE_H4",
                                 retCellRange="value")
        r0, c0, r1, c1 = loc
        data_r0 = r0 + 2          # 跳过 title(1) + header(1)
        data_r1 = r1
        colpos  = {name: c0 + idx for idx, name in enumerate(ddf.columns)}

        # 列数字格式
        for cn, fmt in ([(c, fmt_pct)  for c in pct_cn]
                        + [(c, fmt_num4) for c in num4_cn]
                        + [(c, fmt_num2) for c in num2_cn]):
            if cn in colpos:
                cc = colpos[cn]
                em.set_cell_format(ws, [data_r0, cc, data_r1, cc], fmt)

        # WOE / Lift 列色阶(仅普通箱行,避免特殊值极端值干扰色阶)
        if n_normal > 0:
            nb_r1 = data_r0 + n_normal - 1
            if "WOE值" in colpos:
                cc = colpos["WOE值"]
                em.set_color_scale(ws, [data_r0, cc, nb_r1, cc],
                                   colors=("#F4B183", "#FFFFFF", "#A9D08E"))
            if "Lift" in colpos:
                cc = colpos["Lift"]
                em.set_color_scale(ws, [data_r0, cc, nb_r1, cc],
                                   colors=("#9DC3E6", "#FFFFFF", "#F4B183"))

        # 特殊值行整行紫色(叠加在数字格式之上)
        for ri, is_sv in enumerate(sv_mask):
            if is_sv:
                rr = data_r0 + ri
                em.set_cell_format(ws, [rr, c0, rr, c1], fmt_sv)

        # 特殊值图例注释
        if any(sv_mask):
            em.merge_col(ws, ncols=13,
                         text="  ★ 紫色行为特殊值独立分箱,WOE 独立计算,不参与单调约束",
                         cformat="TEXT_ITALIC")

    # ═══════════════════════════════════════════════════════════════
    # Sheet 2: WOE分箱图(每个特征嵌入整体 WOE 图)
    # ═══════════════════════════════════════════════════════════════
    ws2 = em.add_worksheet("WOE分箱图")
    em.merge_col(ws2, ncols=11, text="各特征 WOE 分箱图(整体)", cformat="BLUE_H1")

    # 注意: xlsxwriter 的 insert_image 延迟到 close 时才读取图片文件,
    #       因此 close_workbook() 必须在 tempdir 仍存活时调用。
    with tempfile.TemporaryDirectory() as tmpdir:
        for feat_idx, (feat, wt_df) in enumerate(bins_dict.items()):
            vr        = self._results[feat]
            normal_df = (wt_df[~wt_df["is_special"].astype(bool)]
                         if "is_special" in wt_df.columns else wt_df)
            sv_df     = (wt_df[wt_df["is_special"].astype(bool)]
                         if "is_special" in wt_df.columns else pd.DataFrame())

            # 渲染整体 WOE 图并落盘(insert_image 需要文件路径)
            img_buf   = self._render_woe_chart(
                feat, normal_df, sv_df, vr, dpi=120, figsize=(9, 4.5),
            )
            safe_feat = feat.replace("/", "_").replace("\\", "_")
            img_path  = os.path.join(tmpdir, f"{safe_feat}.png")
            with open(img_path, "wb") as f:
                f.write(img_buf.getbuffer())

            # 特征标题
            em.merge_col(
                ws2, ncols=11,
                text=(f"  [{feat_idx+1:02d}] {feat}   |   IV={vr['iv']:.4f}   "
                      f"|   普通箱={vr['n_bins']}   "
                      f"|   单调={'✓' if vr['is_monotonic'] else '✗'}"
                      + (f"   |   特殊值箱={len(sv_df)}" if len(sv_df) > 0 else "")),
                cformat="BLUE_H4",
            )
            # 插入图片(缩放到合适大小)
            em.insert_image(ws2, figPath=img_path, figScale=(0.62, 0.62),
                            skipby="row")

        em.close_workbook()

    logger.info(f"[export_woe_report] 报告已保存至: {report_path}  "
                f"(ExcelMaster, 含图片Sheet)")

plot_woe_graph

plot_woe_graph(graph_path: str, group_name: Optional[str] = None, _df_for_group: Optional[DataFrame] = None, dpi: int = 150, figsize: tuple = (9, 6), bar_mode: str = 'clustered') -> None

为每个特征绘制复合图(线图 + Stack 柱图),保存到 graph_path 目录。

整体图(group_name=None): - 普通箱 stacked 柱图 + WOE 折线 + 标注框 - 若有特殊值箱,追加在右侧(虚边框 + 紫色标注) - 标题:"{feat}: IV={iv:.3f}"

分组图(group_name 不为 None):每个 group 一条 WOE 折线(仅普通箱), 柱图样式由 bar_mode 控制: - "pooled" : 单套柱,全量好坏占比(占全量样本) - "clustered" : 每个箱位置并排各组柱,柱高=占【该组】总样本(默认) - "small_multiples" : 每个 group 一个子图 panel,各画该组组内占比柱 + 该组 WOE 线(WOE y 轴跨 panel 统一,便于对比) - 标题:"{feat}: IV_range={min}−{max}"

参数:

名称 类型 描述 默认
graph_path str
必需
group_name Optional[str]
None
_df_for_group Optional[DataFrame]
None
dpi int
150
figsize tuple
         的基准尺寸,整图按子图网格自动放大
(9, 6)
bar_mode str
         默认 "clustered"。group_name=None(整体图)时此参数忽略
'clustered'
源代码位于: Modeling_Tool/WOE/WOE_Monotone_Binner.py
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
def plot_woe_graph(
    self,
    graph_path: str,
    group_name: Optional[str] = None,
    _df_for_group: Optional[pd.DataFrame] = None,
    dpi: int = 150,
    figsize: tuple = (9, 6),
    bar_mode: str = "clustered",
) -> None:
    """
    为每个特征绘制复合图(线图 + Stack 柱图),保存到 graph_path 目录。

    整体图(group_name=None):
      - 普通箱 stacked 柱图 + WOE 折线 + 标注框
      - 若有特殊值箱,追加在右侧(虚边框 + 紫色标注)
      - 标题:"{feat}:  IV={iv:.3f}"

    分组图(group_name 不为 None):每个 group 一条 WOE 折线(仅普通箱),
    柱图样式由 bar_mode 控制:
      - "pooled"          : 单套柱,全量好坏占比(占全量样本)
      - "clustered"       : 每个箱位置并排各组柱,柱高=占【该组】总样本(默认)
      - "small_multiples" : 每个 group 一个子图 panel,各画该组组内占比柱
                            + 该组 WOE 线(WOE y 轴跨 panel 统一,便于对比)
      - 标题:"{feat}:  IV_range={min}−{max}"

    Parameters
    ----------
    graph_path     : 图片保存目录(自动创建)
    group_name     : 分组列名(如 "month"),None = 画整体图
    _df_for_group  : 含原始特征+target+group_name 的 DataFrame(group 模式必填)
    dpi            : 图片分辨率,默认 150
    figsize        : 图片尺寸,默认 (9, 6)。small_multiples 模式下为单个 panel
                     的基准尺寸,整图按子图网格自动放大
    bar_mode       : 分组图柱样式,"pooled" | "clustered" | "small_multiples",
                     默认 "clustered"。group_name=None(整体图)时此参数忽略
    """
    self._check_fitted()
    _valid_bar_modes = {"pooled", "clustered", "small_multiples"}
    if bar_mode not in _valid_bar_modes:
        raise ValueError(
            f"bar_mode 必须是 {_valid_bar_modes} 之一,收到: {bar_mode!r}"
        )
    os.makedirs(graph_path, exist_ok=True)
    bins_dict = self.get_final_bins()

    GOOD_COLOR = "#5BBCD6"
    BAD_COLOR  = "#F4856A"
    WOE_COLOR_OVERALL = "#2E75B6"
    SV_GOOD    = "#A8D8A8"
    SV_BAD     = "#F7B7A3"
    SV_WOE     = "#8E44AD"

    for feat, wt_df in bins_dict.items():
        vr = self._results[feat]
        edges  = [float(e) for e in vr["edges"]]

        # 分离普通箱和特殊值箱
        if "is_special" in wt_df.columns:
            normal_df = wt_df[~wt_df["is_special"].astype(bool)].copy()
            sv_df     = wt_df[wt_df["is_special"].astype(bool)].copy()
        else:
            normal_df = wt_df.copy()
            sv_df     = pd.DataFrame()

        n_normal  = len(normal_df)
        n_sv      = len(sv_df)
        n_total   = n_normal + n_sv
        iv_overall = vr["iv"]

        x_normal = np.arange(n_normal)
        x_sv     = np.arange(n_normal, n_total)
        x_all    = np.arange(n_total)

        # ── small_multiples 独立路径:每组一个子图,自建多子图 figure ──
        if group_name is not None and bar_mode == "small_multiples":
            self._plot_feat_small_multiples(
                feat, normal_df, sv_df,
                n_normal, n_sv, n_total, x_normal, x_sv, x_all,
                group_name, _df_for_group, graph_path, dpi, figsize,
                GOOD_COLOR, BAD_COLOR, SV_GOOD, SV_BAD, SV_WOE,
            )
            continue

        fig, ax_bar = plt.subplots(figsize=figsize)
        ax_woe = ax_bar.twinx()

        pct_bad_n  = normal_df["pct_bad"].values  if n_normal > 0 else np.array([])
        pct_good_n = normal_df["pct_good"].values if n_normal > 0 else np.array([])
        pct_bad_sv  = sv_df["pct_bad"].values  if n_sv > 0 else np.array([])
        pct_good_sv = sv_df["pct_good"].values if n_sv > 0 else np.array([])

        if group_name is None:
            # ── 整体图 ──
            if n_normal > 0:
                ax_bar.bar(x_normal, pct_good_n, color=GOOD_COLOR,
                           alpha=0.85, label="0", width=0.6, zorder=2)
                ax_bar.bar(x_normal, pct_bad_n, bottom=pct_good_n,
                           color=BAD_COLOR, alpha=0.85, label="1",
                           width=0.6, zorder=2)

            if n_sv > 0:
                ax_bar.bar(x_sv, pct_good_sv, color=SV_GOOD, alpha=0.85,
                           width=0.6, zorder=2, edgecolor="#888",
                           linewidth=1.2, linestyle="--")
                ax_bar.bar(x_sv, pct_bad_sv, bottom=pct_good_sv, color=SV_BAD,
                           alpha=0.85, width=0.6, zorder=2, edgecolor="#888",
                           linewidth=1.2, linestyle="--")
                ax_bar.axvline(x=n_normal - 0.5, color="#888",
                               linewidth=1.2, linestyle=":", zorder=3)
                # 注意: 用数据坐标而非 get_xaxis_transform(),避免 bbox_inches='tight' 拉伸
                ax_bar.text(n_normal - 0.35, 0.93, "Special",
                            fontsize=8, color=SV_WOE, va="top",
                            transform=ax_bar.transData)

            # WOE 线(普通箱)
            woe_n  = normal_df["woe"].values  if n_normal > 0 else np.array([])
            br_n   = normal_df["bad_rate"].values if n_normal > 0 else np.array([])
            if n_normal > 0:
                ax_woe.plot(x_normal, woe_n, color=WOE_COLOR_OVERALL,
                            marker="o", linewidth=2, markersize=6, zorder=5)

            # WOE 线(特殊值箱)
            woe_sv = sv_df["woe"].values  if n_sv > 0 else np.array([])
            br_sv  = sv_df["bad_rate"].values if n_sv > 0 else np.array([])
            if n_sv > 0:
                ax_woe.plot(x_sv, woe_sv, color=SV_WOE, marker="D",
                            linewidth=1.5, markersize=6, linestyle="--", zorder=5)

            # 标注框(普通箱)
            bar_ylim_max = 1.0
            label_offset = 0.04
            label_margin = 0.02

            lift_nn  = normal_df["lift"].values  if "lift"  in normal_df.columns and n_normal > 0 else [None]*n_normal
            pct_n_nn = normal_df["pct_n"].values if "pct_n" in normal_df.columns and n_normal > 0 else [None]*n_normal
            for xi, (wv, br, lv, pn) in enumerate(zip(woe_n, br_n, lift_nn, pct_n_nn)):
                lines_txt = [f"WOE: {wv:.3f}", f"BR: {br:.2%}"]
                if lv is not None:
                    lines_txt.append(f"Lift: {lv:.2f}x  |  {pn:.1%}"
                                     if pn is not None else f"Lift: {lv:.2f}x")
                label_txt = "\n".join(lines_txt)
                bar_top   = pct_good_n[xi] + pct_bad_n[xi]
                y_above   = bar_top + label_offset
                if y_above + label_margin <= bar_ylim_max:
                    y_text, va_text = y_above, "bottom"
                else:
                    y_text = min(bar_ylim_max - label_margin, bar_top) - 0.02
                    va_text = "top"
                ax_bar.annotate(
                    label_txt,
                    xy=(xi, wv), xycoords=("data", ax_woe.transData),
                    xytext=(xi, y_text),
                    textcoords=("data", ax_bar.transData),
                    fontsize=7.0, va=va_text, ha="center",
                    zorder=10,
                    bbox=dict(boxstyle="round,pad=0.3", fc="white",
                              ec="black", lw=0.8, zorder=10),
                    arrowprops=dict(arrowstyle="-", color="black", lw=0.8),
                )

            # 标注框(特殊值箱,紫色)
            lift_sv2  = sv_df["lift"].values  if "lift"  in sv_df.columns and n_sv > 0 else [None]*n_sv
            pct_n_sv2 = sv_df["pct_n"].values if "pct_n" in sv_df.columns and n_sv > 0 else [None]*n_sv
            for xi, (wv, br, pg, pb, lv, pn) in enumerate(
                    zip(woe_sv, br_sv, pct_good_sv, pct_bad_sv, lift_sv2, pct_n_sv2)):
                xi_abs = n_normal + xi
                lines_sv = [f"WOE: {wv:.3f}", f"BR: {br:.2%}"]
                if lv is not None:
                    lines_sv.append(f"Lift: {lv:.2f}x  |  {pn:.1%}"
                                    if pn is not None else f"Lift: {lv:.2f}x")
                label_txt = "\n".join(lines_sv)
                bar_top   = pg + pb
                y_above   = bar_top + label_offset
                if y_above + label_margin <= bar_ylim_max:
                    y_text, va_text = y_above, "bottom"
                else:
                    y_text = min(bar_ylim_max - label_margin, bar_top) - 0.02
                    va_text = "top"
                ax_bar.annotate(
                    label_txt,
                    xy=(xi_abs, wv), xycoords=("data", ax_woe.transData),
                    xytext=(xi_abs, y_text),
                    textcoords=("data", ax_bar.transData),
                    fontsize=7.0, va=va_text, ha="center",
                    zorder=10,
                    bbox=dict(boxstyle="round,pad=0.3", fc="#F5EEF8",
                              ec=SV_WOE, lw=0.9, zorder=10),
                    arrowprops=dict(arrowstyle="-", color=SV_WOE, lw=0.8),
                )

            # Legend: sv 区域右上角内部,有 sv 时合并两个 legend
            bar_handles, bar_labels = ax_bar.get_legend_handles_labels()
            if n_sv > 0:
                woe_handles2 = [l for l in ax_woe.get_lines()
                                if not l.get_label().startswith("_")]
                all_h = bar_handles + woe_handles2
                all_l = bar_labels + [l.get_label() for l in woe_handles2]
                anchor_x2 = n_total - 1.0
                ax_bar.legend(all_h, all_l,
                              loc="upper right",
                              bbox_to_anchor=(anchor_x2, 1.0),
                              bbox_transform=ax_bar.transData,
                              fontsize=8.0, framealpha=0.88,
                              ncol=2, borderpad=0.35, handlelength=1.2)
            else:
                ax_bar.legend(bar_handles, bar_labels,
                              loc="upper right",
                              fontsize=8.0, framealpha=0.88,
                              title="Target", title_fontsize=8.0,
                              ncol=2, borderpad=0.35)
            ax_woe.set_ylabel("WOE (TargetRate)", fontsize=9, color="#333")
            title = f"{feat}:  IV={iv_overall:.3f}"

        else:
            # ── By-group 图 ──
            if _df_for_group is None:
                logger.info(f"  [WARN] group_name='{group_name}' 需要传入 _df_for_group,跳过 {feat}")
                plt.close(fig)
                continue
            if group_name not in _df_for_group.columns or feat not in _df_for_group.columns:
                logger.info(f"  [WARN] group '{group_name}' 或 feature '{feat}' 不在 DataFrame 中")
                plt.close(fig)
                continue

            # ── 用拟合好的 edges 对各 group 分别分箱 ──
            fitted_edges = list(vr["edges"])
            eps = self.eps

            groups   = sorted(_df_for_group[group_name].dropna().unique())
            n_groups = len(groups)
            # tab10 调色板,最多 10 种颜色循环
            cmap_colors = plt.cm.tab10(np.linspace(0, 0.9, min(max(n_groups,1), 10)))
            group_ivs = []

            # WOE 基准:全量 total_bad / total_good(各组 WOE 相对全量,保证跨组可比)
            all_normal_df, all_sv_groups = self._split_special_for_plot(_df_for_group, feat, vr)
            all_normal_sub = all_normal_df[[feat, self.target_col]].dropna(subset=[feat]).copy()
            all_normal_sub["_bin"] = self._assign_normal_bins(
                all_normal_sub, feat, vr, fitted_edges)
            all_normal_sub = all_normal_sub[all_normal_sub["_bin"].notna()]
            all_total_bad  = float(all_normal_sub[self.target_col].sum())
            all_total_good = float((all_normal_sub[self.target_col] == 0).sum())

            # ── 柱图模式:pooled(全量单套柱)vs clustered(各组并排柱)──
            if bar_mode == "pooled":
                # 全量普通箱比例(分母 = 全量普通行数)
                all_n_full = len(all_normal_sub)
                pct_good_n_grp = np.zeros(n_normal)
                pct_bad_n_grp  = np.zeros(n_normal)
                for b in range(n_normal):
                    grp_b  = all_normal_sub[all_normal_sub["_bin"] == b]
                    bad_b  = float(grp_b[self.target_col].sum())
                    good_b = float((grp_b[self.target_col] == 0).sum())
                    pct_good_n_grp[b] = good_b / (all_n_full + eps) if all_n_full > 0 else 0.0
                    pct_bad_n_grp[b]  = bad_b  / (all_n_full + eps) if all_n_full > 0 else 0.0
                # 全量特殊值箱比例(分母 = 全量行数)
                all_sv_n = len(_df_for_group)
                pct_good_sv_grp = np.zeros(n_sv)
                pct_bad_sv_grp  = np.zeros(n_sv)
                if n_sv > 0:
                    for si, sv_row in enumerate(sv_df.itertuples()):
                        matched_sv_df = None
                        for sv_key, sv_sub in all_sv_groups.items():
                            if _sv_label(sv_key) == sv_row.bin_label:
                                matched_sv_df = sv_sub
                                break
                        if matched_sv_df is not None and len(matched_sv_df) > 0:
                            pct_good_sv_grp[si] = float((matched_sv_df[self.target_col] == 0).sum()) / (all_sv_n + eps)
                            pct_bad_sv_grp[si]  = float(matched_sv_df[self.target_col].sum()) / (all_sv_n + eps)
                # 画全量单套柱
                if n_normal > 0:
                    ax_bar.bar(x_normal, pct_good_n_grp, color=GOOD_COLOR,
                               alpha=0.45, width=0.6, zorder=2)
                    ax_bar.bar(x_normal, pct_bad_n_grp, bottom=pct_good_n_grp,
                               color=BAD_COLOR, alpha=0.45, width=0.6, zorder=2)
                if n_sv > 0:
                    ax_bar.bar(x_sv, pct_good_sv_grp, color=SV_GOOD, alpha=0.35,
                               width=0.6, zorder=2, edgecolor="#888",
                               linewidth=1.0, linestyle="--")
                    ax_bar.bar(x_sv, pct_bad_sv_grp, bottom=pct_good_sv_grp,
                               color=SV_BAD, alpha=0.35, width=0.6, zorder=2,
                               edgecolor="#888", linewidth=1.0, linestyle="--")
            else:  # clustered:每个箱位置并排 n_groups 根柱,柱宽均分簇宽
                cluster_w = 0.8                       # 每个箱簇占据的总宽度
                bar_w     = cluster_w / max(n_groups, 1)

            # 特殊值分隔线 + 标注(pooled / clustered 公共)
            if n_sv > 0:
                ax_bar.axvline(x=n_normal - 0.5, color="#888",
                               linewidth=1.0, linestyle=":", zorder=3)
                ax_bar.text(n_normal + 0.05, 0.93, "Special",
                            fontsize=8, color=SV_WOE, va="top",
                            transform=ax_bar.transData)

            # 逐组:算 WOE 折线(clustered 时另画该组组内占比柱)
            for gi, grp_val in enumerate(groups):
                grp_df_full = _df_for_group[_df_for_group[group_name] == grp_val]
                n_grp = len(grp_df_full)
                tr    = grp_df_full[self.target_col].mean() if n_grp > 0 else 0.0
                clr   = cmap_colors[gi % len(cmap_colors)]

                # 分离该组的特殊值与普通行,并按 edges/类别取值分箱
                grp_normal_df, grp_sv_groups = self._split_special_for_plot(grp_df_full, feat, vr)
                grp_sub = grp_normal_df[[feat, self.target_col]].dropna(subset=[feat]).copy()
                grp_sub["_bin"] = self._assign_normal_bins(grp_sub, feat, vr, fitted_edges)
                grp_sub = grp_sub[grp_sub["_bin"].notna()]

                # 普通箱:组内占比(分母=该组总样本 n_grp)+ WOE(相对全量基准)
                pct_good_n_g = np.zeros(n_normal)
                pct_bad_n_g  = np.zeros(n_normal)
                grp_woe = []
                grp_iv  = 0.0
                for b in range(n_normal):
                    bin_rows = grp_sub[grp_sub["_bin"] == b]
                    bad_b  = float(bin_rows[self.target_col].sum())
                    good_b = float((bin_rows[self.target_col] == 0).sum())
                    pct_good_n_g[b] = good_b / (n_grp + eps)
                    pct_bad_n_g[b]  = bad_b  / (n_grp + eps)
                    if len(bin_rows) == 0:
                        grp_woe.append(np.nan)
                        continue
                    pct_bad_w  = bad_b  / (all_total_bad  + eps)
                    pct_good_w = good_b / (all_total_good + eps)
                    woe_b = math.log((pct_bad_w + eps) / (pct_good_w + eps))
                    grp_iv += (pct_bad_w - pct_good_w) * woe_b
                    grp_woe.append(woe_b)

                # ── clustered:画该组组内占比柱(边框用组色,与 WOE 折线对应)──
                if bar_mode == "clustered":
                    x_off      = -cluster_w / 2 + bar_w * (gi + 0.5)
                    x_normal_g = x_normal + x_off
                    x_sv_g     = x_sv + x_off

                    pct_good_sv_g = np.zeros(n_sv)
                    pct_bad_sv_g  = np.zeros(n_sv)
                    if n_sv > 0:
                        for si, sv_row in enumerate(sv_df.itertuples()):
                            matched_sv_df = None
                            for sv_key, sv_sub in grp_sv_groups.items():
                                if _sv_label(sv_key) == sv_row.bin_label:
                                    matched_sv_df = sv_sub
                                    break
                            if matched_sv_df is not None and len(matched_sv_df) > 0:
                                pct_good_sv_g[si] = float((matched_sv_df[self.target_col] == 0).sum()) / (n_grp + eps)
                                pct_bad_sv_g[si]  = float(matched_sv_df[self.target_col].sum()) / (n_grp + eps)

                    if n_normal > 0:
                        ax_bar.bar(x_normal_g, pct_good_n_g, color=GOOD_COLOR,
                                   alpha=0.55, width=bar_w, zorder=2,
                                   edgecolor=clr, linewidth=0.8)
                        ax_bar.bar(x_normal_g, pct_bad_n_g, bottom=pct_good_n_g,
                                   color=BAD_COLOR, alpha=0.55, width=bar_w, zorder=2,
                                   edgecolor=clr, linewidth=0.8)
                    if n_sv > 0:
                        ax_bar.bar(x_sv_g, pct_good_sv_g, color=SV_GOOD,
                                   alpha=0.5, width=bar_w, zorder=2,
                                   edgecolor=clr, linewidth=0.8, linestyle="--")
                        ax_bar.bar(x_sv_g, pct_bad_sv_g, bottom=pct_good_sv_g,
                                   color=SV_BAD, alpha=0.5, width=bar_w, zorder=2,
                                   edgecolor=clr, linewidth=0.8, linestyle="--")

                # ── 画该组 WOE 折线(画在箱中心 x_normal,便于跨组对齐对比)──
                if n_grp < 5 or grp_df_full[self.target_col].nunique() < 2:
                    group_ivs.append(0.0)
                    lbl = f"{grp_val}  N={n_grp:,}  TR={tr:.1%}  IV=0.000"
                    ax_woe.plot(x_normal, [np.nan] * n_normal,
                                color=clr, linewidth=1.5, marker="o",
                                markersize=4, zorder=5, label=lbl)
                else:
                    group_ivs.append(round(grp_iv, 4))
                    lbl = f"{grp_val}  N={n_grp:,}  TR={tr:.1%}  IV={grp_iv:.3f}"
                    ax_woe.plot(x_normal, grp_woe, color=clr,
                                linewidth=1.5, marker="o", markersize=4,
                                zorder=5, label=lbl)

            # Legend: 所有条目合并,放坐标轴右侧外部(更靠右,避免遮挡 WOE y轴标题)
            _bar_desc   = "pooled %" if bar_mode == "pooled" else "in-group %"
            dummy_good  = plt.Rectangle((0,0),1,1, color=GOOD_COLOR, alpha=0.6)
            dummy_bad   = plt.Rectangle((0,0),1,1, color=BAD_COLOR,  alpha=0.6)
            woe_lines_h = [l for l in ax_woe.get_lines()
                           if not l.get_label().startswith("_")]
            woe_labels_h = [l.get_label() for l in woe_lines_h]
            all_handles  = [dummy_good, dummy_bad] + woe_lines_h
            all_labels_l = ["0 (Good)", "1 (Bad)"] + woe_labels_h
            ax_bar.legend(all_handles, all_labels_l,
                          loc="center left",
                          bbox_to_anchor=(1.18, 0.5),
                          bbox_transform=ax_bar.transAxes,
                          fontsize=7.5, framealpha=0.92,
                          ncol=1, borderpad=0.5, handlelength=1.5,
                          title=f"Group WOE (bar={_bar_desc})", title_fontsize=8.0)

            iv_vals  = [v for v in group_ivs if v > 0]
            iv_range = (f"{min(iv_vals):.3f}-{max(iv_vals):.3f}"
                        if iv_vals else "0.000-0.000")
            title = f"{feat}:  IV_range={iv_range}"
            ax_woe.set_ylabel("WOE", fontsize=9, color="#333")

        # ── 通用轴格式 ──
        all_labels = (
            [str(b) for b in normal_df["bin_label"]]
            + ([str(b) for b in sv_df["bin_label"]] if n_sv > 0 else [])
        )
        ax_bar.set_xlim(-0.5, n_total - 0.5)
        ax_bar.set_ylim(0, 1.0)

        # ── 动态计算 WOE y 轴范围(避免折线超出坐标轴)──
        # 收集所有已绘制折线上的有效 WOE 值
        _all_woe_pts = []
        for _line in ax_woe.get_lines():
            _yd = np.array(_line.get_ydata(), dtype=float)
            _all_woe_pts.extend(_yd[~np.isnan(_yd)].tolist())
        if _all_woe_pts:
            _woe_min = min(_all_woe_pts)
            _woe_max = max(_all_woe_pts)
            # padding: 15% of span, 最少 ±0.1 的绝对余量
            _span   = max(_woe_max - _woe_min, 0.2)
            _pad    = max(_span * 0.15, 0.1)
            _y_lo   = _woe_min - _pad
            _y_hi   = _woe_max + _pad
            # 至少覆盖 [-0.5, 0.5],且 0 刻度要在范围内
            _y_lo   = min(_y_lo, -0.5)
            _y_hi   = max(_y_hi,  0.5)
        else:
            _y_lo, _y_hi = -1.0, 1.0
        ax_woe.set_ylim(_y_lo, _y_hi)
        ax_woe.axhline(0, color="gray", linewidth=0.6, linestyle="--", zorder=1)

        ax_bar.set_xticks(x_all)
        ax_bar.set_xticklabels(
            [textwrap.fill(lb, width=14) for lb in all_labels],
            fontsize=8, rotation=30, ha="right",
        )
        ax_bar.set_ylabel("Proportion", fontsize=9)
        ax_bar.yaxis.set_major_formatter(mticker.PercentFormatter(xmax=1, decimals=0))
        ax_bar.tick_params(axis="y", labelsize=8)
        ax_woe.tick_params(axis="y", labelsize=8)
        ax_bar.grid(axis="y", alpha=0.3, zorder=0)
        ax_bar.set_axisbelow(True)

        plt.title(title, fontsize=11, fontweight="bold", pad=10)
        if group_name is not None:
            # by-group 模式:legend 在右侧外,预留右边空间(含 IV 文字,留更多右边距)
            plt.tight_layout(rect=[0, 0, 0.78, 1])
        else:
            plt.tight_layout()

        safe_feat  = feat.replace("/", "_").replace("\\", "_")
        suffix_str = f"_by_{group_name}" if group_name else ""
        out_file   = os.path.join(graph_path, f"{safe_feat}{suffix_str}.png")
        plt.savefig(out_file, dpi=dpi, bbox_inches="tight")
        plt.close(fig)
        logger.info(f"  [plot_woe_graph] {out_file}")

    logger.info(f"[plot_woe_graph] 全部图表已保存至: {graph_path}")

WOE Excel 报告 — WOE_Report_Builder

WOE_Report_Builder

WoeReportBuilder

A streamlined class for creating multiple WOE analysis report sheets in one Excel workbook.

Example usage: builder = WoeReportBuilder( em=em, data=data, valid_varlist=valid_varlist, woe_suffix='_woe', proc_means_func=proc_means_by_grp, missing_rate_ref=0.95, default_var_dict=var_dict_1 ) builder.add_group('sample_ind_fnl', woe_plot_dir='../customized_woe_by_sample/') builder.add_group('launch_month', woe_plot_dir='../customized_woe_by_month/') builder.add_group('platform_2', woe_plot_dir='../customized_woe_by_platform/') builder.close()

源代码位于: Modeling_Tool/WOE/WOE_Report_Builder.py
class WoeReportBuilder:
    """
    A streamlined class for creating multiple WOE analysis report sheets in one Excel workbook.

    Example usage:
        builder = WoeReportBuilder(
            em=em,
            data=data,
            valid_varlist=valid_varlist,
            woe_suffix='_woe',
            proc_means_func=proc_means_by_grp,
            missing_rate_ref=0.95,
            default_var_dict=var_dict_1
        )
        builder.add_group('sample_ind_fnl', woe_plot_dir='../customized_woe_by_sample/')
        builder.add_group('launch_month', woe_plot_dir='../customized_woe_by_month/')
        builder.add_group('platform_2', woe_plot_dir='../customized_woe_by_platform/')
        builder.close()
    """

    def __init__(self, em, data, valid_varlist: list, woe_suffix: str = '_woe',
                 proc_means_func=None, missing_rate_ref=0.95,
                 default_var_dict: dict = None):
        """
        Parameters
        ----------
        em : ExcelMaster
            An initialized ExcelMaster instance (with the target .xlsx file path).
        data : pd.DataFrame
            The full dataset (must contain the raw variables and their woe columns).
        valid_varlist : list
            List of variable names to be plotted.
        woe_suffix : str
            Suffix that identifies the woe‑transformed columns (e.g., '_woe').
        proc_means_func : callable
            Function with signature (data, full_var_list, group_cols, spec_missing_value) -> pd.DataFrame
            It should return a long-format dataframe of binned means.
        missing_rate_ref : float
            Missing rate threshold for proc_means_func.
        default_var_dict : dict, optional
            Default dictionary mapping variable name -> explanation text.
            Can be overridden per group if needed.
        """

        self.proc_means_func = proc_means_func
        if proc_means_func is None:
            from Modeling_Tool.Feature.Distribution_Tool import proc_means_by_grp
            self.proc_means_func = proc_means_by_grp

        self.em = em
        self.data = data
        self.valid_varlist = valid_varlist
        self.woe_suffix = woe_suffix
        self.missing_rate_ref = missing_rate_ref
        self.default_var_dict = default_var_dict or {}

        # Pre‑cast raw variables to float (as done in the original script)
        try:
            self.data[self.valid_varlist] = self.data[self.valid_varlist].astype(float)
        except KeyError as e:
            logging.warning(f"Some valid variables not found in data: {e}")

        # Build full variable list (raw + woe columns)
        self.full_var_list = self.valid_varlist + [x + self.woe_suffix for x in self.valid_varlist]

    def add_group(self, group_name: str, woe_plot_dir: str,
                  sheet_name: str = None, cell_scale: tuple = (1, 2),
                  var_dict: dict = None):
        """
        Add a new worksheet with WOE plots for the given group.

        Parameters
        ----------
        group_name : str
            Name of the grouping column (e.g., 'sample_ind_fnl').
        woe_plot_dir : str
            Path to the directory containing the pre‑generated WOE images.
            The function expects files like {var}.png and {var}_{group_name}.png.
        sheet_name : str, optional
            Name of the Excel sheet. If not given, a name like "Bivar_{group_name}" is used.
        cell_scale : tuple (row_scale, col_scale), default (1, 2)
            Cell size scaling for the worksheet.
        var_dict : dict, optional
            Variable explanation dictionary. Falls back to self.default_var_dict.
        """
        # Compute means report using the provided function
        means_rpt = self.proc_means_func(
            self.data,
            self.full_var_list,
            [group_name],
            spec_missing_value=self.missing_rate_ref
        )

        # Build sheet name
        if sheet_name is None:
            sheet_name = f"Bivar_{group_name}"

        # Add worksheet
        ws = self.em.add_worksheet(name=sheet_name, cell_scale=cell_scale)

        # Use the provided var_dict or fall back to default
        active_var_dict = var_dict if var_dict is not None else self.default_var_dict

        # Call the updated plot report function (get_woe_plot_report_new)
        # which must now accept var_dict.
        get_woe_plot_report_new(
            self.em, ws,
            woe_plot_dir=woe_plot_dir,
            grp_name=group_name,
            varlist=self.valid_varlist,
            means_rpt=means_rpt,
            var_dict=active_var_dict
        )

        logging.info(f"Added WOE report sheet: {sheet_name}")

    def close(self):
        """Close and save the Excel workbook."""
        self.em.close_workbook()

add_group

add_group(group_name: str, woe_plot_dir: str, sheet_name: str = None, cell_scale: tuple = (1, 2), var_dict: dict = None)

Add a new worksheet with WOE plots for the given group.

参数:

名称 类型 描述 默认
group_name str

Name of the grouping column (e.g., 'sample_ind_fnl').

必需
woe_plot_dir str

Path to the directory containing the pre‑generated WOE images. The function expects files like {var}.png and {var}_{group_name}.png.

必需
sheet_name str

Name of the Excel sheet. If not given, a name like "Bivar_{group_name}" is used.

None
cell_scale tuple(row_scale, col_scale)

Cell size scaling for the worksheet.

(1, 2)
var_dict dict

Variable explanation dictionary. Falls back to self.default_var_dict.

None
源代码位于: Modeling_Tool/WOE/WOE_Report_Builder.py
def add_group(self, group_name: str, woe_plot_dir: str,
              sheet_name: str = None, cell_scale: tuple = (1, 2),
              var_dict: dict = None):
    """
    Add a new worksheet with WOE plots for the given group.

    Parameters
    ----------
    group_name : str
        Name of the grouping column (e.g., 'sample_ind_fnl').
    woe_plot_dir : str
        Path to the directory containing the pre‑generated WOE images.
        The function expects files like {var}.png and {var}_{group_name}.png.
    sheet_name : str, optional
        Name of the Excel sheet. If not given, a name like "Bivar_{group_name}" is used.
    cell_scale : tuple (row_scale, col_scale), default (1, 2)
        Cell size scaling for the worksheet.
    var_dict : dict, optional
        Variable explanation dictionary. Falls back to self.default_var_dict.
    """
    # Compute means report using the provided function
    means_rpt = self.proc_means_func(
        self.data,
        self.full_var_list,
        [group_name],
        spec_missing_value=self.missing_rate_ref
    )

    # Build sheet name
    if sheet_name is None:
        sheet_name = f"Bivar_{group_name}"

    # Add worksheet
    ws = self.em.add_worksheet(name=sheet_name, cell_scale=cell_scale)

    # Use the provided var_dict or fall back to default
    active_var_dict = var_dict if var_dict is not None else self.default_var_dict

    # Call the updated plot report function (get_woe_plot_report_new)
    # which must now accept var_dict.
    get_woe_plot_report_new(
        self.em, ws,
        woe_plot_dir=woe_plot_dir,
        grp_name=group_name,
        varlist=self.valid_varlist,
        means_rpt=means_rpt,
        var_dict=active_var_dict
    )

    logging.info(f"Added WOE report sheet: {sheet_name}")

close

close()

Close and save the Excel workbook.

源代码位于: Modeling_Tool/WOE/WOE_Report_Builder.py
def close(self):
    """Close and save the Excel workbook."""
    self.em.close_workbook()

分组指标工具 — plot_woe_tool

plot_woe_tool

extract_group_value

extract_group_value(woe_grp_df, value_name='lift')

获取指标值矩阵.

参数:

名称 类型 描述 默认
woe_grp_df DataFrame

分组WOE表

必需
value_name str

指标名称, 候选值"p", "p1"

lift

返回:

名称 类型 描述
value_df DataFrame
源代码位于: Modeling_Tool/WOE/plot_woe_tool.py
def extract_group_value(woe_grp_df, value_name="lift"):
    """获取指标值矩阵.

    Parameters
    ----------
    woe_grp_df : pandas.DataFrame
        分组WOE表
    value_name : str, default lift
        指标名称, 候选值"p", "p1"

    Returns
    -------
    value_df: pandas.DataFrame
    """
    value_df = pd.pivot_table(woe_grp_df, index=["Var_Name", "Bin_No", "Bin_Value"], columns="Group_Name", values=value_name)

    return value_df

cre_psi_table

cre_psi_table(woe_grp_df, exp_values, value_name='p')

计算psi值 psi = sum((a - e) * ln(a / e))

参数:

名称 类型 描述 默认
woe_grp_df DataFrame

分组WOE表

必需
exp_values array like

期望值序列

必需
value_name str

psi计算字段, 候选值"p", "p1"

p

返回:

名称 类型 描述
psi float
源代码位于: Modeling_Tool/WOE/plot_woe_tool.py
def cre_psi_table(woe_grp_df, exp_values, value_name="p"):
    """计算psi值
    psi = sum((a - e) * ln(a / e))

    Parameters
    ----------
    woe_grp_df : pandas.DataFrame
        分组WOE表
    exp_values : array like
        期望值序列
    value_name : str, default p
        psi计算字段, 候选值"p", "p1"

    Returns
    -------
    psi: float
    """
    value_df = extract_group_value(woe_grp_df, value_name)
    psi_df = {}
    for g in value_df.columns:
        components = []
        for actual, expected in zip(value_df[g], exp_values):
            pair = pd.DataFrame(
                {"actual": [actual], "expected": [expected]}
            )
            components.append(
                calc_iv(pair, "actual", "expected").iloc[0]
            )
        psi_df.update({g: components}) # psi计算函数与iv相同
    psi_df = pd.DataFrame(psi_df, index=value_df.reset_index()['Bin_Value'])
    psi_df.loc["psi"] = psi_df.apply(sum)
    psi_df.loc[:, "avg_psi"] = psi_df.apply(np.mean, axis=1)

    return psi_df

plot_woe

plot_woe(woe_df, var_rename=None, to_show=True, save_dir=None)

绘制变量的WOE图.

参数:

名称 类型 描述 默认
woe_df

WOE表

必需
var_rename

变量重命名

None
to_show

是否展示图片

True
save_dir

结果图片存放的文件夹

None
源代码位于: Modeling_Tool/WOE/plot_woe_tool.py
def plot_woe(woe_df, var_rename = None, to_show=True, save_dir=None):
    """绘制变量的WOE图.

    Parameters
    ----------
    woe_df: pandas.DataFrame
        WOE表
    var_rename: str, default Non
        变量重命名
    to_show: bool, default True
        是否展示图片
    save_dir: str, default None
        结果图片存放的文件夹
    """
    var_name = woe_df["Var_Name"].iloc[0]
    iv = round(sum(woe_df["iv"]), 5)
    X = woe_df["Bin_No"]
    xticks_list = [str(x)[:20]+"..." if len(str(x)) > 20 else str(x) for x in woe_df["Bin_Value"]]

    # 创建画布
    plt.figure(figsize=(12, 5), dpi=200) # 8,4
    grid = plt.GridSpec(1, 12, wspace=0.5, hspace=0.5)

    # 1.绘制Woe图
    ax1 = plt.subplot(grid[:, :5])
    # 绘制主坐标轴
    ax1.bar(X, woe_df["p"], color=palette["single_01"][0], label="0", align="edge", width=0.985, alpha=0.8)
    ax1.bar(X, woe_df["p"] * woe_df["tr"], color=palette["single_01"][1], label="1", align="edge", width=0.985)

    plt.xticks(X+0.5, xticks_list, fontsize=6)
    plt.yticks(fontsize=6)
    ax1.axis(ymin=0.0, ymax=1)
    ax1.set_ylabel("Proportion", fontsize=6)
    ax1.legend(loc=2, fontsize=6)

    # 绘制次坐标轴
    ax1_2 = plt.twinx()
    plt.axis(ymin=np.min([-1, woe_df["woe"].min() * 1.1]), ymax=np.max([1, woe_df["woe"].max() * 1.1])) # 设置次轴区间
    plt.plot(X+0.5, woe_df["woe"], color="black", linewidth=1.5)
    for x, woe, tr in zip(X, woe_df["woe"], woe_df["tr"]):
        ax1_2.annotate(f"{woe:.3f} ({tr:.2%})",
            xy=(x+0.5, woe),
            va="center", 
            ha="center",
            bbox={"boxstyle": "round", "fc": "w"}, 
            fontsize=7
            )
    plt.yticks(fontsize=6)
    ax1_2.set_ylabel("Woe (TargetRate)", fontsize=6)

    # 绘制标题
    if bool(var_rename):
        plt.title(f"{str(var_rename)}: IV={iv:.3f}", fontsize=12, fontproperties=zhfont)
    else:
        plt.title(f"{var_name}: IV={iv:.3f}", fontsize=12, fontproperties=zhfont)

    # 2.绘制Woe表
    ax2 = plt.subplot(grid[:, 7:])
    ax2.set_axis_off()
    # plt.subplots_adjust(left=0.2, bottom=0.2)

    # 调整要展示的数据
    tbl = woe_df[["n", "p", "tr", "lift", "woe",]].copy()
    tbl.loc["total"] = [tbl["n"].sum(), tbl["p"].sum(), woe_df["n1"].sum()/woe_df["n"].sum(), 1, 0]
    tbl["n"] = [f"{x:,.0f}" for x in tbl["n"]]
    tbl["p"] = [f"{x:.2%}" for x in tbl["p"]]
    tbl["tr"] = [f"{x:.2%}" for x in tbl["tr"]]
    tbl["lift"] = [f"{x:.2}" for x in tbl["lift"]]
    tbl["woe"] = [f"{x:.3f}" for x in tbl["woe"]]

    # 绘制表格
    rowls = xticks_list
    rowls.append("total")
    tbl = ax2.table(
        cellText=tbl[["n", "p", "tr", "lift", "woe"]].values,
        colLabels=["N", "Prop", "TargetRate", "Lift", "WOE"],
        rowLabels=rowls,
        colWidths=[0.2]*5,
        # rowHeights=[0.1]*len(xticks_list),
        loc="center",
        cellLoc="right",
        rowLoc="right",
        colLoc="center",
        colColours=["#CCCCCC"]*5,
        rowColours=["#CCCCCC"]*len(rowls),
    )

    tbl.scale(1, 1.5)
    for key, cell in tbl.get_celld().items():
        row, col = key
        if row == 0 or col == -1:
             cell.set_text_props(font=zhfont, fontsize=7, fontstyle="oblique")
        if row > 0 and col > -1:
            cell.set_text_props(font=zhfont, fontsize=7)

    # 保存结果
    if bool(save_dir):
        plt.savefig(os.path.join(save_dir, f"{var_name}.png"), bbox_inches="tight")

    # 展示结果
    if to_show:
        plt.show()
    plt.close()

plot_woe_group

plot_woe_group(woe_grp_df, var_rename=None, to_show=True, save_dir=None)

绘制变量的分组WOE图.

参数:

名称 类型 描述 默认
woe_grp_df

分组WOE表

必需
var_rename str

变量重命名

None
to_show

是否展示图片

True
save_dir

结果图片存放的文件夹

None
源代码位于: Modeling_Tool/WOE/plot_woe_tool.py
def plot_woe_group(woe_grp_df, var_rename = None, to_show=True, save_dir=None):
    """绘制变量的分组WOE图.

    Parameters
    ----------
    woe_grp_df: pandas.DataFrame
        分组WOE表
    var_rename : str, default None
        变量重命名
    to_show: bool, default True
        是否展示图片
    save_dir: str, default None
        结果图片存放的文件夹
    """
    var_name = woe_grp_df["Var_Name"].iloc[0]
    summary_df = woe_grp_df.groupby(["Group_Name"]).agg({"iv": sum, "n": sum, "n1": sum})
    summary_df["tr"] = summary_df["n1"] / summary_df["n"]

    iv_dict = {x: round(y, 5) for x, y in zip(summary_df.index, summary_df["iv"])}
    tr_dict = {x: round(y, 5) for x, y in zip(summary_df.index, summary_df["tr"])}
    N_dict = {x: y for x, y in zip(summary_df.index, summary_df["n"])}
    X = woe_grp_df["Bin_No"].drop_duplicates()
    Xticks = woe_grp_df.groupby(["Bin_No"]).agg({"Bin_Value": max})["Bin_Value"]

    gs = list(set(woe_grp_df["Group_Name"]))
    gs.sort()
    n = len(gs)

    # 构建画布
    plt.figure(figsize=(12, 5), dpi=200) # 8,4
    grid = plt.GridSpec(1, 12, wspace=0.5, hspace=0.5)

    # 1.绘制Woe图
    ax1 = plt.subplot(grid[:, :5])

    # 绘制主坐标轴
    width = 0.9 / n
    alpha = 0.5 / n
    for i in range(n):
        g = gs[i]
        df_plot = woe_grp_df.loc[woe_grp_df["Group_Name"] == g, ].reset_index(drop=True)
        ax1.bar(X + i * (0.01 + width), df_plot["p"], color=palette["single_01"][0], label=f"{g} N={N_dict[g]:,.0f} TR={tr_dict[g]:.2%}", align="edge", width=width, alpha=0.5 + alpha*(i+1))
        ax1.bar(X + i * (0.01 + width), df_plot["p"] * df_plot["tr"], color=palette["red_list"][2], align="edge", width=width, alpha=1)

    xticks_list = [str(x)[:20]+"..." if len(str(x)) > 20 else str(x) for x in Xticks]
    plt.xticks(X+0.5, xticks_list, fontsize=6)
    plt.axis(ymin=0.0, ymax=1)
    plt.yticks(fontsize=6)
    plt.ylabel("Proportion", fontsize=6)
    plt.legend(loc=2, fontsize=6)

    # 绘制次坐标轴
    alpha = 0.8 / n
    ax1_2 = plt.twinx()
    for i in range(n):
        g = gs[i]
        df_plot = woe_grp_df.loc[woe_grp_df["Group_Name"] == g, ].reset_index(drop=True)
        plt.plot(X+0.5, df_plot["woe"], color=palette["grey"], linewidth=1, label=f"{g} IV={iv_dict[g]:.2f}", alpha=0.2 + alpha*(i+1))
    plt.axis(ymin=np.min([-1, woe_grp_df["woe"].min() * 1.1]), ymax=np.max([1, woe_grp_df["woe"].max() * 1.1])) # 设置次轴区间
    plt.yticks(fontsize=6)
    plt.ylabel("Woe", fontsize=6)
    plt.legend(loc=1, fontsize=6)

    # 绘制总标题
    if bool(var_rename):
        plt.title(f"{str(var_rename)}: IV_range={summary_df.iv.min():.2f}-{summary_df.iv.max():.2f}", fontsize=12, fontproperties=zhfont)
    else:
        plt.title(f"{var_name}: IV_range={summary_df.iv.min():.2f}-{summary_df.iv.max():.2f}", fontsize=12, fontproperties=zhfont)

    # 2.绘制Woe表
    ax2 = plt.subplot(grid[:, 7:])
    ax2.set_axis_off()

    # 调整要展示的数据
    tbl = pd.DataFrame()
    for i in range(n):
        g = gs[i]
        tbl.loc[:, g] = woe_grp_df.loc[woe_grp_df["Group_Name"] == g, "woe"]
        tbl.loc[:, g] = [f"{x:.3f}" for x in tbl[g]]

    # 绘制表格
    rowls = xticks_list
    colls = ["_".join([x, "woe"]) for x in gs]
    tbl = ax2.table(
        cellText=tbl.values,
        colLabels=colls,
        rowLabels=rowls,
        colWidths=[1.0 / n] * n,
        loc="center",
        cellLoc="right",
        rowLoc="right",
        colLoc="center",
        colColours=["#CCCCCC"] * n,
        rowColours=["#CCCCCC"] * len(rowls),
    )
    tbl.scale(1, 1.5)
    for key, cell in tbl.get_celld().items():
        row, col = key
        if row == 0 or col == -1:
             cell.set_text_props(font=zhfont, fontsize=7, fontstyle="oblique")
        if row > 0 and col > -1: 
            cell.set_text_props(font=zhfont, fontsize=7)

    # 保存结果
    if bool(save_dir):
        plt.savefig(os.path.join(save_dir, f"{var_name}_group.png"), bbox_inches="tight")

    # 展示结果
    if to_show:
        plt.show()
    plt.close()