Sub topic 2
User-Based Collaborative Filtering
Assume you know Python, NumPy arrays, dot products, matrices, and basic averages. Collaborative filtering recommends items from patterns in user behavior rather than item descriptions.
User-based collaborative filtering
User-based collaborative filtering finds users with similar rating patterns. To predict user \(u\)'s rating for item \(i\), it combines ratings for \(i\) from those neighboring users:
\[ \hat r{u,i} = \frac{\sum{v \in N(u)} s(u,v)r{v,i}} {\sum{v \in N(u)} |s(u,v)|} \]
Here, \(s(u,v)\) is a similarity score and \(N(u)\) is the selected neighborhood. Cosine similarity works directly on rating vectors. Pearson correlation first subtracts each user's average rating, so it handles users who consistently rate higher or lower.
Item-based collaborative filtering
Item-based filtering compares items instead of users. It asks which items resemble the target item, then uses the user's ratings for those items. This often changes more slowly than user similarity because item relationships are usually more stable.
import numpy as np
R = np.array([
[5, 3, 0, 1],
[4, 0, 0, 1],
[1, 1, 0, 5],
], dtype=float)
norms = np.linalg.norm(R, axis=0)
norms[norms == 0] = 1
S = (R.T @ R) / np.outer(norms, norms)
user, target, k = 0, 2, 2
rated = np.where(R[user] > 0)[0]
neighbors = rated[np.argsort(S[target, rated])[::-1][:k]]
weights = S[target, neighbors]
prediction = weights @ R[user, neighbors] / weights.sum()
print(prediction)Ratings, top-N lists, and leakage
For recommendations, score every unseen item, sort scores descending, and return the first \(N\). Never recommend items already consumed unless repetition is intentional.
Split interactions before computing similarities or fitting factors. A time-based split is usually safest: older events train the model, while later events test it. If test events influence similarities, the evaluation leaks future information and becomes too optimistic.
Evaluating recommenders
RMSE measures rating error, but ranking metrics often match recommendation goals better.
| Metric | Meaning |
|---|---|
| Precision@k | Fraction of the first k recommendations that are relevant |
| Recall@k | Fraction of relevant items recovered in the first k |
| RMSE | Square-root average of squared rating errors |
Exercise
Why can a model have good RMSE but poor top-N recommendations?
Show answer
RMSE rewards accurate numeric ratings, while top-N metrics depend on whether relevant items appear near the beginning of the ranked list.