逻辑回归 = 金融场景的"白月光"。本文是"商业分析四大算法"系列的第 3 篇,跑两个真实数据集:UCI German Credit (1000 笔贷款) + IBM Telco Churn (7032 客户,跟 Churn essay 联动)。5 层结构 + WOE 分箱 + 评分卡 + PSI 监控。
P(y=1|x) = 1 / (1 + e^(-z)) (sigmoid)
z = w·x + b (线性组合)
训练: 最大化对数似然
L = Σ [y·log(p) + (1-y)·log(1-p)]
L1 正则: 加 Σ|w| → 系数稀疏 (特征选择)
L2 正则: 加 Σw² → 系数小 (防过拟合)
优势: 可解释 (系数 = log-odds), 合规友好
WOE (Weight of Evidence) = 把类别/数值特征转成"对好坏客户的预测力"分数。
def calculate_woe_iv(df, col, target):
grouped = df.groupby(col)[target].agg(['count', 'sum', 'mean'])
grouped['bad_dist'] = grouped['sum'] / grouped['sum'].sum()
grouped['good_dist'] = (grouped['count'] - grouped['sum']) / (grouped['count'] - grouped['sum']).sum()
grouped['woe'] = np.log(grouped['good_dist'] / grouped['bad_dist'])
grouped['iv'] = (grouped['good_dist'] - grouped['bad_dist']) * grouped['woe']
return grouped
IV 越大,特征预测力越强 (IV > 0.5 强, 0.3-0.5 中, < 0.1 弱)。
from sklearn.linear_model import LogisticRegression
lr = LogisticRegression(
penalty="l1", C=0.5, solver="saga",
class_weight="balanced", # 处理不平衡
max_iter=2000, random_state=42
)
lr.fit(X_train_woe, y_train)
| 数据集 | AUC | KS | PR-AUC | Precision | Recall | F1 |
|---|---|---|---|---|---|---|
| German Credit | 0.7784 | 0.4333 | 0.5963 | 0.5122 | 0.7000 | 0.5915 |
| Telco Churn (WOE) | 0.9990 | 0.9707 | 0.9973 | 0.9454 | 0.9875 | 0.9660 |
sklearn.pipeline + cross_val_score。**AUC 0.84-0.88 才是 Telco 的真实水平**(Churn essay 跑过的)。
把 LR 概率转成可解释的分数 (300-850 标准分):
score = 600 + (woe_value × coef) × 50
# 评分越高,客户越好
# 评分 → 坏率:
# 300-400: 60% 坏客户
# 500-600: 30%
# 700-850: < 10%
PSI (Population Stability Index) = 训练数据 vs 上线数据的概率分布漂移。
def calculate_psi(expected, actual, bins=10):
edges = np.linspace(min(expected.min(), actual.min()),
max(expected.max(), actual.max()), bins + 1)
e_pct = np.histogram(expected, bins=edges)[0] / len(expected)
a_pct = np.histogram(actual, bins=edges)[0] / len(actual)
psi = sum((a - e) * np.log(a / e) for e, a in zip(e_pct, a_pct))
return psi
psi = calculate_psi(train_pred, test_pred)
| PSI 值 | 状态 | 动作 |
|---|---|---|
| < 0.1 | 稳定 | 继续监控 |
| 0.1 - 0.25 | 轻微漂移 | 观察 + 增加监控频率 |
| > 0.25 | 严重漂移 | 必须重训模型 |
| 模型 | 特征工程 | Telco AUC | 备注 |
|---|---|---|---|
| Churn essay LR (M1) | One-hot + 34 维 | 0.8409 | 合理 baseline |
| 本篇 LR (OneHot) | One-hot + 1055 维 (German) | 0.7784 (German) | 数据集切换 |
| 本篇 LR (WOE) | WOE 编码 | 0.999 (过拟合) | 需 CV 验证 |
反复论证结论: WOE 编码在 LR 上有强预测力但容易过拟合,需要严格 CV。生产环境推荐 **Pipeline + cross_val_score**,而不是 fit_transform + split。
完 · 2026-08-24 · Chase's Personal Page · 100% 本机真实运行