Sub topic 5
User-based collaborative filtering
This chapter assumes you know basic Python and NumPy, and that you have read the earlier chapters on the user-item matrix and on similarity measures (cosine, Pearson, Jaccard). Here you will build a user-based recommender step by step, and see where it fails.
The core idea
User-based collaborative filtering predicts a user's rating for an item from the ratings of users who behave like that user. The assumption is that if two users agreed on past items, they will probably agree on future ones.
For a target user u and an item i the user has not rated, the method has four steps:
- Compute the similarity between
uand every other user. - Keep only users who have rated
i. - Select the
kmost similar of those users. These are the neighbors. - Combine the neighbors' ratings of
iinto one prediction.
The method uses no information about the items themselves, such as genre or description. It uses only the matrix of who rated what.
Step 1: similarity on co-rated items
Pearson correlation is the usual choice for explicit ratings. It subtracts each user's own average, so a generous rater (mostly 4s and 5s) and a harsh rater (mostly 1s and 2s) can still count as similar if they rank items the same way.
The computation uses only co-rated items, meaning items that both users rated. Missing entries (0 in our matrix) must be excluded. If you treat 0 as a real rating, you are saying "this user hated the item", which is wrong.
import numpy as np
# Rows are users, columns are items. 0 means "not rated".
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_means(R):
observed = R > 0
return (R * observed).sum(axis=1) / observed.sum(axis=1)
def pearson(R, u, v, min_overlap=2):
both = (R[u] > 0) & (R[v] > 0)
if both.sum() < min_overlap:
return 0.0
a = R[u, both] - R[u, both].mean()
b = R[v, both] - R[v, both].mean()
denom = np.linalg.norm(a) * np.linalg.norm(b)
if denom == 0:
return 0.0
return float(a @ b / denom)Two guards in this function matter in practice:
- Minimum overlap. With only two co-rated items, Pearson is always +1 or -1 (or undefined), whatever the data. Real systems require a larger overlap, often 5 to 20 items, or shrink the similarity toward 0 when the overlap is small.
- Zero variance. If a user gave identical ratings on all co-rated items, the denominator is 0. The function returns 0.0 instead of dividing by zero.
Step 2 to 4: neighbors and prediction
Raw averaging of neighbor ratings has a bias problem. A neighbor who rates everything 5 would pull every prediction up. The standard fix is mean-centering. For each neighbor v, you take the deviation r(v,i) - mean(v), which says how much better or worse than usual that neighbor found the item. You then add the weighted average deviation to the target user's own mean:
pred(u,i) = mean(u) + sum(sim(u,v) * (r(v,i) - mean(v))) / sum(|sim(u,v)|)Both sums run over the neighbors v. The denominator uses absolute values so negative weights cannot cancel it toward zero.
def predict_user_based(R, user, item, k=2, min_overlap=2):
means = user_means(R)
scored = []
for v in range(R.shape[0]):
if v == user or R[v, item] == 0:
continue
s = pearson(R, user, v, min_overlap)
if s > 0:
scored.append((s, v))
if not scored:
return float(means[user]) # no usable neighbor: fall back to the user's mean
scored.sort(reverse=True)
top = scored[:k]
num = sum(s * (R[v, item] - means[v]) for s, v in top)
den = sum(abs(s) for s, _ in top)
return float(np.clip(means[user] + num / den, 1, 5))
print(f"{predict_user_based(R, user=3, item=1):.2f}")
print(f"{predict_user_based(R, user=0, item=2):.2f}")Running this prints 1.17 and then 3.00.
Here is how the first number comes out. User 3 rated items 0 and 3 with 1 and 4, and has a mean of 2.5. Three users rated item 1:
| Candidate neighbor | Co-rated items with user 3 | Pearson | Used? |
|---|---|---|---|
| User 0 | 0 and 3 | -1.0 | No, negative similarity |
| User 2 | 0 and 3 | +1.0 | Yes |
| User 4 | 3 only | 0.0 (overlap below 2) | No |
User 2 rated item 1 as 1, and user 2's mean is 7/3 (about 2.33). The deviation is 1 - 2.33 = -1.33. The prediction is 2.5 + 1.0 * (-1.33) / 1.0, about 1.17.
The second number shows the fallback. The only user who rated item 2 is user 4, whose similarity to user 0 is -1. It is dropped, so the prediction becomes user 0's mean of 3.0. A prediction that is just the user's mean carries no collaborative signal, and you should be able to detect and report that case.
Design choices
Choosing k
A small k (such as 5) gives noisy predictions from a few users. A large k (such as 200) pulls in weakly similar users and drifts toward the global item average. Typical values lie between 20 and 100. Choose k by evaluation on held-out data, not by intuition. Evaluation is covered in a later chapter.
Negative and weak neighbors
Some systems keep only neighbors with positive similarity, as above. Others also set a minimum similarity threshold. Negative neighbors are noisy evidence: "users who disagree with you" does not reliably mean "you will dislike what they like".
Neighborhoods are per item
The neighbors must have rated the item in question. The top k users overall for u may include none of them, so you pick the neighbors separately for each item. This is why step 2 comes before step 3 in the pipeline above.
Rating scale differences
Mean-centering handles users' different average levels. Some systems also divide by each user's standard deviation (z-scores), which handles users who use only a narrow part of the scale.
Cost and where it breaks
Predicting one rating costs one similarity per user, and each similarity scans the items. For U users and I items, building the full user-user similarity table costs on the order of U² · I operations and U² memory. That is acceptable for thousands of users and painful for millions.
User-based filtering has these specific weaknesses:
- Instability. A user's neighbors change whenever the user rates more items, so cached similarities go stale quickly.
- Sparsity. Two users may share few or no co-rated items, which makes their similarity undefined or unreliable.
- Scale. The user count usually grows faster than the item count, so the similarity table grows quickly. This is a main reason many production systems prefer item-based filtering, which the next chapter covers.
- Popular-item dominance. Items rated by many users make many pairs of users look similar, even when the shared ratings say little about taste.
Common errors
- Leaving zeros in the Pearson calculation, so missing ratings act as real low ratings.
- Computing a user's mean over all items (including zeros) instead of over rated items only.
- Forgetting to exclude the target user from their own neighbor list, which gives a similarity of 1 to themselves.
- Dividing by
sum(sim)instead ofsum(abs(sim))when negative weights are allowed. - Not clipping predictions to the rating range, which allows values like 5.8.
Exercise
In the code above, user 1 has not rated item 1. Predictuserbased(R, user=1, item=1) finds three users who rated item 1 (users 0, 2, and 4). Without running the code, explain why user 0 cannot contribute strongly to the prediction, and name one change that would make the similarity for this pair more trustworthy.
Show answer
User 1 rated only items 0 and 3 (values 4 and 1), and user 0 rated both of those items too, so the overlap is exactly two items. Pearson on two points is always +1 or -1 (here the deviations are (1.5, -1.5) and (1, -1), which gives +1), so the weight is determined by the shape of two numbers and carries little evidence. A more trustworthy similarity requires a larger minimum overlap (for example 5 or more co-rated items) or shrinks the similarity toward 0 in proportion to the overlap, for example by multiplying it by overlap / (overlap + 10).