N3Medium★ 风控/MLOps 必考 · 漂移告警Part N · 数据特征管道与生产系统算子

生产特征分布漂移监测:PSI 稳定度指标计算

⚡闪卡盲测➔

基于训练集等频分箱边界计算线上真实流量相对于基线的 PSI(对称 KL 散度),触发模型重训与降级。

⏱️ 时间复杂度: O((N + M) log B)
💾 空间复杂度: O(B)
🎯 免登录实战自测闭环(先做再看答案)
按「机制回忆 → 关键行填空 → 边界反例 → 追问与错题记录」顺序自测,进度自动保存在本地。
Step 1 · 机制口述与数值稳定性自检
Step 2 · 核心代码关键行补全
import numpy as np
def compute_psi(expected: np.ndarray, actual: np.ndarray, num_bins: int = 10, eps: float = 1e-6) -> float:
"""
Compute Population Stability Index (PSI) between training baseline (expected) and
production distribution (actual) using baseline quantile buckets.
PSI < 0.1: stable; 0.1..0.25: moderate shift; >= 0.25: severe drift alert.
"""
exp = np.asarray(expected, dtype=np.float64)
act = np.asarray(actual, dtype=np.float64)
quantiles =
edges = np.percentile(exp, quantiles)
edges[0], edges[-1] = -np.inf, np.inf
exp_counts, _ = np.histogram(exp, bins=edges)
act_counts, _ = np.histogram(act, bins=edges)
p = np.clip(exp_counts / max(len(exp), 1), eps, None)
q = np.clip(act_counts / max(len(act), 1), eps, None)
p = p / p.sum()
q = q / q.sum()
return
Step 3 · 反例与边界断言核对
Step 4 · 面试追问盲答与错题记录
Q1: 线上单个高权重特征 PSI 突然飙升到 0.8,如何快速区分是「业务真实季节变化」还是「特征管道字段 Bug」?
下一题: Prefill / Decode 分离式推理调度仿真 (DistServe / Mooncake) →
💡

实战一句话记忆口诀

训练集定边界包正负无穷,空桶 eps 截断防对数炸,0.1 看观察 0.25 告警

📐 核心数学公式与机理推导

PSI=∑b=1B(pb−qb)ln⁡(pbqb)\text{PSI} = \sum_{b=1}^{B} (p_b - q_b) \ln\left(\frac{p_b}{q_b}\right)
### PSI 的数学本质:Jeffreys 散度(对称 KL)
在线上风控、推荐与模型路由中,真实标签往往滞后数周才回收。PSI (Population Stability Index) 用连续特征在训练基线上的分位数边界 e0,…,eBe_0,\dots,e_B 对线上新特征分桶:
PSI=∑b=1B(qb−pb)ln⁡qbpb=DKL(q∥p)+DKL(p∥q)\text{PSI} = \sum_{b=1}^B (q_b - p_b) \ln\frac{q_b}{p_b} = D_{\text{KL}}(q \parallel p) + D_{\text{KL}}(p \parallel q)
业界标准预警线:
- PSI<0.1\text{PSI} < 0.1:分布稳定;
- 0.1≤PSI<0.250.1 \le \text{PSI} < 0.25:轻度偏移,需排查上游管道;
- PSI≥0.25\text{PSI} \ge 0.25:显著漂移,立即触发特征异常排查或重训。

🔄 张量维度与形状流转说明

expected [N] -> 分位数切点 edges [B+1] -> histogram 频率 (p, q) [B] -> eps 截断归一化 -> scalar PSI

🛡️ 数值稳定性自检与边界要点

  • 分箱边界必须且只能由基线训练集等频分位数确定(首尾扩展为 −∞,+∞-\infty, +\infty 接住线上极端离群值)
  • 线上分桶命中率为 0 时必须加 eps 截断并重新归一化,否则 ln⁡(0)\ln(0) 直接产生 NaN / Inf
  • 离散高基数特征存在重复分位数边界时,生产实现需对重复边做去重或按 Top-K + Other 类别计算

💻 完整参考代码实现

import numpy as np

def compute_psi(expected: np.ndarray, actual: np.ndarray, num_bins: int = 10, eps: float = 1e-6) -> float:
    """
    Compute Population Stability Index (PSI) between training baseline (expected) and
    production distribution (actual) using baseline quantile buckets.
    PSI < 0.1: stable; 0.1..0.25: moderate shift; >= 0.25: severe drift alert.
    """
    exp = np.asarray(expected, dtype=np.float64)
    act = np.asarray(actual, dtype=np.float64)
    quantiles = np.linspace(0, 100, num_bins + 1)
    edges = np.percentile(exp, quantiles)
    edges[0], edges[-1] = -np.inf, np.inf
    exp_counts, _ = np.histogram(exp, bins=edges)
    act_counts, _ = np.histogram(act, bins=edges)
    p = np.clip(exp_counts / max(len(exp), 1), eps, None)
    q = np.clip(act_counts / max(len(act), 1), eps, None)
    p = p / p.sum()
    q = q / q.sum()
    return float(np.sum((q - p) * np.log(q / p)))

🧪 本地测试与正确性断言

可直接复制到本地 Python / Jupyter 验证:

import numpy as np
rng = np.random.default_rng(7)
base = rng.normal(0.0, 1.0, size=5000)
same_dist = rng.normal(0.0, 1.0, size=5000)
shifted_dist = rng.normal(1.2, 1.0, size=5000)
psi_ok = compute_psi(base, same_dist, num_bins=10)
psi_drift = compute_psi(base, shifted_dist, num_bins=10)
assert psi_ok < 0.05, f"Identical distribution PSI too high: {psi_ok}"
assert psi_drift > 0.25, f"Shifted distribution failed drift alert: {psi_drift}"
print("✓ PSI feature drift detector assertion passed")

🎯 核心工程追问与标准应答

Q1:线上单个高权重特征 PSI 突然飙升到 0.8,如何快速区分是「业务真实季节变化」还是「特征管道字段 Bug」?
同时核对空值率(Null Ratio)与 0 值占比跳变、检查该特征上下游链路(Feature Store TTL/Schema 变更)是否近期有发布,并查看该分箱外边界截断桶的样本占比是否突然异常集中在单桶。
⚡
想检验本题的肌肉记忆?进入 3 阶闪卡主动回忆盲测
隐藏答案遮罩,自测:审题锚点 ➔ 数理公式机理 ➔ 工业标杆代码与连环追问。3 分钟攻破认知盲区!
🎯 立即在闪卡中盲测此题➔
← 上一题: Feature Store 无穿越 Point-in-Time AS-OF 拼接返回 Part N 与全部 105 题下一题: Prefill / Decode 分离式推理调度仿真 (DistServe / Mooncake) →