3. 对排行榜分数进行排名,使并列分数共享名次
模型排行榜在每个分数旁边打印名次。当两个模型并列时,它们应该共享同一个名次,并且下一个模型名次跳跃,例如 1, 2, 2, 4。
为 1D 列表或数字数组编写 rank_scores(scores)。返回一个长度相同的 int 数组,其中最高分获得排名 1。并列分数获得其组内最小的排名。一个分数的排名等于 1 加上严格大于它的分数数量。
def rank_scores(scores)示例 1
输入: rank_scores([70, 90, 80, 90])
输出: [4, 1, 3, 1]
示例 2
输入: scores = [0.5, 0.9, 0.1]
输出: [2, 1, 3]
示例 3
输入: scores = [3, 3, 3]
输出: [1, 1, 1]
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
提示 1
A score's rank depends only on how many scores beat it, so you never need to sort.
提示 2
Compare every score with every other score using broadcasting, count the strictly larger ones per score, and add 1.
提示 3
With s as a float array, s[None, :] > s[:, None] is an (n, n) boolean matrix where row i marks scores above s[i]; sum along axis=1 and cast to int before adding 1.
常见错误
- 这就是错误版本中的 bug。
理解思路
竞赛排名(Competition ranking)是一种排行榜风格,其中并列分数共享名次,且下一个名次会被跳过,例如 1, 1, 3。一个简洁的理解方式是:一个分数的排名是 1 加上严格大于它的分数数量。这个定义会自动处理并列情况。普通的 argsort 即使在分数并列时也会给每个项目分配不同的位置,这是经典的错误。
scores [5, 9, 9, 7]。对于 5,有三个分数更大,所以排名 4。每个 9 都没有更大的分数,所以排名 1。对于 7,有两个分数更大,所以排名 3。结果 [4, 1, 1, 3]。一种无需循环的方法是将分数降序排列,并在取负后的排序数组上使用 np.searchsorted 来统计有多少个分数严格更大,或者对于小输入使用 broadcasting 比较每一对分数。
rank_i = 1 + count of j with score_j > score_i,以 ints 返回。模型排行榜和评估报告都使用这种排名方式。