Predict a rating from similar users

User-based collaborative filtering predicts how user u would rate item i by looking at users with similar taste who already rated i.

R is a ratings matrix where 0 means not rated. Write predict_rating(R, u, i, k):
1. Similarity between u and v is cosine similarity over items both have rated (0 if they share none).
2. Among users v != u who rated i, take the k with the highest similarity (ties: lower index first).
3. Predict mean_u + sum(sim * (R[v, i] - mean_v)) / sum(|sim|), where means are over each user's rated items only.
If no neighbour has nonzero similarity, return mean_u.

Signaturedef predict_rating(R, u, i, k)

Understand the idea

User-based collaborative filtering predicts a rating by asking users with similar taste. Compare users only on items both have rated, so missing zeros do not distort similarity. Then, since some people rate harshly and others generously, use each neighbour's deviation from their own average and add it to the target user's average. Worked example: predict user 0 on item 2. User 0 rated [5, 3, -], mean 4. User 1 rated [4, 2, 4], mean 3.333. User 2 rated [1, 5, 2], mean 2.667. Cosine on shared items 0 and 1: user 1 gives 26 / (5.831 x 4.472) = 0.997, user 2 gives 20 / (5.831 x 5.099) = 0.673. Deviations on item 2: 4 - 3.333 = 0.667 and 2 - 2.667 = -0.667. Prediction = 4 + (0.997 x 0.667 - 0.673 x 0.667) / (0.997 + 0.673) = 4.13. Rule: mean_u + sum(sim x (R_vi - mean_v)) / sum(|sim|) over the top k raters of i. Classic movie recommenders used this.

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

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: user 1 item 1predict_rating(_R, 1, 1, 2)
  • Sample 2: user 0 item 2predict_rating(_R, 0, 2, 3)