在 Kaggle 信用卡欺诈比赛中构建代价敏感 Stacking
解读
Kaggle 信用卡欺诈检测是典型的极端类别不平衡+代价敏感场景:正类(欺诈)占比通常低于 0.2%,但漏检成本是误检的 50~100 倍。面试官问“代价敏感 Stacking”,不是让你背调参技巧,而是考察三件事:
- 能否把业务代价量化到模型目标函数;
- 能否用 Scikit-learn 的 API 无缝拼装分层采样、阈值移动、代价敏感学习、异构基模型、元模型调参;
- 能否在单台 8 核 16 G 笔记本上 30 min 内跑通 5 折交叉验证,并给出可解释的结果。
国内面试常追问:“如果银行风控部要求 Recall≥85%,同时 False Positive Cost≤0.3 元/样本,你怎么用开源工具落地?”答不出代价函数与阈值决策联动,基本会被判“只会调包”。
知识点
- 代价敏感学习三件套:
- 类权重
class_weight='balanced'或自定义compute_class_weight; - 阈值移动
sklearn.metrics.precision_recall_curve+cost_matrix决策; - 采样+集成
imblearn.pipeline.Pipeline与sklearn.ensemble.StackingClassifier混用。
- 类权重
- Stacking 的 Scikit-learn 原生实现:
- 基模型列表需设置
passthrough=False避免信息泄漏; - 元模型必须用不同折的 out-of-fold 预测做训练,Scikit-learn 0.24+ 已内置
cv参数; - 结合
CalibratedClassifierCV保证元模型输入概率单调、可解释。
- 基模型列表需设置
- 交叉验证与度量:
- 必须采用分层时序交叉验证
StratifiedKFold(shuffle=False),防止未来信息泄漏; - 自定义
make_scorer把金融代价写进cost_matrix=[[0, 1], [50, 0]],用average_cost作为早停指标。
- 必须采用分层时序交叉验证
- 大数据技巧:
- 用
sklearn.config_context(assume_finite=True, working_memory=2048)加速; - 基模型中
HistGradientBoostingClassifier支持sample_weight与缺失值,内存占用 < LightGBM,过安检机无外部依赖。
- 用
- 合规与可解释:
- 输出
sklearn.inspection.permutation_importance供审计; - 用
sklearn.metrics.det_curve给出监管最爱的 Detection Cost Function (DCF) 曲线。
- 输出
答案
步骤级代码与解释(可直接在 Jupyter 单机复现):
from sklearn.datasets import fetch_openml
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.metrics import make_scorer
from sklearn.ensemble import StackingClassifier, HistGradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.calibration import CalibratedClassifierCV
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.utils.class_weight import compute_class_weight
import numpy as np
# 1. 加载数据并构造代价矩阵
X, y = fetch_openml(name='credit-card-fraud', version=1, as_frame=False, return_X_y=True)
cost_matrix = np.array([[0, 1], [50, 0]]) # 假正代价 1,假负代价 50
# 2. 自定义代价评价函数
def cost_sensitive_score(y_true, y_prob, cost_mat=cost_matrix):
# 先找最优阈值使得总期望代价最小
precision, recall, thresholds = precision_recall_curve(y_true, y_prob)
fpr = 1 - precision
fnr = 1 - recall
total_cost = fpr * cost_mat[0,1] + fnr * cost_mat[1,0]
best_thresh = thresholds[np.argmin(total_cost)]
y_pred = (y_prob >= best_thresh).astype(int)
# 返回平均代价
return np.mean((y_pred != y_true) *
np.where(y_true == 1, cost_mat[1,0], cost_mat[0,1]))
cost_scorer = make_scorer(cost_sensitive_score, needs_proba=True, greater_is_better=False)
# 3. 基模型:代价敏感直方图梯度提升 + 轻量逻辑回归
hgbc = HistGradientBoostingClassifier(
class_weight='balanced',
max_iter=300,
early_stopping=True,
n_iter_no_change=20,
random_state=42)
logi = LogisticRegression(
class_weight='balanced',
max_iter=1000,
n_jobs=-1,
random_state=42)
# 4. 元模型:用校准后的逻辑回归,防止过拟合
meta = CalibratedClassifierCV(
LogisticRegression(class_weight='balanced', max_iter=2000),
method='isotonic',
cv=3)
# 5. Stacking 流水线
stack = StackingClassifier(
estimators=[('hgbt', hgbc), ('lr', logi)],
final_estimator=meta,
cv=StratifiedKFold(n_splits=5, shuffle=False),
n_jobs=-1,
passthrough=False)
pipe = Pipeline(steps=[('scaler', StandardScaler(with_mean=False)),
('model', stack)])
# 6. 交叉验证
cv = StratifiedKFold(n_splits=5, shuffle=False)
score = cross_val_score(pipe, X, y, scoring=cost_scorer, cv=cv, n_jobs=-1)
print("平均代价:", -score.mean()) # 越低越好
关键回答话术:
“我把业务代价矩阵写进自定义评价函数,用 StackingClassifier 的 cv 参数保证每一折基模型输出 out-of-fold 概率,避免信息泄漏;元模型再经过 CalibratedClassifierCV 校准,确保概率单调且可解释。整个流程纯 Scikit-learn 原生 API,无需外部库即可通过银行审计。”
拓展思考
- 阈值决策在线更新:生产环境每日新增样本,可用
sklearn.linear_model.SGDClassifier(loss='log', class_weight='balanced')做增量训练,再滚动更新阈值,使 DCF 持续最优。 - AutoML 级联:在
StackingClassifier外层包sklearn.model_selection.HalvingGridSearchCV,搜索空间只调HistGradientBoostingClassifier的max_leaf_nodes与learning_rate,可在 15 min 内找到帕累托前沿。 - 联邦学习合规:若数据分散在多家银行,可用
sklearn.ensemble.VotingClassifier先本地训练,再共享模型参数而非样本,满足《个人金融信息保护技术规范》JR/T 0171—2020。 - GPU 加速替代:当样本量 >5 千万,Scikit-learn 的
HistGradientBoostingClassifier仍单机内存映射,但可用cuml.experimental.HistGradientBoostingClassifier做零代码迁移,面试可提“Scikit-learn API 兼容”作为亮点。