max_fpr代码审查:标准化部分ROC-AUC为什么不等于裁剪面积除以宽度
配图为AI生成概念示意图,曲线不对应本文样本或真实模型测试结果。
在告警排序或垃圾内容过滤中,我们可能只关心低误报区间。让AI把完整ROC-AUC改成部分AUC,它常会先裁剪曲线,再把面积除以区间宽度。这个数有明确含义,却不等于scikit-learn的roc_auc_score(max_fpr=...)返回值。审查关键在于标准化基准。
max_fpr控制的是评估横轴上限,不是预测概率阈值。m=1/4表示考察负例被误报比例不超过四分之一的区间,不能改写成把预测分数超过0.25的样本判为正类。输入也可以是未校准的决策分数,但分数增大的方向应对应正类。
先区分三个量
设m=max_fpr,A是ROC曲线在假正例率0到m之间的面积。A/m是这个区间内的平均真正例率。scikit-learn 1.8文档明确说接口返回的是标准化部分AUC,而1.8.0版本源码使用McClish校正:
S=1/2×[1+(A−m²/2)/(m−m²/2)]。
其中m²/2是对角线TPR=FPR在该区间的面积,m是完美曲线的面积。校正把对角线基准映射到0.5,把完美结果映射到1。单纯除以m时,对角线的值却是m/2,会随区间宽度变化。这里说的是对角线基准,有限样本中的随机打分结果不必恰好等于0.5。
四个样本手算到分数
取标签[1,1,0,0]、分数[0.9,0.8,0.8,0.1]。ROC关键点依次为(0,0)、(0,1/2)、(1/2,1)、(1,1)。令m=1/4,截断点落在斜线段内部,线性插值得到TPR=3/4。
原始部分面积A=(1/4)×(1/2+3/4)/2=5/32;除宽结果是5/8。代入标准化公式,对角线面积为1/32、完美面积为8/32,因此S=1/2×[1+4/7]=11/14。三个数分别约为0.15625、0.625和0.785714,不能混用名称。
源码会补入截断点再积分。若只保留FPR不超过m的原有点,本例只剩FPR为零的点,便会把整个有效区间漏掉。ROC曲线接口提供经验点;部分AUC的截断插值由评分过程完成。
可运行的版本锁定核对
例子锁定scikit-learn 1.8.0和NumPy 2.3.5,用Fraction精确积分,再核对官方结果。保存为test.py运行,依赖安装命令见代码首行。
"""Reproduce with: pip install scikit-learn==1.8.0 numpy==2.3.5"""
from fractions import Fraction as F
import warnings
import numpy as np
import sklearn
from sklearn.exceptions import UndefinedMetricWarning
from sklearn.metrics import roc_auc_score, roc_curve
assert sklearn.__version__ == "1.8.0", "This audit pins scikit-learn 1.8.0"
def clipped_area(points, limit):
"""Exact integration of a piecewise-linear ROC, including the cut point."""
area = F(0)
for (x0, y0), (x1, y1) in zip(points, points[1:]):
if x1 == x0:
continue # Vertical segments have zero area.
if x0 >= limit:
break
right = min(x1, limit)
y_right = y0 + (y1 - y0) * (right - x0) / (x1 - x0)
area += (right - x0) * (y0 + y_right) / 2
return area
def mcclish(area, limit):
diagonal_area = limit * limit / 2
return (1 + (area - diagonal_area) / (limit - diagonal_area)) / 2
y = np.array([1, 1, 0, 0])
scores = np.array([0.9, 0.8, 0.8, 0.1])
limit = F(1, 4)
points = [(F(0), F(0)), (F(0), F(1, 2)),
(F(1, 2), F(1)), (F(1), F(1))]
fpr, tpr, _ = roc_curve(y, scores, drop_intermediate=False)
assert np.allclose(fpr, [float(p[0]) for p in points])
assert np.allclose(tpr, [float(p[1]) for p in points])
cut_tpr = F(1, 2) + (F(1) - F(1, 2)) * limit / F(1, 2)
assert cut_tpr == F(3, 4)
area = clipped_area(points, limit)
normalized = area / limit
standardized = mcclish(area, limit)
actual = roc_auc_score(y, scores, max_fpr=float(limit))
assert area == F(5, 32)
assert normalized == F(5, 8)
assert standardized == F(11, 14)
assert np.isclose(actual, float(standardized))
assert not np.isclose(actual, float(normalized))
assert np.isclose(roc_auc_score(y, scores, max_fpr=1), float(F(7, 8)))
assert roc_auc_score(y, scores, max_fpr=1) == roc_auc_score(y, scores)
print(f"NumPy={np.__version__}, scikit-learn={sklearn.__version__}")
print(f"max_fpr={limit}; interpolated_TPR={cut_tpr}")
print(f"raw_partial_area={area} ({float(area):.6f})")
print(f"area_divided_by_width={normalized} ({float(normalized):.6f})")
print(f"standardized_partial_AUC={standardized} ({actual:.6f})")
for name, values, expected in [
("perfect", [0.9, 0.8, 0.2, 0.1], F(1)),
("diagonal_all_tied", [0.5, 0.5, 0.5, 0.5], F(1, 2)),
("reversed", [0.1, 0.2, 0.8, 0.9], F(3, 7)),
]:
result = roc_auc_score(y, values, max_fpr=float(limit))
assert np.isclose(result, float(expected))
print(f"{name}={expected} ({result:.6f})")
for cutoff in [F(1, 10), F(1, 4), F(1, 2), F(1)]:
expected = mcclish(clipped_area(points, cutoff), cutoff)
assert np.isclose(roc_auc_score(y, scores, max_fpr=float(cutoff)),
float(expected))
for bad_limit in [0.0, 1.01]:
try:
roc_auc_score(y, scores, max_fpr=bad_limit)
except ValueError:
pass
else:
raise AssertionError("Invalid max_fpr was accepted")
try:
roc_auc_score([0, 1, 2], np.eye(3), multi_class="ovr", max_fpr=0.25)
except ValueError as exc:
assert "Partial AUC" in str(exc)
else:
raise AssertionError("Multiclass partial AUC was unexpectedly accepted")
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
result = roc_auc_score([1, 1], [0.2, 0.8], max_fpr=0.25)
assert np.isnan(result)
assert any(issubclass(w.category, UndefinedMetricWarning) for w in caught)
print("Exact area, normalization, boundaries and multiclass checks: PASS")实际输出
NumPy=2.3.5, scikit-learn=1.8.0 max_fpr=1/4; interpolated_TPR=3/4 raw_partial_area=5/32 (0.156250) area_divided_by_width=5/8 (0.625000) standardized_partial_AUC=11/14 (0.785714) perfect=1 (1.000000) diagonal_all_tied=1/2 (0.500000) reversed=3/7 (0.428571) Exact area, normalization, boundaries and multiclass checks: PASS
边界比小数位更重要
完全反向排序在m=1/4时得到3/7,而不是零。因为A最低为零,此时公式给出S=(1−m)/(2−m)。因此不能把这个标准化分数理解为从零起算的正确率。
有效范围为0<m≤1;m=1退化为完整ROC-AUC。锁定版本中,直接多分类调用只允许max_fpr为None或1,即便指定ovr也不能传入较小上限。二分类评估若只有一种真实标签,结果未定义,库会告警并返回NaN;示例对这些行为逐项断言。
比较两个模型时,应使用相同测试数据、样本权重和上限。统一了对角线基准,并不意味着不同上限的成绩已经在回答同一个问题。评估报告最好同时记录库版本、上限、负例数量以及是否采用标准化,避免只留下一个名为partial_auc的小数。
低误报区间应按业务需求事先选定,不宜看完测试结果再挑最好看的m。负例很少时,经验FPR格点很稀,插值点不代表某个确定阈值能精确达到该误报率。这个分数汇总一段区间的排序表现,部署时仍需检查实际阈值、误报数量和漏报代价。


