文章目录
-
- [01 本篇要解决什么问题](#01 本篇要解决什么问题)
- [02 核心原理、公式与条件](#02 核心原理、公式与条件)
- [03 代码实验、实际结果与验证范围](#03 代码实验、实际结果与验证范围)
- [04 工程场景与排错思路](#04 工程场景与排错思路)
- [05 面试问答与追问](#05 面试问答与追问)
- [06 本篇回顾与练习](#06 本篇回顾与练习)
01 本篇要解决什么问题
Accuracy很高,为什么仍可能漏掉全部正样本?ROC-AUC高,为什么部署阈值还要单独选择?RAG检索里Recall@K和NDCG又分别回答什么?本篇把指标放回决策目标,并用手算实现与库函数交叉核对,避免只记缩写。
02 核心原理、公式与条件
(1)先区分预测、排序与决策
概率预测关注数值是否可信,排序关注好对象能否排前,类别决策关注给定阈值下做什么。一个模型可能排序不错却概率未校准,也可能整体Accuracy高但关键类别Recall很低。
评价前写清正类、观察单位、集合与分母。患者级、切片级和查询级不是同一口径;单一指标也不能同时代表质量、成本、延迟与不确定性。
(2)混淆矩阵把二分类说清楚
设正类为1,TP为正确报正,FP为误报正,FN为漏报正,TN为正确报负:
P = T P T P + F P , R = T P T P + F N , F 1 = 2 T P 2 T P + F P + F N , F P R = F P F P + T N . P=\frac{TP}{TP+FP},\quad R=\frac{TP}{TP+FN},\quad F_1=\frac{2TP}{2TP+FP+FN},\quad FPR=\frac{FP}{FP+TN}. P=TP+FPTP,R=TP+FNTP,F1=2TP+FP+FN2TP,FPR=FP+TNFP.
Precision回答报正里有多少正确,Recall回答实际正例找回多少;F1是两者调和平均,不包含TN。分母为0时必须说明策略,本篇手写函数对相应Precision、Recall、F1取0,并与库的zero_division=0核对。
95个负例、5个正例,全部预测负类可得95% Accuracy,但正类Recall为0。多类别Macro-F1先逐类算F1再平均,Weighted-F1按类别支持数加权,Micro-F1汇总计数;单标签、完整类别集合下Micro-F1常与Accuracy一致,不应扩成所有多标签情形。
(3)ROC与PR看的是不同坐标
ROC绘制TPR与FPR随阈值变化的轨迹;AUC可解释为随机正例得分高于随机负例的概率,平分计0.5。严格单调变换保留排序时AUC不变,但概率校准和固定阈值决策可能改变。
PR绘制Precision与Recall,受正类比例影响。若正类比例为 π \pi π,在相应条件下:
P r e c i s i o n = π T P R π T P R + ( 1 − π ) F P R . Precision=\frac{\pi\,TPR}{\pi\,TPR+(1-\pi)\,FPR}. Precision=πTPR+(1−π)FPRπTPR.
因此极少正例时,看似不大的FPR仍可能对应大量误报。ROC并非因此无用,PR也不是任何任务都天然更好;需要结合类比例、关注区域与实际代价选择,比较不同数据集的AP时尤其要交代基率。
(4)AP不等于任意一种PR面积
本篇AP按不同分数阈值分组,以Recall增量加权Precision: A P = ∑ j ( R j − R j − 1 ) P j AP=\sum_j(R_j-R_{j-1})P_j AP=∑j(Rj−Rj−1)Pj。相同分数必须作为一组处理,不能任意打散并列结果后只按正样本位置平均。
梯形积分会采用另一种插值方式,所以可能与AP不同。实验同时输出二者,并让手写分组AP与average_precision_score一致。论文或报告若只写"PR-AUC",应补充具体实现与并列处理。AP接口定义
(5)阈值要在开发数据上定
模型分数固定后,阈值在Precision、Recall与业务代价之间移动。本例预先列出0.3、0.5、0.7,只按验证F1选,若并列优先较高阈值,再冻结到另一组测试分数。
这只是十条验证分数上的教学选择,不是充分统计证据;不能因为某个阈值赢了就套到所有部署。训练类权重、概率校准或业务正类比例变化,都可能改变决策需要。测试集不能反复负责挑阈值。
(6)回归指标保留单位和基线
MAE是平均绝对误差,MSE平方误差对大残差更敏感,RMSE把MSE开方恢复目标单位。若目标单位整体乘10,MAE和RMSE乘10,MSE乘100,不能跨单位直接比较。
R 2 = 1 − ∑ i ( y i − y ^ i ) 2 ∑ i ( y i − y ˉ ) 2 . R^2=1-\frac{\sum_i(y_i-\hat y_i)^2}{\sum_i(y_i-\bar y)^2}. R2=1−∑i(yi−yˉ)2∑i(yi−y^i)2.
R²可以小于0,表示相对这一定义的基准更差;目标恒定时分母为0,库可能采用特定有限化策略,需要说明。部署基线预测不能偷偷用未来测试均值训练,公式中的评价参照与可部署基线是两回事。
(7)排序评价要明确相关性与截断
P@K数前K中相关项比例;Recall@K还需要已知相关项总数;MRR平均第一条相关结果的倒数排名;NDCG兼顾位置与分级相关性。若标注不完整,不能假装已经知道所有相关文档。
本例使用 g ( r e l ) = 2 r e l − 1 g(rel)=2^{rel}-1 g(rel)=2rel−1和 log 2 ( r a n k + 1 ) \log_2(rank+1) log2(rank+1)折扣,并与同增益口径的库函数比较。scikit-learn的ndcg_score直接使用传入相关值作增益,因此代码先传入 2 r e l − 1 2^{rel}-1 2rel−1,不能忽略这一约定。NDCG接口说明
无相关项查询在本例取0并计入均值;其他任务可能排除,报告应声明。MRR本例看完整五项列表而非截断到3,Recall与NDCG则按K=3;检索结果若重复返回同一文档,也应先明确去重规则。

03 代码实验、实际结果与验证范围
在完整解压目录运行python examples/lesson_05.py。保留同目录ml_common.py,安装随包requirements.txt;本批在CPU运行,不需下载外部数据。使用正常模式,不用会关闭assert的python -O。
python
import numpy as np
from sklearn.metrics import (accuracy_score, average_precision_score, f1_score, mean_absolute_error,
mean_squared_error, ndcg_score, precision_recall_curve,
precision_score, recall_score, roc_auc_score, roc_curve, r2_score)
from ml_common import output_dir, table, figure, finish, plt
def binary_counts(y, predicted):
y, predicted = np.asarray(y), np.asarray(predicted)
tp = int(np.sum((y == 1) & (predicted == 1)))
fp = int(np.sum((y == 0) & (predicted == 1)))
fn = int(np.sum((y == 1) & (predicted == 0)))
tn = int(np.sum((y == 0) & (predicted == 0)))
precision = tp / (tp + fp) if tp + fp else 0.0
recall = tp / (tp + fn) if tp + fn else 0.0
f1 = 2 * tp / (2 * tp + fp + fn) if 2 * tp + fp + fn else 0.0
return {'TP': tp, 'FP': fp, 'FN': fn, 'TN': tn, 'precision': precision, 'recall': recall, 'F1': f1}
def pairwise_auc(y, scores):
positive, negative = scores[y == 1], scores[y == 0]
if not len(positive) or not len(negative):
raise ValueError('ROC-AUC requires both classes')
difference = positive[:, None] - negative[None, :]
return np.mean((difference > 0) + 0.5 * (difference == 0))
def grouped_ap(y, scores):
if np.sum(y == 1) == 0:
return 0.0 # explicit convention for this teaching helper
total, previous_recall, answer = np.sum(y == 1), 0.0, 0.0
for threshold in np.unique(scores)[::-1]:
chosen = scores >= threshold
tp = np.sum(y[chosen] == 1)
recall = tp / total
answer += (recall - previous_recall) * tp / np.sum(chosen)
previous_recall = recall
return answer
def ranking_metrics(ordered_relevance, k):
rel = np.asarray(ordered_relevance, dtype=float)
top = rel[:k]
relevant = rel > 0
precision = np.sum(top > 0) / k
recall = np.sum(top > 0) / np.sum(relevant) if np.sum(relevant) else 0.0
positions = np.flatnonzero(relevant)
reciprocal_rank = 1 / (positions[0] + 1) if len(positions) else 0.0
def dcg(values):
return np.sum((2 ** values - 1) / np.log2(np.arange(len(values)) + 2))
ideal = dcg(np.sort(rel)[::-1][:k])
ndcg = dcg(top) / ideal if ideal else 0.0
return {'P_at_k': precision, 'Recall_at_k': recall, 'RR': reciprocal_rank, 'NDCG_at_k': ndcg}
def main():
out = output_dir(5)
y_valid = np.array([1, 0, 1, 0, 1, 0, 0, 0, 0, 0])
scores_valid = np.array([0.9, 0.8, 0.7, 0.6, 0.4, 0.4, 0.3, 0.2, 0.1, 0.05])
thresholds = [0.3, 0.5, 0.7]
results = []
for threshold in thresholds:
predicted = scores_valid >= threshold
row = {'threshold': threshold, **binary_counts(y_valid, predicted)}
assert np.isclose(row['precision'], precision_score(y_valid, predicted, zero_division=0))
assert np.isclose(row['recall'], recall_score(y_valid, predicted, zero_division=0))
assert np.isclose(row['F1'], f1_score(y_valid, predicted, zero_division=0))
results.append(row)
# Select by validation F1, ties prefer the higher threshold; freeze before test.
selected = max(results, key=lambda r: (r['F1'], r['threshold']))['threshold']
y_test = np.array([0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0])
scores_test = np.array([0.1, 0.8, 0.6, 0.2, 0.65, 0.4, 0.3, 0.7, 0.05, 0.2, 0.9, 0.1])
test_result = binary_counts(y_test, scores_test >= selected)
roc_auc = pairwise_auc(y_valid, scores_valid)
ap = grouped_ap(y_valid, scores_valid)
assert np.isclose(roc_auc, roc_auc_score(y_valid, scores_valid))
assert np.isclose(ap, average_precision_score(y_valid, scores_valid))
assert binary_counts([0, 1], [0, 0])['F1'] == 0
rare_y = np.array([0] * 95 + [1] * 5)
constant_accuracy = accuracy_score(rare_y, np.zeros(100))
regression_y, regression_p = np.array([1., 2., 3., 4.]), np.array([0., 2., 4., 6.])
residual = regression_p - regression_y
regression = {'MAE': np.mean(abs(residual)), 'MSE': np.mean(residual ** 2), 'RMSE': np.sqrt(np.mean(residual ** 2)),
'R2': 1 - np.sum(residual ** 2) / np.sum((regression_y - regression_y.mean()) ** 2)}
assert np.isclose(regression['MAE'], mean_absolute_error(regression_y, regression_p))
assert np.isclose(regression['MSE'], mean_squared_error(regression_y, regression_p))
assert np.isclose(regression['R2'], r2_score(regression_y, regression_p))
assert r2_score(regression_y, np.zeros(4)) < 0
rankings = [np.array([3, 0, 2, 1, 0]), np.array([0, 1, 0, 0, 1]), np.zeros(5)]
rank_results = [ranking_metrics(rel, 3) for rel in rankings]
# sklearn uses linear gains; pass 2^rel-1 to match the explicit graded-gain convention.
for rel, row in zip(rankings, rank_results):
assert np.isclose(row['NDCG_at_k'], ndcg_score([(2 ** rel - 1)], [np.arange(5, 0, -1)], k=3))
fpr, tpr, _ = roc_curve(y_valid, scores_valid)
precision, recall, _ = precision_recall_curve(y_valid, scores_valid)
trapezoid_pr_area = np.trapezoid(precision[::-1], recall[::-1])
table(out / 'validation_thresholds.csv', list(results[0]), [list(r.values()) for r in results])
table(out / 'classification_scores.csv', ['split', 'label', 'score'],
[('valid', y, p) for y, p in zip(y_valid, scores_valid)] + [('test', y, p) for y, p in zip(y_test, scores_test)])
table(out / 'regression_predictions.csv', ['y', 'prediction'], zip(regression_y, regression_p))
table(out / 'ranking_relevance.csv', ['query', 'rank', 'relevance'], [(i, j + 1, rel) for i, values in enumerate(rankings) for j, rel in enumerate(values)])
fig, axes = plt.subplots(1, 3, figsize=(12, 4), constrained_layout=True)
axes[0].plot(fpr, tpr, marker='o')
axes[0].plot([0, 1], [0, 1], '--', color='gray')
axes[0].set(xlabel='FPR', ylabel='TPR', title=f'Validation ROC; AUC={roc_auc:.3f}')
axes[1].step(recall, precision, where='post')
axes[1].axhline(y_valid.mean(), linestyle='--', color='gray')
axes[1].set(xlabel='Recall', ylabel='Precision', title=f'Validation PR; AP={ap:.3f}')
axes[2].plot(thresholds, [r['F1'] for r in results], 'o-')
axes[2].axvline(selected, linestyle='--', color='gray')
axes[2].set(xlabel='threshold', ylabel='F1', title='Validation threshold selection')
figure(fig, out)
finish(out, {'validation': {'threshold_results': results, 'ROC_AUC': roc_auc, 'AP': ap, 'trapezoid_PR_area': trapezoid_pr_area},
'frozen_threshold': selected, 'test_at_frozen_threshold': test_result,
'rare_class_baseline': {'accuracy': constant_accuracy, 'positive_recall': 0.0},
'regression': regression, 'ranking_k': 3, 'ranking_per_query': rank_results,
'mean_RR_including_zero_relevance_query': np.mean([r['RR'] for r in rank_results]),
'scope': 'hand-authored score arrays, not a trained production model; zero-relevant query contributes 0 by explicit convention'})
if __name__ == '__main__':
main()
二分类计数、Precision、Recall、F1与库函数核对;AUC用正负样本两两比较并处理同分,AP按阈值分组。回归公式与库实现比较,并检查R²可为负。三组排名含无相关项查询,按指数增益转换后核对NDCG;全部输入分数为手工构造,没有隐含训练模型。
本次真实运行结果
验证ROC-AUC=0.8333、AP=0.7222、梯形PR面积=0.6944,后两者口径不同。只按验证F1选出阈值0.7,冻结后测试Precision=0.6667、Recall=0.5000、F1=0.5714。95%负类的全负预测Accuracy=0.95但正类Recall=0;排序评价按明确增益和无相关项约定与库结果交叉核对。

图由随包原始数据与脚本生成,未平滑或补造数值;SVG与明细见实验结果目录。
结论的适用边界
| 口径 | 本篇约定 | 需要另外说明 |
|---|---|---|
| 二分类 | 正类1,零分母取0 | 临床或业务代价与不确定性 |
| 阈值 | 验证F1选择,测试冻结 | 小样本稳定性与部署校准 |
| AP | 同分分组,Recall增量加权 | 不能混称梯形PR面积 |
| NDCG | 指数增益、K=3 | 库默认增益可能不同 |
| MRR | 完整五项排名,无相关项计0 | 不是MRR@3或排除空查询 |
04 工程场景与排错思路
科研文献检索系统可以先看Recall@K能否把证据找回来,再看重排NDCG与最终回答引用是否正确。分类Accuracy不能替代检索召回,检索指标好也不自动证明生成答案忠实。
汇报时同时给样本量、类别支持数、阈值来源和关键错误类型;对于相关样本,应按独立来源设计不确定性估计。只报告一个很高的小数,而不交代分母和测试协议,很难支持工程选择。
05 面试问答与追问
问题1:Accuracy高为什么仍可能不能用?
类别极不平衡时,多数类预测可以很高,但关键少数类全部漏掉。还要看逐类Recall、Precision、支持数以及实际错误代价。
问题2:ROC-AUC与F1能互相替代吗?
不能。前者综合排序表现,后者依赖具体阈值与正类定义;排序好也需要合适决策,F1好也不保证概率校准。
问题3:AP就是梯形PR-AUC吗?
本篇和相应库接口的AP是Recall增量加权Precision,不等于一般梯形积分;同分、插值和空正类策略都需声明。
问题4:R²会小于0吗?
会,预测误差平方和大于按公式参照的总离差时即可为负。目标恒定还可能没有普通有限定义,应核对库的处理。
问题5:Macro-F1与Weighted-F1怎么选?
Macro更强调每类同等权重,Weighted按支持数加权可能更受多数类影响。选择由任务决定,最好保留逐类结果避免汇总掩盖问题。
问题6:NDCG为什么同一数据不同实现可能不一样?
增益函数、折扣、并列排序、截断K和无相关项策略可能不同。先对齐这些定义,再比较数值;本例显式转换指数增益。
06 本篇回顾与练习
指标是有条件的测量协议:目标、分母、阈值、并列、截断与无效情况都属于定义。先对齐口径,再比较数字,才能把模型表现与真实决策联系起来。
三道递进练习
| 练习 | 思路与验收重点 |
|---|---|
| 手算一个少数类混淆矩阵 | 同时给Accuracy、Precision、Recall、F1,并写清正类。 |
| 实现含同分的AP | 按不同阈值分组,与库结果比较,不随意拆并列。 |
| 比较两组检索排名 | 明确相关性、K、增益和空查询策略,再算MRR与NDCG。 |
练习表提供方向与验收提示,并非额外完整题解。合成实验用于讲清机制,不能直接推广为真实患者、行业数据或大模型的性能结论。