Item-Based Collaborative Filtering

Recommender SystemsMedium+15 XP+15

Item-Based Collaborative Filtering

User-based filtering asks "who is like you?". Item-based filtering turns it around: to predict how you'd rate an item, find the items most similar to it that you have already rated, and average your own ratings of those.

r^ui=∑jsim(i,j) ruj∑j∣sim(i,j)∣\hat{r}_{ui} = \frac{\sum_j sim(i, j)\,r_{uj}}{\sum_j |sim(i, j)|}r^ui​=∑j​∣sim(i,j)∣∑j​sim(i,j)ruj​​

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

The steps:

  1. Candidates — every other item the target user has already rated.
  2. Similarity — for each candidate, cosine similarity between its column and the target item's column, over only the users who rated both. No shared users, or a zero magnitude, means a similarity of 0.
  3. Neighbours — the k most similar candidates. Ties go to the lower item index.
  4. Predict — the weighted average of the user's raw ratings of those neighbours, with the absolute similarities as the divisor.
  • ratings is a list of rows (users) by columns (items), with None for unrated. zip(*ratings) gives you the columns.
  • If the similarities all come to 0, return 0.0.
  • Notice there's no mean-centering here, unlike the user-based version. Every rating in this average came from the same user, so there's no difference in generosity to correct for — the thing that made centring necessary there is absent by construction.

Item-based is the version that actually got deployed at scale, and the reason is practical rather than mathematical: item-item similarities are far more stable than user-user ones. A film's relationship to other films barely moves from week to week, so the similarity matrix can be computed nightly and cached, while a user's taste profile shifts with every click. Amazon's recommender was built on exactly this asymmetry.

Examples

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