风控建模流程#

本示例用 kivi 走一遍评分卡项目的各个步骤:分析并筛选候选变量,对入选变量分箱,用 WOE 编码并保存分箱供生产环境使用,筛选变量并拟合模型,刻度为评分卡,评估模型,基于主标尺校准模型,设定截断点并计算预期损失,并准备监控所需的稳定性报告。随包数据记录的是营销响应而非违约,但对信用违约标记来说步骤完全相同:把坏样本标记作为 target 即可。

银行数据没有交易或还款的历史,因此本例直接从各列的概况开始。有这类事件时,先由 时间窗特征 把它们变成候选变量,只使用每个观察日期时已知的信息,再由概况把它们与其他列一起筛选。

>>> import numpy as np
>>> import pandas as pd
>>> from kivi.binning import bin_edges
>>> from kivi.datasets import load_bank
>>> from kivi.stability import psi_table
>>> from kivi.woe import woe_table, woe_transform
>>> data = load_bank()
>>> development, monitoring = data.iloc[:3000], data.iloc[3000:]

按 IV 筛选变量#

先为每个候选变量做概况分析。 profile_table() 为每个变量给出一行,包括缺失值、最常见的取值,以及在给定目标变量时按统一方式快速分箱得到的 IV:数值变量分为五个等频箱,类别变量直接使用原始标签;见 单变量概况 。各变量的 IV 给出初步排序, tied_bins 标出取值并列导致箱数少于要求的数值变量:

>>> from kivi.univariate import profile_table
>>> profile = profile_table(development.drop(columns="target"), development["target"])
>>> profile.index[profile["tied_bins"]].tolist()
['campaign', 'pdays', 'previous']
>>> iv = profile["iv"].sort_values(ascending=False)
>>> iv.round(3).head(8)
variable
duration    1.594
poutcome    0.423
month       0.334
contact     0.215
job         0.137
housing     0.108
balance     0.099
loan        0.059
Name: iv, dtype: float64
银行数据中各变量的信息值排序,含 0.02、0.1 和 0.3 的解读区间

快速分箱下各候选变量的 IV。虚线标出 0.02、0.1 和 0.3 三个区间;duration 的柱子在图的右边缘被截断。#

在确定入选名单之前,请审慎地解读这个排序:

  • duration 是最后一次通话的时长。它只有在通话结束后才知道,而那时结果基本已经确定,因此它 1.59 的 IV 是信息泄漏而非有效信号。数据集的说明建议在构建实际可用的模型时排除它。在信用风险中,也要警惕在决策之后才填写的字段,例如催收状态。

  • month 描述的是营销活动开展的时间,而不是客户本身,因此同样排除。

  • pdays 和 previous 的 IV 为零,只是因为大量重复值使它们被压缩进一个等频箱。自定义边界或 special 参数都可以挽回 pdays ,见 自定义边界 和 特殊值 。

对入选变量分箱#

每个入选变量都使用可以解释的分组:余额采用合并后 WOE 单调的分箱,pdays == -1 编码单独成箱,年龄采用政策分段, poutcome 、 contact 和 housing 使用各自的标签,职业则合并为少数几组。小类别的 WOE 不稳定:只有几十位客户的职业只有寥寥几个事件,而在之后的样本上,12 种职业里有 4 种的 WOE 改变了符号,见 类别分组 。 chimerge_groups() 把事件率相近的职业合并为更大的组,并返回从职业到组的 dict:

>>> from kivi.binning import chimerge_groups, group_categories
>>> job_groups = chimerge_groups(development["job"], development["target"])
>>> job_groups["unknown"]
'technician, admin., housemaid, management, unknown'

每个组的标签按 WOE 从小到大列出其中的职业。开发样本中没有的职业不在 dict 中,因此在对新数据评分之前,要先决定它并入哪个组。本例通过 group_categories() 的 unseen 参数,让新职业并入 unknown (即未记录职业的客户)所在的组。把分箱逻辑集中在一处,确保开发数据和监控数据的分组完全一致:

>>> fine = bin_edges(development["balance"], bins=10)
>>> numeric_edges = {
...     "balance": fine[[0, 3, 7, 10]],
...     "pdays": np.array([-np.inf, -1, 100, 200, 300, np.inf]),
...     "age": np.array([-np.inf, 25, 35, 45, 55, 65, np.inf]),
... }
>>> categorical = ["poutcome", "contact", "housing"]
>>> new_job = job_groups["unknown"]
>>> def to_groups(frame):
...     groups = {column: pd.cut(frame[column], edges) for column, edges in numeric_edges.items()}
...     groups.update({column: frame[column] for column in categorical})
...     groups["job"] = group_categories(frame["job"], job_groups, unseen=new_job)
...     return pd.DataFrame(groups)
>>> dev_groups = to_groups(development)
>>> tables = {column: woe_table(dev_groups[column], development["target"]) for column in dev_groups}
>>> print(tables["job"][["total", "event_rate", "woe"]].round(3).to_string())
                                                                total  event_rate    woe
bin
blue-collar, services, self-employed, entrepreneur, unemployed   1210       0.079 -0.420
technician, admin., housemaid, management, unknown               1581       0.132  0.144
retired, student                                                  209       0.211  0.709

job 的三个组各有 209 到 1,581 位开发样本客户,WOE 从 -0.420 升至 0.709。 tables 为每个变量保存一个 woe_table() 结果。继续之前,请逐一以 WOE 图的形式复核(见 证据权重与信息值)。pdays 和 poutcome 都描述上一轮营销,同时保留之前请先检查二者的相关性。

WOE 编码#

基于 WOE 值的逻辑回归是经典的评分卡模型。用 woe_transform() 把每个分组替换为开发样本表中对应的 WOE:

>>> def to_woe(groups):
...     return pd.DataFrame({
...         column: woe_transform(groups[column], tables[column]) for column in groups
...     })
>>> X_dev = to_woe(dev_groups)
>>> X_dev.head(3).round(3)
   balance  pdays    age  poutcome  contact  housing    job
0    0.373 -0.257 -0.032    -0.257    0.241    0.333 -0.420
1    0.373 -0.092 -0.032     0.214    0.241   -0.327 -0.420
2    0.373 -0.092 -0.032     0.214    0.241   -0.327  0.144

对开发样本中从未出现的分组(例如 poutcome 的新类别), woe_transform 会引发错误。 job 的分组已经为新职业指定了组;对其他变量,请在对新数据评分之前约定处理方式,例如用 unseen=0.0 取中性的 WOE。

保存分箱#

生产系统对新申请的分组和编码必须与开发样本完全一致。 fit_spec() 一次拟合每列的边界和 WOE 表,得到的 BinningSpec 把它们保存为带版本号的 JSON;参见 分箱方案 。把入选变量的边界作为 bins 、 job 的方法 "chimerge" 以及新职业并入的组作为 unseen 传入,即可复现上面的分组和编码:

>>> from kivi.spec import BinningSpec, fit_spec
>>> spec = fit_spec(
...     development,
...     development["target"],
...     columns=list(dev_groups),
...     method={"job": "chimerge"},
...     bins=numeric_edges,
...     unseen={"job": {"group": new_job}},
... )
>>> spec.groups["job"] == job_groups
True
>>> spec.woe_transform(development).equals(X_dev)
True
>>> restored = BinningSpec.from_json(spec.to_json())
>>> restored == spec
True

把 JSON 与模型一起保存。打分服务用 BinningSpec.from_json 加载后,用 restored.woe_transform(frame) 对新数据编码,无需开发项目的代码,并给新职业 unknown 所在组的 WOE:

>>> restored.woe_transform(monitoring.head(1).assign(job="astronaut"))["job"].round(3).tolist()
[0.144]

筛选变量并拟合模型#

高度相关的变量携带相同的信息,还会让系数不稳定。 correlation_filter() 在每对相关系数超过 0.7 的变量中保留 IV 较高的一个,随后 stepwise() 按逻辑回归的 p 值筛选变量。以 WOE 作为输入时,所有系数都应为正, stepwise 会拒绝会使某个系数变为负的变量;详见 变量筛选 。

>>> from kivi.selection import correlation_filter, logistic_regression, stepwise
>>> target = development["target"]
>>> iv_dev = pd.Series({column: table["iv"].sum() for column, table in tables.items()})
>>> kept = correlation_filter(X_dev, priority=iv_dev)
>>> X_dev.columns.difference(kept).tolist()
[]
>>> selected = stepwise(X_dev[kept], target)
>>> selected.tolist()
['balance', 'pdays', 'poutcome', 'contact', 'housing', 'job']
>>> model = logistic_regression(X_dev[selected], target)
>>> model.round(3)
            coef     se       z  p_value
variable
intercept -2.028  0.062 -32.730    0.000
balance    0.796  0.183   4.360    0.000
pdays      0.356  0.122   2.920    0.004
poutcome   0.657  0.112   5.876    0.000
contact    0.588  0.153   3.850    0.000
housing    0.635  0.189   3.358    0.001
job        0.592  0.180   3.285    0.001

没有哪一对变量的相关性强到需要剔除变量, stepwise 去掉了 age 。模型只在开发样本上拟合。 vif_filter() 检查保留的变量之间是否存在涉及多个变量的共线性, selection_path() 则在验证样本上显示按 IV 顺序加入变量时从哪里开始不再带来收益; 变量筛选 介绍了这两个函数。

银行数据记录了每位客户的结果。信贷开发样本通常只包含原有策略批准的申请,仅用这些申请拟合的模型会低估原先被拒申请人的风险。 拒绝推断 推断这些申请人的结果,并通过 weights 重新拟合模型。

刻度为评分卡#

points_table() 把 WOE 表和系数转换为每组的分值。这里每增加 20 分,好坏比翻一倍;600 分对应 50 的好坏比;详见 评分卡 。WOE 越高风险越大,分值也就越低:

>>> from kivi.scorecard import points_table, woe_to_points
>>> scale = dict(pdo=20, base_score=600, base_odds=50)
>>> coefficients = model["coef"].drop("intercept")
>>> intercept = model.loc["intercept", "coef"]
>>> card = points_table({column: tables[column] for column in selected}, coefficients, intercept, **scale)
>>> card.loc["poutcome"].round({"woe": 3, "points": 1})
              bin    woe  points
variable
poutcome  unknown -0.257    95.8
poutcome  failure  0.214    86.9
poutcome    other  0.592    79.7
poutcome  success  2.548    42.6

用开发样本的表给监控样本打分:每个客户的分数是其各项分值之和。

>>> mon_groups = to_groups(monitoring)
>>> mon_points = woe_to_points(to_woe(mon_groups)[selected], coefficients, intercept, **scale)
>>> mon_score = mon_points.sum(axis=1)
>>> mon_points.assign(score=mon_score).head(3).round(1)
variable  balance  pdays  poutcome  contact  housing   job  score
3000         91.0   93.6      95.8     87.4     84.8  88.5  541.1
3001        102.9   93.6      95.8    106.5     96.9  88.5  584.2
3002         82.4   93.6      95.8     86.9     96.9  98.1  553.7

评估模型#

分数越高风险越低,而 模型表现 中的指标要求分数随事件概率升高。因此请传入每个分数对应的概率。增益表使用在开发样本分数上拟合的分段,使两个样本按同样的方式切分:

>>> from kivi.metrics import gains_table, gini, ks
>>> from kivi.scorecard import score_to_pd
>>> dev_score = woe_to_points(X_dev[selected], coefficients, intercept, **scale).sum(axis=1)
>>> dev_pd, mon_pd = score_to_pd(dev_score, **scale), score_to_pd(mon_score, **scale)
>>> y_mon = monitoring["target"]
>>> print(f"Gini = {gini(mon_pd, y_mon):.3f}, KS = {ks(mon_pd, y_mon):.3f}")
Gini = 0.375, KS = 0.281
>>> pd_edges = bin_edges(dev_pd, bins=5).round(3)
>>> gains = gains_table(mon_pd, y_mon, bins=pd_edges)
>>> gains[["total", "event_rate", "lift", "cum_event_share"]].round(3)
               total  event_rate   lift  cum_event_share
bin
(0.136, inf]     313       0.249  2.191            0.451
(0.1, 0.136]     294       0.102  0.897            0.624
(0.071, 0.1]     300       0.093  0.821            0.786
(0.05, 0.071]    235       0.077  0.673            0.890
(-inf, 0.05]     379       0.050  0.441            1.000

风险最高的分段约占监控样本的五分之一,却包含了 45% 的事件,事件率超过平均水平的两倍。

这种规模的监控样本对 Gini 的测量存在一定的不确定性。 roc_auc_interval() 给出 AUC 和 Gini 的 DeLong 标准误及 95% 区间:

>>> from kivi.metrics import roc_auc_interval
>>> roc_auc_interval(mon_pd, y_mon).round(3)
           estimate     se  lower  upper
statistic
auc           0.687  0.023  0.643  0.732
gini          0.375  0.046  0.285  0.464
>>> print(f"development Gini = {gini(dev_pd, target):.3f}")
development Gini = 0.429

在 1,521 名客户中有 173 个事件,Gini 的区间从 0.285 到 0.464。它包含开发样本的 Gini 0.429,而后者本身偏乐观,因为分箱、变量和系数都是在开发样本上拟合的,所以监控样本的 Gini 较低仍在抽样误差范围内。 模型表现 还用 DeLong 检验比较同一样本上的两个评分。

检查校准#

评级让不同模型的 PD 具有统一的含义。 master_scale() 由每个等级的 PD 构建标尺,这里共五个等级,每个等级的 PD 是前一个的两倍; assign_grades() 为监控样本中的每位客户分配其 PD 所属的等级;见 校准 。然后把每个等级与其 PD 比较。Jeffreys 检验考察一个等级的事件数是否多于其 PD 的预测,因此较小的 p 值提示该等级低估了风险:

>>> from kivi.calibration import assign_grades, calibration_table, jeffreys_test, master_scale
>>> scale = master_scale(np.geomspace(0.025, 0.4, 5), labels=list("ABCDE"))
>>> scale.round(4)
        lower  probability   upper
grade
A      0.0000        0.025  0.0354
B      0.0354        0.050  0.0707
C      0.0707        0.100  0.1414
D      0.1414        0.200  0.2828
E      0.2828        0.400  1.0000
>>> grades = assign_grades(mon_pd, scale)
>>> grade_table = calibration_table(grades, y_mon, mon_pd).join(scale["probability"])
>>> grade_table["jeffreys"] = jeffreys_test(
...     grade_table["event"], grade_table["total"], grade_table["probability"]
... )
>>> grade_table.round(3)
     total  event  event_rate  mean_probability  probability  jeffreys
bin
A       80      2       0.025             0.028        0.025     0.452
B      534     35       0.066             0.053        0.050     0.054
C      595     58       0.097             0.108        0.100     0.574
D      222     38       0.171             0.187        0.200     0.859
E       90     40       0.444             0.460        0.400     0.194

在 5% 的水平下没有等级被拒绝,但等级 B 已接近拒绝:其 6.6% 的事件率高于 5% 的 PD,p 值为 0.054,后续各期的监控应重点关注。等级 D 的事件少于其 PD 的预测,这种单侧检验不会标出这种情况。

设定截断点#

评分卡为申请人排序,截断点决定批准谁。 cutoff_table() 对每个候选的 PD 截断点给出它批准的申请人占比、通过客群的坏账率以及它拒绝的事件占比;见 信贷策略 。以各等级的上界作为截断点,就是批准截至该等级的所有等级:

>>> from kivi.strategy import cutoff_table, expected_loss_table
>>> policies = cutoff_table(mon_pd, y_mon, cutoffs=scale["upper"])
>>> columns = ["approval_rate", "approved_event_rate", "rejected_event_share"]
>>> policies.set_index(scale.index)[columns].round(3)
       approval_rate  approved_event_rate  rejected_event_share
grade
A              0.053                0.025                 0.988
B              0.404                0.060                 0.786
C              0.795                0.079                 0.451
D              0.941                0.093                 0.231
E              1.000                0.114                 0.000

批准等级 A 到 C,即 PD 不超过 14.1%,会以 7.9% 的坏账率批准 79.5% 的申请人,并拒绝 45.1% 的事件。若再批准等级 D,则以 9.3% 的坏账率批准 94.1% 的申请人。选择哪一行是业务决策;这张表给出了每种选择的代价。

一笔敞口的预期损失等于其 PD 乘以违约损失率,再乘以违约风险敞口。 expected_loss_table() 按等级汇总预期损失。银行数据没有贷款金额,因此示例把余额(负值记为零)作为敞口,并对所有客户使用 45% 的违约损失率; LGD 与 EAD 由违约贷款的清收估计 LGD:

>>> exposure = monitoring["balance"].clip(lower=0)
>>> by_grade = expected_loss_table(grades, mon_pd, 0.45, exposure)
>>> by_grade[["exposure", "expected_loss", "expected_loss_rate"]].round(
...     {"exposure": 0, "expected_loss": 0, "expected_loss_rate": 4}
... )
     exposure  expected_loss  expected_loss_rate
bin
A      2390.0           30.0              0.0125
B    440743.0        11065.0              0.0251
C    957512.0        46901.0              0.0490
D    769549.0        66399.0              0.0863
E    151415.0        31344.0              0.2070

等级 E 只占敞口的 6.5%,却占 155,740 预期损失的 20.1%;等级 D 和 E 合计占敞口的 40%、预期损失的 63%。

稳定性报告#

把监控样本中的每个变量与其开发样本分布比较。status 列采用 群体稳定性指标 中的 PSI 经验口径。

>>> report = pd.DataFrame({
...     "iv": {column: tables[column]["iv"].sum() for column in dev_groups},
...     "psi": {column: psi_table(dev_groups[column], mon_groups[column])["psi"].sum()
...             for column in dev_groups},
... })
>>> report["status"] = pd.cut(report["psi"], [-np.inf, 0.1, 0.25, np.inf],
...                           labels=["stable", "watch", "shift"])
>>> from kivi.stability import csi_table
>>> report["csi"] = pd.Series({
...     column: csi_table(dev_groups[column], mon_groups[column], card.loc[[column]])["csi"].sum()
...     for column in selected
... })
>>> report.sort_values("iv", ascending=False).round(3)
             iv    psi  status    csi
poutcome  0.423  0.003  stable -0.336
pdays     0.360  0.005  stable -0.074
contact   0.215  0.008  stable  0.315
job       0.118  0.001  stable  0.123
balance   0.115  0.000  stable -0.145
housing   0.108  0.000  stable -0.035
age       0.061  0.005  stable    NaN

这里所有变量都是稳定的,监控数据与开发数据来自同一客群时理应如此。 job 的 IV 是其三个组的 IV,即 0.118,略低于筛选时其 12 个标签的 0.137。 csi 列用各组的分值对其占比变化加权,因此等于该变量平均分值的变化; age 不在评分卡中,所以没有 CSI。对评分卡的所有变量求和,CSI 等于平均分的变化:

>>> shift = mon_score.mean() - dev_score.mean()
>>> print(f"sum of csi = {report['csi'].sum():.3f}, score shift = {shift:.3f}")
sum of csi = -0.151, score shift = -0.151

分数本身也按同样的方式监控,使用在开发样本分数上拟合的分段:

>>> score_edges = bin_edges(dev_score, bins=5).round(1)
>>> score_psi = psi_table(pd.cut(dev_score, score_edges), pd.cut(mon_score, score_edges))
>>> print(f"score PSI = {score_psi['psi'].sum():.4f}")
score PSI = 0.0020

群体稳定性指标 展示了分布偏移的样子。在生产环境中, monitoring_table() 对每一期重复计算这一 PSI,并给出已知结果和 Gini, stability_table() 给出每个变量的 PSI;见 模型监控 。主标尺的 PD 还决定了 监管资本 所计算的监管资本。已批准的贷款入账后, Vintage 与滚动率分析 跟踪其逾期情况, 存续期 PD 与预期信用损失 再把它转换为 PD 期限结构和 IFRS 9 损失准备。