64. 使用平均并列排名计算 Spearman 秩相关系数
一个廉价的评判器(judge)对答案的排序方式是否与人类一致?Spearman 相关系数比较的是排名而非原始分数,因此它对不同的量纲具有鲁棒性。
编写 spearman(x, y) 函数,输入为两个长度相同的 1D 数组。将每个数组从 1 到 n 进行排名,并为并列的值分配它们所跨越排名的平均值。返回这两个排名数组的 Pearson 相关系数。如果其中任何一个排名数组是常数,则返回 0.0。
def spearman(x, y)示例 1
输入: spearman([1, 2, 2, 3], [10, 20, 20, 40])
输出: 1.0
示例 2
输入: x = [1, 2, 3, 4], y = [9, 7, 5, 1]
输出: -1.0
示例 3
输入: x = [1, 1, 2, 3, 3], y = [2, 1, 4, 3, 5]
输出: 0.790569
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
提示 1
Spearman is just Pearson correlation applied to ranks, so the real work is ranking with ties averaged.
提示 2
Sort the indices with np.argsort, walk through the sorted order finding runs of equal values, give every member of a run the average of its positions, then use np.corrcoef on the two rank arrays.
提示 3
For a run spanning sorted positions i to j (0-based), the shared rank is (i + j) / 2 + 1, written back through the sort order; check for a constant rank array with std() == 0 and return 0.0 before calling corrcoef.
理解思路
Spearman 相关系数用于询问两个列表对项目的排序方式是否一致,而忽略实际的分数量纲。将每个值替换为其排名,然后计算这些排名的普通 Pearson 相关系数。并列的值共享它们所覆盖排名的平均值,这使得总排名之和保持不变。
x = [10, 20, 20, 30], y = [1, 3, 2, 4]。x 的排名:10 是 1,两个 20 占据了排名 2 和 3,因此每个 20 得到 2.5,30 是 4:[1, 2.5, 2.5, 4]。y 的排名:[1, 3, 2, 4]。两者的均值均为 2.5。离差:x [-1.5, 0, 0, 1.5], y [-1.5, 0.5, -0.5, 1.5]。乘积之和 = 2.25 + 0 + 0 + 2.25 = 4.5。平方和分别为 4.5 和 5。r = 4.5 / sqrt(4.5 * 5) = 0.9487。
对并列值取平均排名,计算排名数组的 Pearson 相关系数,如果任一排名数组是常数则返回 0.0。如果给所有并列值分配第一个排名,会使结果产生偏差。该方法用于检查廉价的 LLM judge 是否按照人类评分者的排序方式对答案进行排序。