Maximal Marginal Relevance Selection
Problem Statement
Select a diverse yet relevant set of memories with Maximal Marginal Relevance (MMR): greedily pick items that are relevant to the query but not too similar to what you already picked.
Background
MMR selects the next item maximizing
where S is the already-selected set. The first pick is the highest-relevance item (the max-sim term is 0 when S is empty). Ties are broken by smaller index.
Your Task
Implement:
def mmr(relevance, similarity, lam, k):
- relevance: list of floats, relevance[i] = rel of item i.
- similarity: n x n nested list, similarity[i][j].
- Return the list of selected indices in selection order, length min(k, n).
Input Format
- relevance (list), similarity (nested list), lam (float), k (int).
Output Format
- A list of ints (selected indices).
Sample
rel = [0.9, 0.8, 0.7]
sim = [[1,0.9,0.1],[0.9,1,0.2],[0.1,0.2,1]]
print(mmr(rel, sim, 0.5, 2))
Output:
[0, 2]
Example
rel = [0.9, 0.8, 0.7] sim = [[1,0.9,0.1],[0.9,1,0.2],[0.1,0.2,1]] print(mmr(rel, sim, 0.5, 2))
[0, 2]
-
First Selection (Empty Set): Since the selected set is empty, the similarity penalty is 0 for all items. We calculate the MMR score as with :
- Item 0:
- Item 1:
- Item 2:
- Item 0 has the highest score, so it is selected first. .
-
Second Selection (S = {0}): We evaluate the remaining items (1 and 2) using the formula . We must find the maximum similarity between each candidate and the already selected item 0:
- Item 1: . Score: .
- Item 2: . Score: .
-
Comparison and Selection: Comparing the scores from the second step, Item 2 () is greater than Item 1 (). Therefore, Item 2 is selected next. .
-
Termination: The target size is reached, so the algorithm stops.
-
The final output is [0, 2]
Constraints
0 <= lam <= 1,similarityisn x n.- First pick = argmax relevance (ties: smaller index).
- Each later pick maximizes
lam*rel - (1-lam)*max sim to selected; ties: smaller index.