Maximal Marginal Relevance
Implement Maximal Marginal Relevance (MMR) for diverse retrieval.
MMR selects documents that are both relevant to the query and diverse:
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
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
0 2
- We start with an empty set of selected documents and a candidate set containing all documents.
- The first document is selected based on its relevance to the query, calculated as , which is the cosine similarity between the document vector and the query vector . In this case, document 0 has the highest similarity to the query vector .
- For the second selection, we calculate the MMR score for each remaining document in using the formula: . With , 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