Sub topic 6
Item-based collaborative filtering
Item-based collaborative filtering predicts a user's rating of an item from the ratings that same user gave to similar items. "Similar" is defined by how all users rated the items, not by item content. This chapter covers how the method works, how to implement it, and where it fails.
This chapter assumes you know basic Python, NumPy arrays, dot products, and cosine similarity. It also assumes you can build a user-item matrix with 0 marking missing ratings, as in the earlier chapters.
The idea
Suppose Ana rated three films and you want to predict her rating for a fourth. Look at the people who rated the fourth film. Check whether they rated it the way they rated the films Ana already saw. If the fourth film behaves like the film Ana loved, she will probably like it too.
Item-based filtering works on the columns of the user-item matrix. Each item is a vector of the ratings it received from all users. Two items are similar when those vectors point in similar directions.
The method has two steps:
- Compute an item-item similarity matrix
Sfrom the whole rating matrix. This step is offline and can be cached. - To predict user
uon itemi, take the itemsuhas rated, keep thekmost similar toi, and averageu's ratings of them, weighted by similarity.
The prediction formula is:
pred(u, i) = sum_j S[i, j] * R[u, j] / sum_j S[i, j]
Both sums run over the k neighbors j of i that user u has rated.
The running example
The same small matrix is used throughout. Rows are users, columns are items, and 0 means "not rated".
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)
observed = R > 0
sparsity = 1.0 - observed.sum() / R.size
print(f"{observed.sum()} ratings, sparsity = {sparsity:.2f}")Only user 4 rated item 2. That makes it a hard case, and a useful one to study.
Computing item-item similarity
Cosine similarity between item columns is a dot product divided by the product of the norms. Treating missing ratings as 0 works here because a 0 adds nothing to the dot product.
import numpy as np
def item_cosine(R):
norms = np.linalg.norm(R, axis=0)
norms[norms == 0] = 1.0
return (R.T @ R) / np.outer(norms, norms)
def predict(R, S, user, item, k=2):
rated = np.where(R[user] > 0)[0]
rated = rated[rated != item]
if len(rated) == 0:
return float(R[R > 0].mean())
top = rated[np.argsort(S[item, rated])[::-1][:k]]
w = S[item, top]
if w.sum() == 0:
return float(R[R > 0].mean())
return float(w @ R[user, top] / w.sum())
S = item_cosine(R)
print(predict(R, S, user=0, item=2))The printed value is about 1.73. Here is how it comes about:
- User 0 rated items 0, 1, and 3. Item 2 has similarity 0 with item 0, about 0.30 with item 1, and about 0.52 with item 3.
- With
k=2, the neighbors are items 3 and 1. User 0 rated them 1 and 3. - The weighted average is
(0.52*1 + 0.30*3) / (0.52 + 0.30), which is about 1.73.
The code handles two edge cases. If the user has rated nothing else, or all neighbor weights are zero, it falls back to the global mean rating. Without that guard you would divide by zero.
Why item-based often beats user-based
Item-based filtering became popular in large retail systems for practical reasons.
| Property | User-based | Item-based |
|---|---|---|
| Similarity computed over | Rows (users) | Columns (items) |
| Stability | Changes whenever a user rates something | Item relationships change slowly |
| Precomputation | Hard to cache usefully | Cache `S` and refresh it periodically |
| Typical size | Millions of users | Often far fewer items than users |
| Explanation | "People like you liked this" | "Because you liked X" |
Item vectors are also denser than user vectors. A popular item has many ratings, so its similarity estimates rest on more overlap. A typical user has rated only a handful of items, so two users rarely share enough ratings to compare reliably.
Mean-centering and adjusted cosine
Plain cosine on raw ratings has a flaw. Some users rate everything high and others rate everything low. Raw cosine treats a 4 from a harsh critic the same as a 4 from a generous one.
Adjusted cosine fixes this by subtracting each user's mean rating before comparing items. Only observed entries are centered. Missing entries stay 0, which now means "no information" rather than "rated at the average".
import numpy as np
def adjusted_cosine(R):
mask = R > 0
counts = mask.sum(axis=1, keepdims=True)
means = (R * mask).sum(axis=1, keepdims=True) / np.maximum(counts, 1)
C = np.where(mask, R - means, 0.0)
norms = np.linalg.norm(C, axis=0)
norms[norms == 0] = 1.0
return (C.T @ C) / np.outer(norms, norms)Centered similarities can be negative. A negative weight in the prediction formula is a problem. If the positive and negative weights nearly cancel, w.sum() is close to zero and the prediction explodes. Two common fixes:
- Keep only neighbors with positive similarity.
- Predict the deviation from the user's mean, then add the mean back:
pred = mean_u + sum(S * (R_uj - mean_u)) / sum(abs(S)).
From predictions to a top-N list
Most products show a ranked list rather than a predicted number. To build one, predict a score for every item the user has not rated, sort, and keep the best n.
import numpy as np
def recommend(R, S, user, n=2, k=2):
unrated = np.where(R[user] == 0)[0]
scored = [(int(i), predict(R, S, user, i, k)) for i in unrated]
scored.sort(key=lambda t: t[1], reverse=True)
return scored[:n]
print(recommend(R, S, user=1, n=2))This code reuses R, S, and predict from the earlier blocks, so run them first. For ranking, the absolute prediction values matter less than their order. That is why top-N quality is judged with precision@k and recall@k, not RMSE alone.
Choosing k
k controls the bias-variance trade-off.
- A small
kuses only the closest neighbors. Predictions are specific but noisy, and one odd rating can dominate. - A large
ksmooths predictions toward the user's overall average. Weakly related items start to contribute. - Values from 20 to 50 are common on real data. On the toy matrix,
k=2is the practical maximum.
Choose k by evaluating on a validation split that was built without leakage. Never tune it on the test set.
Common errors and edge cases
- Treating 0 as a real rating. In the similarity step this is acceptable, as shown above. In
predict, you must select only entries whereR > 0. Averaging over zeros drags predictions down. - Similarity from tiny overlap. Two items rated by a single shared user can have cosine 1.0 from one data point. Apply significance weighting: multiply similarity by
min(n_common, 50) / 50, or require a minimum number of co-raters. - Predicting an item the user already rated. Exclude rated items from the candidate list. The
predictfunction excludes the target item from its own neighbor set for a related reason: self-similarity is 1.0 and would copy the answer. - Leaking test ratings into
S. ComputeSonly from training ratings. If held-out ratings influence the similarity matrix, your evaluation is too optimistic. - Memory growth.
Sis items by items. With 100,000 items, a dense float64 matrix needs about 80 GB. Keep only the top neighbors per item, or use approximate nearest neighbor search, covered in the scaling chapter. - Cold start. A new item has no ratings, so its column is all zeros and its similarity to every other item is 0. Item-based filtering cannot recommend it until it collects ratings.
Exercise
In the running example, user 0 has rated items 0, 1, and 3. The similarity of item 2 to item 0 is 0, to item 1 is about 0.30, and to item 3 is about 0.52. Why does predict(R, S, user=0, item=2, k=3) give a different result from k=2, and in which direction does it move? Assume ratings of 5, 3, and 1 for items 0, 1, and 3.
Show answer
With k=3, item 0 joins the neighbor set. Its weight is 0, so it adds nothing to the numerator or to the weight sum. The result is unchanged at about 1.73. The prediction would shift only if item 0 had a nonzero similarity. A positive similarity would pull the prediction toward user 0's rating of 5 for item 0, which raises it. This shows that zero-similarity neighbors are harmless in the weighted average, while weakly positive ones can distort it when k is large.