Implement the MAP@K function by iterating through each query, slicing the top K retrieved items, checking if they exist in the ground truth, and calculating the mean average precision.
💡 Model Answer
MAP@K is a variant of MAP that considers only the top K results for each query. The procedure is similar to MAP, but the ranked list is truncated to the first K items.
Algorithm:
- For each query:
a. Take the top K items from the ranked list.
b. Initialize relevant_seen = 0, sum_precisions = 0.
c. For each rank k (1‑based) in the truncated list:
- If the item at rank k is in the ground‑truth set, increment relevant_seen.
- If relevant_seen > 0, add (relevant_seen / k) to sum_precisions.d. If there are relevant items in the top K, AP@K = sum_precisions / min(total_relevant, K); otherwise AP@K = 0.
- MAP@K = (sum of AP@K values) / number_of_queries.
Complexity: O(K * number_of_queries) time, as we only scan the first K items per query. Space usage is O(1) per query. This function is useful when only the top results matter, such as in search engines or recommendation systems.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500