User-Based Collaborative Filtering

Recommender SystemsHard+20 XP+20

User-Based Collaborative Filtering

To guess how a user would rate an item they haven't seen, find the users most like them who have rated it, and take a weighted average of what those people thought — corrected for the fact that some of them are simply more generous raters.

r^ui=rˉu+∑vsim(u,v) (rvi−rˉv)∑v∣sim(u,v)∣\hat{r}_{ui} = \bar{r}_u + \frac{\sum_v sim(u, v)\,(r_{vi} - \bar{r}_v)}{\sum_v |sim(u, v)|}r^ui​=rˉu​+∑v​∣sim(u,v)∣∑v​sim(u,v)(rvi​−rˉv​)​

Task: write predict_user_cf(ratings, user, item, k) returning the prediction, rounded to 4 decimal places.

The steps, pinned down:

  1. Candidates — every other user who has rated item.
  2. Similarity — for each candidate, cosine similarity between their raw ratings and the target user's, over only the items both of them rated. If they share no rated items, or either side's magnitude is 0, the similarity is 0.
  3. Neighbours — the k candidates with the highest similarity. Ties go to the lower user index.
  4. Predict — the target user's own mean, plus the weighted average of each neighbour's rating expressed as a deviation from that neighbour's own mean.
  • ratings is a list of rows, one per user, with None for unrated. Every user's mean is over the items they actually rated.
  • If the similarities all come to 0, return the target user's mean alone.
  • Fewer than k candidates is fine — use what there is.

Two details carry the whole method. The deviations are why a harsh critic's 3 can push a prediction up: what transfers is "they liked it more than usual", not the number itself. And the denominator is a sum of absolute similarities, so a negatively-correlated neighbour still contributes a full share of the weight — their rating just gets flipped, which is information too.

Examples

ratings = [[5, 3, 4], [4, 3, None], [1, 5, 2]]
user = 1
item = 2
k = 2
returns 3.2145
ratings = [[5, 5, 5], [5, 5, None]]
user = 1
item = 2
k = 1
returns 5.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