PIXELBANKv9.1.0
Menu

Implement Maximal Marginal Relevance (MMR) for diverse retrieval.

MMR selects documents that are both relevant to the query and diverse: MMR=arg⁡max⁡d∈R∖S[λ⋅sim(d,q)−(1−λ)⋅max⁡dj∈Ssim(d,dj)]\text{MMR} = \arg\max_{d \in R \setminus S} [\lambda \cdot \text{sim}(d, q) - (1-\lambda) \cdot \max_{d_j \in S} \text{sim}(d, d_j)]

where S is the set of already selected docs, R is the candidate set, λ balances relevance vs. diversity, and sim is cosine similarity.

Input:

  • Line 1: N D K lambda (num docs, dimension, num to select, lambda)
  • Line 2: query vector
  • Next N lines: document vectors

Output: Indices of K selected documents in order of selection.

Example:

Input:
4 2 2 0.5
1.0 0.0
1.0 0.1
0.9 0.0
0.0 1.0
0.5 0.5
Output:
0 2
Reasoning:
  • We start with an empty set SS of selected documents and a candidate set RR containing all documents.
  • The first document is selected based on its relevance to the query, calculated as sim(d,q)\text{sim}(d, q), which is the cosine similarity between the document vector dd and the query vector qq. In this case, document 0 has the highest similarity to the query vector [1.0,0.0][1.0, 0.0].
  • For the second selection, we calculate the MMR score for each remaining document dd in R∖SR \setminus S using the formula: λ⋅sim(d,q)−(1−λ)⋅max⁡dj∈Ssim(d,dj)\lambda \cdot \text{sim}(d, q) - (1-\lambda) \cdot \max_{d_j \in S} \text{sim}(d, d_j). With λ=0.5\lambda = 0.5, document 2 has the highest MMR score, balancing its relevance to the query and diversity from the already selected document 0.
  • The selected documents are output in the order of their selection, resulting in the output: 0 2

Constraints:

  • 0 <= lambda <= 1
  • 1 <= K <= N
  • Cosine similarity
  • If S is empty, max similarity to S = 0
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Maximal Marginal Relevance - Hard | PixelBank