Sub topic 7
Predicting ratings and producing top-N lists
This chapter assumes you have the user-item matrix R (0 means "not rated") and the item-item cosine matrix S from the earlier chapters. It also assumes you are comfortable with NumPy indexing. Here you turn similarities into predicted ratings, then into a ranked list of items to show.
From similarity to a prediction
A neighborhood method predicts the rating of user u for item i as a similarity-weighted average. In the item-based form, you take the items u has already rated that are most similar to i. These items are the neighbors. You then average u's ratings of them, weighting each by its similarity to i:
pred(u, i) = Σ sim(i, j) · r(u, j) / Σ sim(i, j), summed over the k neighbors j.
The weights make closer neighbors count more. Dividing by the sum of weights keeps the result on the rating scale.
Building a top-N list
A recommender rarely shows predicted ratings. It shows a ranked list. To build one, score every item the user has not rated, sort, and cut at N.
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 top_n(R, S, user, n=2, k=2):
candidates = np.where(R[user] == 0)[0]
scored = [(int(i), predict(R, S, user, i, k)) for i in candidates]
scored.sort(key=lambda pair: pair[1], reverse=True)
return scored[:n]
S = item_cosine(R)
print(top_n(R, S, user=1))For user 1, item 1 scores about 2.83 and item 2 scores about 1.0, so item 1 ranks first. The key line is candidates = np.where(R[user] == 0)[0]. It stops the list from recommending things the user already consumed.
Common errors
- Recommending seen items. Always filter out items the user has already rated or interacted with.
- Trusting one neighbor. Item 2 above has only one neighbor with a nonzero similarity. Its prediction therefore equals that neighbor's rating (1.0), however weak the evidence is. Require a minimum number of neighbors, or shrink toward a baseline.
- Ignoring rating scale per user. Some users rate everything high. Subtract each user's mean rating before averaging, then add it back. Pearson similarity handles the same issue on the similarity side.
- Silent fallbacks. The global-mean fallback in
predicthides cold-start cases. Log how often it fires. - Out-of-range outputs. With mean-centering, predictions can exceed the scale. Clip them to the valid range, for example 1 to 5.
Exercise
In the code above, user 1 has rated items 0 and 3. If you call predict(R, S, user=1, item=2, k=1), which item supplies the prediction, and what does it return?
Show answer
With k=1 only the most similar rated item is used. Item 3 has similarity about 0.52 to item 2, and item 0 has 0. So item 3 is the sole neighbor. The prediction is the weighted average of one rating, which is user 1's rating of item 3, so it returns 1.0.