Problems
Loading...
1 / 1

Adjusted Cosine Similarity

Recommender Systems
Medium

Adjusted cosine similarity is used in item-based collaborative filtering to measure the similarity between two items. Unlike regular cosine similarity, it accounts for differences in user rating scales by subtracting each user's mean rating before computing the similarity. A user who rates everything 4-5 and a user who rates 1-2 should contribute equally, which raw cosine similarity fails to capture.

Given a ratings matrix (users x items, 0 = unrated), compute the adjusted cosine similarity between two specified items. Only consider users who have rated both items.

Formula

sim(i,j)=uUij(ruirˉu)(rujrˉu)uUij(ruirˉu)2uUij(rujrˉu)2\text{sim}(i,j) = \frac{\sum_{u \in U_{ij}} (r_{ui} - \bar{r}_u)(r_{uj} - \bar{r}_u)}{\sqrt{\sum_{u \in U_{ij}} (r_{ui} - \bar{r}_u)^2} \cdot \sqrt{\sum_{u \in U_{ij}} (r_{uj} - \bar{r}_u)^2}}

where UijU_{ij} is the set of users who rated both items, and rˉu\bar{r}_u is the mean of user u's non-zero ratings.

Loading visualization...

Examples

Input:

ratings = [[5,3,0],[4,0,2],[0,1,4]], item_i = 0, item_j = 1

Output:

-1.0

Only user 0 rated both items. User 0 mean = (5+3)/2 = 4. Centered: (5-4, 3-4) = (1, -1). Similarity = (1)(-1) / (1)(1) = -1.0.

Input:

ratings = [[5,1],[4,2],[3,3]], item_i = 0, item_j = 1

Output:

-1.0

All users rated both items. User means: 3, 3, 3. Centered item 0: (2, 1, 0). Centered item 1: (-2, -1, 0). Perfect negative correlation.

Hint 1

First compute each user's mean rating (only over non-zero entries). Then for each user who rated both items, compute the centered ratings and accumulate the numerator and denominator terms.

Hint 2

The denominator has two parts under separate square roots multiplied together. Track sum of squared centered ratings for each item separately, then take the product of their square roots.

Requirements

  • Compute per-user mean ratings using only non-zero (rated) entries
  • Only include users who have rated both items in the similarity calculation
  • Center each rating by subtracting the user mean before computing similarity
  • Return 0.0 if the denominator is zero or no users rated both items

Constraints

  • ratings_matrix is a list of lists (users x items), 0 means unrated
  • item_i and item_j are valid column indices
  • Return a float between -1.0 and 1.0
  • Time limit: 300 ms
Try Similar Problems