Measure hit rate and recall at k for a recommender

Offline recommender evaluation hides one item each user later interacted with and checks whether your top-k list contains it.

Write hit_recall_at_k(recs, truth, k) where recs[u] is a ranked list of item ids and truth[u] is the set of items user u actually liked. Return (hit_rate, mean_recall):
- hit: 1 if any of the first k recs is in truth[u], else 0
- recall: |top_k intersect truth| / |truth| (0 if truth is empty)
Average both over users.

Signaturedef hit_recall_at_k(recs, truth, k)

Understand the idea

Offline recommender tests hide items a user later liked and check whether your top-k list finds them. Hit rate asks a yes or no question per user: did any of the top k appear in the liked set? Recall asks what fraction of the liked items appeared in the top k. Dividing by k instead would give precision, a different metric. Worked example, k = 2. User A: recs [5, 3, 9], liked {3, 7}. Top 2 are [5, 3], so hit = 1 and recall = 1 / 2 = 0.5. User B: recs [1, 2, 4], liked {8}. No match, so hit = 0 and recall = 0. Hit rate = (1 + 0) / 2 = 0.5, mean recall = (0.5 + 0) / 2 = 0.25. A user with an empty liked set gets recall 0. Rule: hit = 1 if top_k intersects truth; recall = |top_k intersect truth| / |truth|; average both over users. Streaming and shopping recommenders report these numbers.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: three usershit_recall_at_k([[1, 2, 3], [4, 5, 6], [7, 8, 9]], [{2, 10}, {9}, {7, 8}], 2)
  • Sample 2: k = 1hit_recall_at_k([[5, 1], [3, 4]], [{1}, {3}], 1)
  • Test 3: big truth setshit_recall_at_k([[1, 2, 3, 4], [9, 8, 7]], [{1, 2, 5, 6}, {7}], 3)