#329Maximal Marginal Relevance (MMR)Medium

Maximal Marginal Relevance (MMR)

Background

Maximal Marginal Relevance (MMR) is the greedy diversifier for ranked lists. It balances relevance to the query against redundancy among already-selected items, picking the next item that maximises (1λ)rel(i)λmaxjsim(i,j)(1 - \lambda)\,\text{rel}(i) - \lambda \max_j \text{sim}(i, j) where jj ranges over already-selected items.

Problem statement

Implement mmr(rel_scores, sim_matrix, k, lambda_=0.5). Greedily build a list of k indices.

score(i)  =  (1λ)reli    λmaxjSsimi,j\text{score}(i) \;=\; (1 - \lambda)\,\text{rel}_i \;-\; \lambda\, \max_{j \in S} \text{sim}_{i, j}

For the first pick, the max-sim term is 00 (empty set). Return the selected indices in selection order.

Input

  • rel_scores - 1-D array length nn, relevance to the query.
  • sim_matrix - n×nn \times n array of pairwise similarities in [0,1][0, 1].
  • k - int, number of items to select.
  • lambda_ - float in [0,1][0, 1], diversity strength. λ=0\lambda = 0 -> pure relevance; λ=1\lambda = 1 -> pure diversity.

Output

  • list[int] of length min(k,n)\min(k, n), selected indices in order.

Examples

Input: rel=[0.9, 0.85, 0.8], sim_matrix all-1s, k=2, lambda_=0.5
Output: [0, ...]   # first pick is highest-relevance; second is whichever maximises diversity

Constraints

  • Use selection-set max sim (not sum or mean); that's the canonical MMR form.
  • Tie-break on score by lower index.
  • kk may exceed nn; in that case return nn items.

Notes

  • Why greedy. The exact diversification problem is NP-hard; MMR is the universally-cited greedy heuristic. Production rerankers run it as a post-step after the bi-encoder retrieval.
Python
Loading...

▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.

  • Example: first pick is the highest-relevance item
  • Reference: lambda=0 gives pure relevance ordering
  • Sample: lambda=0.5 promotes diversity over a redundant second-best