Mean Average Precision at K (MAP@K)
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `mean_average_precision_at_k(actual, predicted, k)`. `actual[i]` holds the relevant items for query i (treated as a set) and `predicted[i]` is its ranked prediction list. Return the mean of AP@K over all queries as a `float`.
- Deduplicate each prediction list (keep the first occurrence, preserve order) before truncating to the top `k`.
- AP@K is the sum over ranks `i ≤ k` of `P@i * rel_i`, divided by `min(|relevant|, k)`. Short lists are not padded.
- A query with no relevant items scores `0.0` but still counts in the mean. An empty query list returns `0.0`.
- Raise `ValueError` if `k` is not a positive integer (bools rejected; an integral float such as `3.0` counts as 3) or if the two lists differ in length.
Examples:
```python
mean_average_precision_at_k([[3, 7]], [[5, 3, 5, 3, 7, 1]], k=3)
# dedup -> [5, 3, 7, 1], top 3 -> [5, 3, 7]
# -> (1/2 + 2/3) / 2 = 0.58333...
mean_average_precision_at_k([[1, 2, 3], []], [[1], [3]], k=2)
# query 1: one hit at rank 1, divided by min(3, 2) = 2 -> 0.5
# query 2: no relevant items -> 0.0
# -> 0.25
```
```hint Running precision
Precision at a rank only needs the number of hits seen so far, so one pass over the ranked list is enough.
```
```hint Validating k
In Python, `True` is an instance of `int`. Decide how your check tells the two apart.
```
### Constraints & Assumptions
- Items are hashable (for example ints or strings).
- Prediction lists may be shorter than `k` or contain duplicates.
### What a Strong Answer Covers
- Deduplicating each prediction list before truncating to the top `k`, and how the order of those two steps changes the score.
- AP@K as a sum of precision at each hit, normalized by `min(|relevant|, k)`.
- Queries with no relevant items, short prediction lists and an empty query list.
- Validation of `k` (including bools and non-integer types) and of the input lengths.
- Time and space complexity over all queries.
### Follow-up Questions
- How does MAP@K differ from MRR, and when would you prefer each?
- Why divide by `min(|relevant|, k)` instead of `|relevant|`?
- How would you extend this to graded relevance?
Overview: Implement mean average precision at K for ranked prediction lists that may contain duplicates, be shorter than K, or belong to queries with no relevant items. It tests the definition of a ranking metric, its normalization, and careful input validation in Python.