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.
def 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.