194. 衡量推荐系统的 hit rate 和 recall at k
离线推荐系统评估会隐藏每个用户随后交互的一个物品,并检查你的 top-k 列表是否包含该物品。
编写 hit_recall_at_k(recs, truth, k),其中 recs[u] 是物品 ID 的排序列表,truth[u] 是用户 u 实际喜欢的物品集合。返回 (hit_rate, mean_recall):
- hit: 如果前 k 个 recs 中的任何一个在 truth[u] 中,则为 1,否则为 0
- recall: |top_k intersect truth| / |truth| (如果 truth 为空则为 0)
对所有用户计算两者的平均值。
def hit_recall_at_k(recs, truth, k)示例 1
输入: recs = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], truth = [{2, 10}, {9}, {7, 8}], k = 2
输出: (0.666667, 0.5)
示例 2
输入: recs = [[5, 1], [3, 4]], truth = [{1}, {3}], k = 1
输出: (0.5, 0.5)
示例 3
输入: recs = [[1, 2, 3, 4], [9, 8, 7]], truth = [{1, 2, 5, 6}, {7}], k = 3
输出: (1.0, 0.75)
约束条件
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
Both metrics only look at the top k recommendations of each user and how many of them are in that user's truth set.
提示 2
Loop over users with zip(recs, truth), take set(r[:k]), intersect it with the truth set, record a hit and a recall, and average each list at the end.
提示 3
Recall divides by the size of the truth set, so give 0.0 when the truth set is empty instead of dividing by zero.
常见错误
- Recall 是除以存在多少相关物品;如果除以 k,得到的则是 precision at k,这是错误版本中的 bug。
理解思路
离线推荐系统测试会隐藏用户随后喜欢的物品,并检查你的 top-k 列表是否能找到它们。Hit rate 对每个用户提出一个“是或否”的问题:top k 中是否有任何物品出现在喜欢的集合中?Recall 则询问喜欢的物品中有多少比例出现在了 top k 中。如果除以 k,则会得到 precision,这是另一个不同的指标。Worked example, k = 2. User A: recs [5, 3, 9], liked {3, 7}. Top 2 是 [5, 3], 所以 hit = 1 且 recall = 1 / 2 = 0.5. User B: recs [1, 2, 4], liked {8}. 没有匹配,所以 hit = 0 且 recall = 0. Hit rate = (1 + 0) / 2 = 0.5, mean recall = (0.5 + 0) / 2 = 0.25. 喜欢集合为空的用户 recall 为 0.
hit = 1 if top_k intersects truth; recall = |top_k intersect truth| / |truth|; average both over users. 流媒体和购物推荐系统都会报告这些指标。