Adjusted Cosine: Item Similarity, Generosity Removed

Recommender SystemsMedium+15 XP+15

Adjusted Cosine: Item Similarity, Generosity Removed

To compare two items, you look at the users who rated both. Plain cosine similarity on their raw ratings has a problem: a user who rates everything 4 or 5 makes every pair of items look similar, because all their numbers are high.

Adjusted cosine removes each user's generosity before comparing. Subtract that user's mean from both of their ratings, then take the cosine of what's left:

sim(a,b)=∑u(rua−rˉu)(rub−rˉu)∑u(rua−rˉu)2 ∑u(rub−rˉu)2sim(a, b) = \frac{\sum_u (r_{ua} - \bar{r}_u)(r_{ub} - \bar{r}_u)}{\sqrt{\sum_u (r_{ua} - \bar{r}_u)^2} \, \sqrt{\sum_u (r_{ub} - \bar{r}_u)^2}}sim(a,b)=∑u​(rua​−rˉu​)2​∑u​(rub​−rˉu​)2​∑u​(rua​−rˉu​)(rub​−rˉu​)​

Task: write adjusted_cosine(ratings, item_a, item_b) returning that similarity, rounded to 4 decimal places.

  • ratings is a list of rows, one per user, one column per item, with None for unrated.
  • Only users who rated both items contribute a term.
  • Each user's mean is taken over all the items they rated, not just the two being compared. That's what makes it a measure of their general generosity rather than of these two items.
  • If no user rated both items, return 0.0.
  • If either sum of squares is 0 — which happens when every contributing user rated both items exactly at their own mean — return 0.0 instead of dividing by zero.

The result runs from -1 to 1. Near +1 means users who liked one liked the other; near -1 means they systematically disagreed; near 0 means knowing one tells you nothing.

The word "adjusted" is the whole lesson. Centring per user inside an item-to-item comparison is a slightly odd-looking move, and it's precisely what strips out the one confound that would otherwise dominate: how high a given person's ratings run.

Examples

ratings = [[5, 4, 1], [1, 2, 5], [4, 5, 2]]
item_a = 0
item_b = 1
returns 0.686
ratings = [[5, 1, 3], [1, 5, 3]]
item_a = 0
item_b = 1
returns -1.0

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run