Sub topic 5
User-based collaborative filtering
This chapter assumes you know the user-item matrix from earlier chapters, can compute cosine similarity, and are comfortable with NumPy indexing.
The idea
User-based collaborative filtering predicts a rating from people who behave like the target user. To predict whether user u will like item i:
- Measure how similar u is to every other user.
- Keep users who rated item i.
- Take the k most similar of those users, called the neighborhood.
- Average their ratings of i, weighted by similarity.
The weighted average is:
predicted rating = Σ sim(u, v) · r(v, i) / Σ sim(u, v)
The sums run over the neighbors v.
Implementation
This code uses the same matrix as the sparsity example, where 0 means "not rated". It predicts user 1's rating for item 1.
import numpy as np
R = np.array([
[5, 3, 0, 1],
[4, 0, 0, 1],
[1, 1, 0, 5],
[1, 0, 0, 4],
[0, 1, 5, 4],
], dtype=float)
def user_cosine(R):
norms = np.linalg.norm(R, axis=1)
norms[norms == 0] = 1.0
return (R @ R.T) / np.outer(norms, norms)
def predict_user_based(R, S, user, item, k=2):
global_mean = float(R[R > 0].mean())
raters = np.where(R[:, item] > 0)[0]
raters = raters[raters != user]
if len(raters) == 0:
return global_mean
top = raters[np.argsort(S[user, raters])[::-1][:k]]
w = S[user, top]
if w.sum() == 0:
return global_mean
return float(w @ R[top, item] / w.sum())
S = user_cosine(R)
print(round(predict_user_based(R, S, user=1, item=1), 2))The output is 2.34. Users 0, 2 and 4 rated item 1. Their similarities to user 1 are about 0.86, 0.42 and 0.15. With k=2, user 4 is dropped. The prediction is (0.86·3 + 0.42·1) / 1.28 ≈ 2.34.
The filter on raters is the key difference from the item-based version. Here you filter to users who rated the item. There you filtered to items the user rated.
Common errors
- Treating 0 as a rating in similarity. In the code above, a missing entry counts as a zero-valued rating in the dot product. That is acceptable for cosine on ratings, but it pulls similarity toward users with few ratings. Pearson avoids this by computing over co-rated items only.
- Forgetting to exclude the target user. The user is perfectly similar to themselves. Without
raters != user, a user who already rated the item predicts their own rating. - Ignoring user rating scales. Some users give 5 to everything and others rarely go above 3. Mean-centering fixes this: predict
mean(u) + Σ w · (r(v,i) − mean(v)) / Σ |w|. - Negative weights. Pearson can be negative. Either keep only positive similarities or divide by
Σ |w|. Dividing by a sum that can cancel to near zero produces wild predictions. - Tiny overlaps. Two users with one co-rated item can have similarity 1.0. Shrink similarity when overlap is small, or require a minimum number of co-rated items.
Cost
User-based CF needs a user-by-user similarity table. Its size grows with the square of the number of users. User behavior also changes quickly, so the table goes stale. Many systems prefer item-based CF for this reason, which the next chapter covers.
Exercise
Using the code above, what does predict_user_based(R, S, user=1, item=1, k=1) return, and why?
Show answer
It returns 3.0. With k=1 the only neighbor is user 0, the most similar user who rated item 1. Their rating is 3. The single weight cancels in the numerator and denominator, so the prediction equals that neighbor's rating.