Measure intra-list diversity of a recommendation list

Why it matters Recommendation teams track ILD next to accuracy metrics so a model does not win offline by repeating near-duplicates.

A list of ten nearly identical items is accurate but boring. Intra-list diversity (ILD) measures how different the recommended items are from each other.

Write intra_list_diversity(emb, items). emb is an (N, D) array of item embeddings and items a list of indices into it. Return the average of 1 - cosine similarity over all unordered pairs of distinct positions in the list, as a float. Return 0.0 if the list has fewer than 2 items.

Signaturedef intra_list_diversity(emb, items)

Example

intra_list_diversity([[1, 0], [0, 1], [1, 1]], [0, 1, 2]) gives 0.5286.

Understand the idea

Accuracy metrics reward a recommender for showing what a user will click, but users also get bored. If a home page shows ten phone cases of the same model, accuracy can look fine while the experience is poor. Intra-list diversity puts a number on variety: the average distance between every pair of items in the list.

Example: three items with embeddings [1, 0], [0, 1] and [1, 1]. The first two are at a right angle, distance 1 - 0 = 1. Each of them is 45 degrees from the third, distance 1 - 0.707 = 0.293. The average of the three pairs is (1 + 0.293 + 0.293) / 3 = 0.529.

Rule: ILD = mean over pairs i < j of (1 - cos(e_i, e_j)).

Teams report ILD alongside NDCG and recall, and use re-ranking methods like MMR when it falls too low.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 5.

  • Sample 1: exampleintra_list_diversity([[1, 0], [0, 1], [1, 1]], [0, 1, 2])
  • Sample 2: same itemsintra_list_diversity([[2, 2], [1, 1], [0, 3]], [0, 1])
  • Test 3: oppositeintra_list_diversity([[1, 0], [-1, 0]], [0, 1])
  • Test 4: shortintra_list_diversity([[1, 0]], [0])
  • Test 5: randomintra_list_diversity(_E, [0, 3, 5, 6])