P6MediumPart P · MLE 生产工程与数据校准算子

广告概率校准 Platt Scaling 与预期校准误差 ECE 算子

⚡闪卡盲测➔

手写概率校准指标 ECE(Expected Calibration Error)及单调保序 Platt Scaling(NLL 梯度拟合参数 a, b),修正负采样导致的高估。

⏱️ 时间复杂度: O(S * N)
💾 空间复杂度: O(N)
🎯 免登录实战自测闭环(先做再看答案)
按「机制回忆 → 关键行填空 → 边界反例 → 追问与错题记录」顺序自测,进度自动保存在本地。
Step 1 · 机制口述与数值稳定性自检
Step 2 · 核心代码关键行补全
import numpy as np
def expected_calibration_error(probs: np.ndarray, labels: np.ndarray, n_bins: int = 10) -> float:
bins =
ece = 0.0
n = len(probs)
for i in range(n_bins):
if i == n_bins - 1:
mask = (probs >= bins[i]) & (probs <= bins[i + 1])
else:
mask = (probs >= bins[i]) & (probs < bins[i + 1])
cnt = int(np.sum(mask))
if cnt > 0:
acc = float(np.mean(labels[mask]))
conf = float(np.mean(probs[mask]))
ece += (cnt / n) * abs(acc - conf)
return float(ece)
def fit_platt_scaling(logits: np.ndarray, labels: np.ndarray, lr: float = 0.1, steps: int = 300) -> tuple[float, float]:
a, b = 1.0, 0.0
for _ in range(steps):
z = np.clip(a * logits + b, -30.0, 30.0)
p = 1.0 / (1.0 + np.exp(-z))
err =
a -= lr * float(np.mean(err * logits))
b -= lr * float(np.mean(err))
return a, b
Step 3 · 反例与边界断言核对
Step 4 · 面试追问盲答与错题记录
Q1: 如果在训练 CTR 模型时为了加快收敛做了 1:10 负样本降采样(Negative Downsampling),公式如何还原真实概率?
Q2: 什么时候 Isotonic Regression(保序回归)优于 Platt Scaling?
下一题: GPU Roofline 计算强度与 Ridge Point 瓶颈诊断器 →
💡

实战一句话记忆口诀

排序看 AUC,出价必须看 ECE 校准;留出集拟合 ax+b 拉回真概率

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

$$\hat{p} = \sigma(a \cdot z + b),\quad \text{ECE} = \sum_{m=1}^{M} \frac{|B_m|}{n} |\text{acc}(B_m) - \text{conf}(B_m)|$$
广告竞价计算 eCPM=pCTR×Bid\text{eCPM} = \text{pCTR} \times \text{Bid},因此即使排序 AUC 为 0.85,如果预测概率整体虚高都会导致广告主出价严重亏损。Platt Scaling 在验证集上用交叉熵拟合 σ(az+b)\sigma(az+b) 两个自由度,而负采样还原需要偏置项偏移 b−=ln⁡(sample_rate)b \mathrel{-}= \ln(\text{sample\_rate})。

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

logits: (N,), labels: (N,) -> NLL gradient steps -> scalar (a, b) & ECE

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

  • Platt Scaling 必须在独立留出验证集(OOT/Calibration Split)上拟合,不能使用训练集以防过拟合加剧
  • 最后一桶边界须包含 1.0(closed interval),防止概率恰好等于 1.0 的样本丢失
  • 裁剪 a*logits+b 防 exp 溢出

💻 完整参考代码实现

import numpy as np

def expected_calibration_error(probs: np.ndarray, labels: np.ndarray, n_bins: int = 10) -> float:
    bins = np.linspace(0.0, 1.0, n_bins + 1)
    ece = 0.0
    n = len(probs)
    for i in range(n_bins):
        if i == n_bins - 1:
            mask = (probs >= bins[i]) & (probs <= bins[i + 1])
        else:
            mask = (probs >= bins[i]) & (probs < bins[i + 1])
        cnt = int(np.sum(mask))
        if cnt > 0:
            acc = float(np.mean(labels[mask]))
            conf = float(np.mean(probs[mask]))
            ece += (cnt / n) * abs(acc - conf)
    return float(ece)

def fit_platt_scaling(logits: np.ndarray, labels: np.ndarray, lr: float = 0.1, steps: int = 300) -> tuple[float, float]:
    a, b = 1.0, 0.0
    for _ in range(steps):
        z = np.clip(a * logits + b, -30.0, 30.0)
        p = 1.0 / (1.0 + np.exp(-z))
        err = p - labels
        a -= lr * float(np.mean(err * logits))
        b -= lr * float(np.mean(err))
    return a, b

🧪 本地测试与正确性断言

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

rng = np.random.default_rng(10)
logits = rng.normal(0, 2.0, 2000)
true_p = 1.0 / (1.0 + np.exp(-(0.5 * logits - 0.8)))
y = (rng.random(2000) < true_p).astype(np.float64)
uncal_p = 1.0 / (1.0 + np.exp(-logits))
ece_before = expected_calibration_error(uncal_p, y)
a, b = fit_platt_scaling(logits, y, lr=0.2, steps=400)
cal_p = 1.0 / (1.0 + np.exp(-(a * logits + b)))
ece_after = expected_calibration_error(cal_p, y)
assert ece_after < 0.03 and ece_after < ece_before * 0.25
print('P6 PASS')

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

Q1:如果在训练 CTR 模型时为了加快收敛做了 1:10 负样本降采样(Negative Downsampling),公式如何还原真实概率?
逻辑回归对数几率满足 logitreal=logitsample+ln⁡(r)\text{logit}_{\text{real}} = \text{logit}_{\text{sample}} + \ln(r)(其中 rr 为负样本保留率),或者把采样因子等价看作给模型加了一个常偏置截距校正。
Q2:什么时候 Isotonic Regression(保序回归)优于 Platt Scaling?
当未校准曲线呈非 S 型畸变(如 GBDT 或某些过自信深度网络的极端双峰偏置)且验证集样本足够多(>10k)时,非参数的保序阶梯函数贴合更准;小样本则容易过拟合。
⚡
想检验本题的肌肉记忆?进入 3 阶闪卡主动回忆盲测
隐藏答案遮罩,自测:审题锚点 ➔ 数理公式机理 ➔ 工业标杆代码与连环追问。3 分钟攻破认知盲区!
🎯 立即在闪卡中盲测此题➔
← 上一题: Thompson Sampling 贝塔后验采样探索(冷启动与动态流量分配)返回 Part P 与全部 105 题下一题: GPU Roofline 计算强度与 Ridge Point 瓶颈诊断器 →