Sub topic 7
Predicting ratings and producing top-N lists
This chapter turns similarity scores into predicted ratings and then into a ranked list of recommendations. It assumes you can already build a user-item matrix, compute cosine or Pearson similarity, and explain the idea behind user-based and item-based collaborative filtering (CF). It also assumes you are comfortable with NumPy indexing.
From similarity to a prediction
A similarity matrix does not recommend anything by itself. A neighborhood method adds two steps:
- Pick a neighborhood: the
kmost similar users, or thekmost similar items. - Combine the ratings in that neighborhood into one number, weighted by similarity.
For item-based CF, the prediction for user u and target item i is:
pred(u, i) = sum(sim(i, j) * r(u, j)) / sum(sim(i, j))The sums run over the k items j that user u has rated and that are most similar to i. A highly similar item pulls the prediction toward the user's rating of that item. A weakly similar item barely moves it.
User-based CF has the same shape with the roles swapped. The neighbors are users who rated item i, and you average their ratings of i.
A working implementation
The listing below builds the small matrix from earlier chapters, computes item-item cosine similarity, and predicts a rating. It then ranks the items a user has 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)
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())
def recommend(R, S, user, n=2, k=2):
candidates = np.where(R[user] == 0)[0]
scores = {int(i): predict(R, S, user, i, k) for i in candidates}
ranked = sorted(scores, key=scores.get, reverse=True)
return [(i, round(scores[i], 2)) for i in ranked[:n]]
S = item_cosine(R)
print(round(predict(R, S, user=0, item=2), 2))
print(recommend(R, S, user=1, n=2))The first call predicts user 0's rating of item 2. Item 2's most similar rated items are item 3 (cosine about 0.52) and item 1 (about 0.30). User 0 rated them 1 and 3, so the prediction is about 1.73. The prediction sits closer to 1 because the stronger neighbor carries more weight.
The second call returns a ranked list for user 1. Item 1 scores about 2.83 and item 2 scores 1.0. User 1 has rated only items 0 and 3, so every prediction rests on those two ratings.
Notice what recommend does. It predicts a score for each unrated item, sorts the scores, and keeps the first n. A top-N list is a ranking of predictions, and the ranking only needs the order to be right. This matters later, when you evaluate with precision@k instead of RMSE.
Details that change the result
Choosing k
k controls the bias-variance trade-off. A small k uses only the closest neighbors, which is precise but noisy, and it fails when the user has rated few of them. A large k is stable but pulls in weakly related neighbors, so predictions drift toward a plain average. Typical values are 20 to 50 on real datasets. Tune k on a validation split, not on the test set.
Neighbors must have rated the item
In user-based CF, only users who rated the target item can contribute. In item-based CF, only items the target user rated can contribute. The code above enforces the item-based version with R[user] > 0. Selecting the nearest neighbors first and discarding unrated ones afterward leaves you with fewer than k usable neighbors.
Mean-centering
Some users rate everything 4 or 5 and others rarely go above 3. A raw weighted average mixes these habits together. The fix is to average deviations from the user's own mean and add that mean back:
pred(u, i) = mean(u) + sum(sim * (r(u, j) - mean(u))) / sum(|sim|)def predict_centered(R, S, user, item, k=2):
observed = R[user] > 0
if not observed.any():
return float(R[R > 0].mean())
mean_u = R[user, observed].mean()
rated = np.where(observed)[0]
rated = rated[rated != item]
if len(rated) == 0:
return float(mean_u)
top = rated[np.argsort(S[item, rated])[::-1][:k]]
w = S[item, top]
denom = np.abs(w).sum()
if denom == 0:
return float(mean_u)
pred = mean_u + w @ (R[user, top] - mean_u) / denom
return float(np.clip(pred, 1, 5))
# Reuses R and S from the previous listing.
print(round(predict_centered(R, S, user=1, item=1), 2))When k covers every rated item and all weights are positive, this gives the same number as the raw version. With a smaller k the two differ, and centering usually lowers RMSE. The denominator uses np.abs(w) because Pearson similarity can be negative, and a signed sum can approach zero and blow up the prediction. The np.clip call keeps the output inside the rating scale.
Fallbacks
Every branch that returns a mean in the code is a fallback. A user with no ratings, an item with no overlapping neighbors, or all-zero similarities each leave nothing to average. The fallback hierarchy is usually the user's mean, then the item's mean, then the global mean. Track how often fallbacks fire. If they cover 30% of your predictions, you are evaluating the fallback more than the model.
Rating prediction versus ranking
| Aspect | Rating prediction | Top-N recommendation |
|---|---|---|
| Output | A number on the rating scale | An ordered list of items |
| Candidates | One user-item pair | All items the user has not interacted with |
| Typical metric | RMSE, MAE | precision@k, recall@k, NDCG |
| Scale matters | Yes | No, only the order |
A model can have good RMSE and still give poor top-N lists. Averaging over many neighbors pulls predictions toward the middle, and a top-N list needs the high end to be accurate. For implicit feedback you have no ratings, so you rank by the similarity-weighted sum of interactions and skip the division by sum(sim).
Common errors
- Recommending items the user already has. Candidates must exclude everything in the user's history.
recommendfilters withR[user] == 0, but the zero in a matrix means "unrated", not "disliked". Exclude items seen in the training data, and decide deliberately whether to exclude purchases that can repeat. - Treating 0 as a real rating. If a zero enters the weighted average, it acts as a strong dislike. Always mask with
> 0before averaging. - Normalizing by the wrong weights. The denominator must sum the weights of the neighbors actually used, not of all items.
- Ties and tiny support. A neighbor that overlaps with the target on one user can reach similarity 1.0. Shrink similarities for small overlaps, for example by multiplying by
n / (n + 10)wherenis the number of co-ratings. - Scoring all items per user in a Python loop. The
recommendfunction is fine for a demo. At scale, vectorize it. For example,S @ R[user]gives unnormalized scores for every item at once.
Exercise
A user has rated items A, B, and C with 5, 3, and 1. For a target item T, the similarities are sim(T, A) = 0.8, sim(T, B) = 0.4, sim(T, C) = 0.1. With k = 2 and the raw weighted average, what is the predicted rating for T? Why is item C ignored?
Show answer
The two most similar rated items are A and B, so C is dropped. The prediction is (0.8 5 + 0.4 3) / (0.8 + 0.4) = (4.0 + 1.2) / 1.2 = 4.33. Item C has the lowest similarity, so it falls outside the k = 2 neighborhood and contributes nothing, even though the user rated it.
Exercise
Why can a recommender with a low RMSE still produce a poor top-N list, and which metric should you check instead?
Show answer
RMSE averages error over all rated pairs, and most of those pairs are near the middle of the scale. A top-N list depends on correctly ordering the few highest-scoring candidates. Weighted averaging compresses predictions toward the mean, which can hide the order at the top. Check ranking metrics such as precision@k, recall@k, or NDCG on held-out interactions.