Top-k准确率的并列规则:高列索引优先与labels对齐
配图为AI生成概念示意图,柱形不代表真实模型测试数据。
让AI生成Top-k评估代码时,不能只检查矩阵维度。量化输出、初始模型或分数取整都可能产生并列;分数列与类别的对应关系也可能在导出时丢失。这些细节会直接改变命中结果,即使函数正常返回一个小数。
并列时有确定规则
本文锁定scikit-learn 1.8.0,讨论多分类、每个样本只有一个真实标签的场景。Top-k准确率统计真实类别是否进入分数最高的k个候选。官方文档指出,并列时较高索引的类别优先。这里的索引指分数矩阵中的列位置,不代表类别出现得更频繁,也不是随机抽签。
若列依次为A、B、C、D,四个分数都为0.25,前两个候选就是D和C。真实标签为[A,A,A,B,C,D]时,只有两行命中,Top-2为2/6。由于测试类别比例不同,这个确定性结果不必等于随机选两个类别时的基准2/4。
Top-1也可能不同于argmax
同一批全同分数据,Top-1总选D,得分1/6;NumPy的argmax遇到多个最大值时返回第一个位置,于是总选A,准确率3/6。两者差异来自并列决策,不能直接解释成评估函数算错了,也不能随意互换实现。
只在并列跨过第k名边界时,选择规则才会影响候选集合。评估应使用原始精度分数;不要先按展示位数四舍五入,制造原本不存在的并列。看起来接近也不等于数值相等,不能假设工具会自动采用自定义容差。
labels不是任意列顺序的通行证
分数列必须对应标签顺序。省略labels时,工具按真实标签的数值或字典序推断;测试子集缺少类别时,应显式传入完整类别集合。更容易忽视的是,1.8.0实现还要求labels唯一且有序,直接传入[C,A,D,B]会报错。
如果导出矩阵按[C,A,D,B]排列,应保留这份来源映射,再把列按[A,B,C,D]重新对齐。这里恢复的是原有类别语义,不能只改标签名称或随意交换列来提高得分。下面故意制造错配,再验证恢复映射后的结果。
完整可运行审查
保存为test.py,依赖锁定scikit-learn 1.8.0与NumPy 2.3.5,安装命令见代码首行。例子无需训练模型,直接核对评分机制。
"""Reproduce with: pip install scikit-learn==1.8.0 numpy==2.3.5"""
import warnings
import numpy as np
import sklearn
from sklearn.exceptions import UndefinedMetricWarning
from sklearn.metrics import accuracy_score, top_k_accuracy_score
assert sklearn.__version__ == "1.8.0", "This audit pins scikit-learn 1.8.0"
labels = np.array(["A", "B", "C", "D"])
y = np.array(["A", "A", "A", "B", "C", "D"])
scores = np.full((len(y), len(labels)), 0.25)
# Independent reconstruction: score first, then higher column index.
manual_top2 = np.array([
labels[sorted(range(len(labels)),
key=lambda j: (row[j], j), reverse=True)[:2]]
for row in scores
])
hits = np.any(manual_top2 == y[:, None], axis=1)
actual_top2 = top_k_accuracy_score(y, scores, k=2, labels=labels)
actual_top1 = top_k_accuracy_score(y, scores, k=1, labels=labels)
argmax_labels = labels[np.argmax(scores, axis=1)]
argmax_accuracy = accuracy_score(y, argmax_labels)
assert np.all(manual_top2 == np.array(["D", "C"]))
assert np.isclose(actual_top2, hits.mean())
assert np.isclose(actual_top2, 2 / 6)
assert np.isclose(actual_top1, 1 / 6)
assert np.isclose(argmax_accuracy, 3 / 6)
# An exported matrix comes with a different, documented column order.
y_all = labels.copy()
canonical_scores = 0.1 + 0.6 * np.eye(4)
permutation = np.array([2, 0, 3, 1])
source_order = labels[permutation]
exported_scores = canonical_scores[:, permutation]
# Deliberate mismatch: the values do not match the declared labels.
wrong = top_k_accuracy_score(y_all, exported_scores, k=1, labels=labels)
# Align columns by their original semantic names. Do not rename classes.
positions = [int(np.flatnonzero(source_order == name)[0]) for name in labels]
aligned = exported_scores[:, positions]
correct = top_k_accuracy_score(y_all, aligned, k=1, labels=labels)
assert np.array_equal(aligned, canonical_scores)
assert wrong == 0 and correct == 1
try:
top_k_accuracy_score(y_all, exported_scores, k=1, labels=source_order)
except ValueError as exc:
assert "must be ordered" in str(exc)
else:
raise AssertionError("Unordered labels were unexpectedly accepted")
# This test slice has only two observed classes, but still four score columns.
subset = np.array([0, 2])
assert top_k_accuracy_score(y_all[subset], aligned[subset],
k=1, labels=labels) == 1
try:
top_k_accuracy_score(y_all[subset], aligned[subset], k=1)
except ValueError:
pass
else:
raise AssertionError("Missing global labels were not detected")
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
assert top_k_accuracy_score(y, scores, k=4, labels=labels) == 1
assert any(issubclass(w.category, UndefinedMetricWarning) for w in caught)
print(f"NumPy={np.__version__}, scikit-learn={sklearn.__version__}")
print("all_tied_top2_labels=", manual_top2[0].tolist())
print(f"top2={actual_top2:.6f} (2/6)")
print(f"top1={actual_top1:.6f} (1/6)")
print(f"argmax_accuracy={argmax_accuracy:.6f} (3/6)")
print("exported_column_order=", source_order.tolist())
print(f"misaligned_top1={wrong:.6f}; aligned_top1={correct:.6f}")
print("Tie rule, column alignment, labels and k-boundary checks: PASS")实际输出
NumPy=2.3.5, scikit-learn=1.8.0 all_tied_top2_labels= ['D', 'C'] top2=0.333333 (2/6) top1=0.166667 (1/6) argmax_accuracy=0.500000 (3/6) exported_column_order= ['C', 'A', 'D', 'B'] misaligned_top1=0.000000; aligned_top1=1.000000 Tie rule, column alignment, labels and k-boundary checks: PASS
第二组数据本来每行都把真实类别排第一,导出列顺序却与声明标签不一致,错误评估得到零分。按来源列名恢复对应关系后,得分回到一。这里展示的是映射错误的后果,不是通过重新定义类别优化指标。
把边界写进评估约定
建议保存完整类别顺序、k、库版本、分数精度和并列处理规则,并记录有多少样本在入选边界处同分。比较模型时固定这些约定,不要根据测试结果挑选标签编号或加噪声拆分并列。
本函数不覆盖多标签任务,二分类一维分数分支也另有阈值逻辑,不能套用本文全部结论。k达到类别总数后所有类别都入选,函数会告警并给出满分,这不再有区分能力。Top-k只说明候选集合是否包含答案,还需结合实际候选展示成本和后续决策质量解释。


