Average Precision与梯形PR-AUC:同一组预测,为什么算出不同分数
配图:AI生成概念示意图。阶梯与梯形仅表达两种计算方式,不是数据曲线,也不表示两者数值相等。
审查AI生成的分类评估代码时,看到“PR-AUC”还不够:它调用的是average_precision_score,还是把精确率召回率曲线交给梯形积分?两者使用同一组预测分数,也可能得到不同结果。对稀少正例任务,报告指标名称、计算方法和正类定义,才能让实验可比较。
差别来自相邻阈值之间怎么算
scikit-learn的AP文档把Average Precision定义为精确率的加权和,权重是召回率的增量,不做线性插值。按召回率递增排列,可写成AP=ΣΔR×P,其中P取本次纳入样本后的精确率。梯形积分则在相邻点间连直线,用两端精确率的平均值乘以ΔR。
这也说明AP不是对所有阈值的精确率简单求平均。某次降低阈值只纳入负例、召回率没有增加,该段对AP的权重就是零;但它可能改变后续区间的精确率。
并列分数必须整体处理
取标签[1,0,1,0]、分数[0.9,0.8,0.8,0.1]。阈值从0.9降到0.8时,两个同分样本同时进入预测正类集合,不能凭数组顺序拆出两个可实现阈值。对应召回率从1/2增至1,精确率从1降至2/3。
因此AP=1/2×1+1/2×2/3=5/6;梯形面积为1/2×1+1/2×(1+2/3)/2=11/12。分数并没有变化,差别来自计算定义。代码用Fraction保留精确分数,并检查交换同分样本的位置不会改变AP。
输入应是面向正类的连续或离散分数,而不是先用0.5切出的硬标签。硬标签会丢失可用于扫描阈值的排序信息。对于量化模型产生的大量并列分数,也不应为了得到更好看的面积随意添加微小噪声,因为那会改变排序与评估规则。
方向与末端点也要检查
precision_recall_curve文档规定阈值递增、召回率递减。默认正类为1时,首点对应全部预测为正,精确率等于正例占比;末点为精确率1、召回率0,没有对应阈值。因此曲线数组比阈值数组多一个元素,不能因为末点没有阈值就直接删掉。
sklearn.metrics.auc接受递增或递减横坐标;NumPy的trapezoid保留积分方向,直接传入递减召回率会得到负值。需要反转时应同步反转两列,不能分别排序。
完整可运行核对
保存为test.py,使用NumPy 2.0及以上、scikit-learn 1.3及以上版本运行。例子是无权重二分类数据,保留全部阈值。
"""Exact AP/PR area. Requires NumPy >= 2.0, scikit-learn >= 1.3."""
from fractions import Fraction as F
import numpy as np
import sklearn
from sklearn.metrics import average_precision_score, precision_recall_curve, auc
def exact_grouped_curve(y, scores):
# Ascending recall: empty prediction first, then whole score-tie groups.
precision, recall = [F(1)], [F(0)]
positives = int(np.sum(y))
if positives == 0:
raise ValueError("This example requires at least one positive")
for threshold in sorted(set(scores), reverse=True):
predicted = scores >= threshold
tp = int(np.sum(y[predicted]))
precision.append(F(tp, int(np.sum(predicted))))
recall.append(F(tp, positives))
ap = sum((recall[i] - recall[i - 1]) * precision[i]
for i in range(1, len(recall)))
trap = sum((recall[i] - recall[i - 1])
* (precision[i] + precision[i - 1]) / 2
for i in range(1, len(recall)))
return precision, recall, ap, trap
scores = np.array([0.9, 0.8, 0.8, 0.1])
cases = [
("positive_first", np.array([1, 0, 1, 0]), F(5, 6), F(11, 12)),
("negative_first", np.array([0, 1, 1, 0]), F(2, 3), F(1, 3)),
]
print(f"NumPy={np.__version__}, scikit-learn={sklearn.__version__}")
for name, y, expected_ap, expected_trap in cases:
p, r, thresholds = precision_recall_curve(
y, scores, drop_intermediate=False)
mp, mr, exact_ap, exact_trap = exact_grouped_curve(y, scores)
ap = average_precision_score(y, scores)
trap = auc(r, p) # sklearn accepts monotonically decreasing x.
ap_from_curve = -np.sum(np.diff(r) * p[:-1])
assert len(p) == len(r) == len(thresholds) + 1
assert len(thresholds) == len(np.unique(scores))
assert p[0] == y.mean() and r[0] == 1.0
assert (p[-1], r[-1]) == (1.0, 0.0)
assert np.all(np.diff(r) <= 0)
assert np.allclose(p, [float(v) for v in mp[::-1]])
assert np.allclose(r, [float(v) for v in mr[::-1]])
assert exact_ap == expected_ap and exact_trap == expected_trap
assert np.isclose(ap, float(exact_ap))
assert np.isclose(trap, float(exact_trap))
assert np.isclose(ap, ap_from_curve)
assert np.isclose(np.trapezoid(p, r), -trap)
# Reordering samples within the same score group cannot change AP.
perm = np.array([0, 2, 1, 3])
assert np.isclose(average_precision_score(y[perm], scores[perm]), ap)
print(f"\n{name}")
print("thresholds=", thresholds.tolist())
print("precision=", np.round(p, 6).tolist())
print("recall=", np.round(r, 6).tolist())
print(f"AP={exact_ap} ({ap:.6f}); trapezoidal_PR_AUC={exact_trap} ({trap:.6f})")
print(f"numpy_signed_area={np.trapezoid(p, r):.6f}")
print("\nExact fractions, score ties, endpoints and direction checks: PASS")实跑输出与评估含义
本地NumPy 2.3.5、scikit-learn 1.8.0结果:
NumPy=2.3.5, scikit-learn=1.8.0 positive_first thresholds= [0.1, 0.8, 0.9] precision= [0.5, 0.666667, 1.0, 1.0] recall= [1.0, 1.0, 0.5, 0.0] AP=5/6 (0.833333); trapezoidal_PR_AUC=11/12 (0.916667) numpy_signed_area=-0.916667 negative_first thresholds= [0.1, 0.8, 0.9] precision= [0.5, 0.666667, 0.0, 1.0] recall= [1.0, 1.0, 0.0, 0.0] AP=2/3 (0.666667); trapezoidal_PR_AUC=1/3 (0.333333) numpy_signed_area=-0.333333 Exact fractions, score ties, endpoints and direction checks: PASS
第二例把标签改为[0,1,1,0],AP为2/3,梯形面积却只有1/3。可见“梯形积分总比AP大”并不成立;精确率可能升降,差异方向取决于曲线形状。公式不同本身也不是程序故障。
比较模型时应固定同一评估集、正类和指标定义,多分类还要声明平均方式。AP汇总多个阈值的表现,不能代替某个上线阈值下的精确率、召回率和业务代价;它也不直接衡量预测概率是否校准。这几个小断言适合加入评估脚本,防止AI把不同计算口径悄悄替换成同一个名字。


