Sub topic 4
Measuring similarity: cosine, Pearson, Jaccard
Neighborhood methods rest on one step: score how alike two users or two items are. This chapter covers three similarity measures, what each one assumes, and where each one fails. It assumes you can read basic Python and NumPy, know dot products and vector norms, and know what the user-item matrix from the earlier chapters looks like. We use the same 5-user, 4-item matrix, where 0 means "not rated".
What a similarity function must do
A similarity function takes two rows of the matrix (users) or two columns (items) and returns a number. Higher means more alike. It must handle three facts about the data:
- Most entries are missing, so two vectors rarely overlap much.
- Users rate on different scales. One user's 4 is another user's 2.
- Some data has no ratings at all, only "interacted or not".
Each measure below handles these differently.
Cosine similarity
Cosine similarity is the cosine of the angle between two vectors:
cos(a, b) = (a · b) / (‖a‖ ‖b‖)
With non-negative ratings it ranges from 0 to 1. It ignores vector length, so a user who rates everything high and a user who rates everything low can still look similar if their pattern matches.
When you store missing ratings as 0, cosine treats them as real values. That has two effects. Items that neither user rated add nothing to the dot product, which is harmless. Items that only one user rated add to that user's norm and lower the similarity. In effect, cosine reads "not rated" as "disliked", which is usually wrong.
Pearson correlation
Pearson correlation subtracts each user's mean rating first, then takes the cosine of the centered vectors. In the neighborhood setting it is usually computed over co-rated items only (items both users rated):
pearson(a, b) = Σ (a_i − ā)(b_i − b̄) / (√Σ (a_i − ā)² · √Σ (b_i − b̄)²)
The sums run over the co-rated set. It ranges from −1 to 1. Centering removes rating-scale differences, so a generous rater and a harsh rater with the same taste correlate strongly. It also produces negative values, which say "these users disagree".
There are two conventions for the means. You can use the mean over co-rated items only, or each user's mean over all their ratings. Both appear in the literature. Pick one and use it consistently in training and serving.
Jaccard similarity
Jaccard similarity ignores rating values and compares only which items each side touched:
jaccard(A, B) = |A ∩ B| / |A ∪ B|
Here A and B are the sets of items each user interacted with. It ranges from 0 to 1. It suits implicit feedback such as clicks, purchases, and plays, where there is no scale to center. It cannot tell a 5-star rating from a 1-star one, so two users who both rated the same items look identical even if they feel opposite about them.
Comparing the three on the example
This script implements all three, treating 0 as missing in Pearson and Jaccard, and compares user 0 with three other users.
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 cosine(a, b):
na, nb = np.linalg.norm(a), np.linalg.norm(b)
if na == 0 or nb == 0:
return 0.0
return float(a @ b / (na * nb))
def pearson(a, b, min_overlap=2):
mask = (a > 0) & (b > 0)
n = int(mask.sum())
if n < min_overlap:
return 0.0, n
x = a[mask] - a[mask].mean()
y = b[mask] - b[mask].mean()
denom = np.linalg.norm(x) * np.linalg.norm(y)
if denom == 0:
return 0.0, n
return float(x @ y / denom), n
def jaccard(a, b):
sa, sb = a > 0, b > 0
union = int((sa | sb).sum())
return float((sa & sb).sum() / union) if union else 0.0
for j in (1, 2, 4):
p, n = pearson(R[0], R[j])
print(f"user 0 vs user {j}: cosine={cosine(R[0], R[j]):.3f} "
f"pearson={p:.3f} (n={n}) jaccard={jaccard(R[0], R[j]):.3f}")Expected output:
user 0 vs user 1: cosine=0.861 pearson=1.000 (n=2) jaccard=0.667
user 0 vs user 2: cosine=0.423 pearson=-0.866 (n=3) jaccard=1.000
user 0 vs user 4: cosine=0.183 pearson=-1.000 (n=2) jaccard=0.500Read the rows closely:
- User 2 rated exactly the same items as user 0, so Jaccard is 1.0. But user 2 loved the item user 0 rated 1 and disliked the item user 0 rated 5. Pearson (−0.866) catches this and Jaccard cannot.
- User 1 gets a perfect Pearson score of 1.0, but from only two shared items. Any two points define a line, so two co-rated items always give a correlation of +1 or −1 (unless one user's ratings are constant). This score is almost meaningless.
- Cosine is moderate for user 1 and low for user 4, partly because the zeros count against them.
Small overlaps and shrinkage
The user 1 result shows the main failure of Pearson on sparse data. Two standard defenses help.
First, set a minimum overlap, as min_overlap does above. Pairs below it get similarity 0.
Second, shrink the similarity toward 0 in proportion to how little evidence supports it:
shrunk = sim · n / (n + λ)
Here n is the number of co-rated items and λ is a constant such as 5 or 10. A similarity backed by 100 shared items barely changes. One backed by 2 items is cut sharply.
def shrink(sim, n, lam=5):
return sim * n / (n + lam)
print(round(shrink(1.0, 2), 3)) # user 1: 2 shared items
print(round(shrink(-0.866, 3), 3)) # user 2: 3 shared items
print(round(shrink(0.9, 200), 3)) # strong evidence, little changeThe output is 0.286, -0.325, and 0.878. User 1's apparent perfect match drops to 0.286.
Choosing a measure
| Measure | Uses rating values | Handles scale differences | Range | Typical use |
|---|---|---|---|---|
| Cosine | Yes | No | 0 to 1 for non-negative data | Implicit counts, quick baselines |
| Pearson | Yes | Yes | −1 to 1 | Explicit ratings, user-based CF |
| Jaccard | No | Not applicable | 0 to 1 | Binary interactions |
For item-based CF, the usual choice is adjusted cosine. It subtracts each user's mean from their ratings (not the item's mean), then takes cosine between item columns. This removes user scale differences, which Pearson on item columns would not.
Common errors
- Treating 0 as a real rating. In Pearson, 0 entries must be masked out before centering, or the mean and the deviations are wrong. In cosine, decide on purpose whether 0 means "absent" or "disliked".
- Trusting small overlaps. A similarity from two or three shared items is noise. Use a minimum overlap, shrinkage, or both.
- Constant ratings. If a user gave every co-rated item the same score, the centered vector is all zeros and Pearson is undefined. Return 0 rather than letting a division by zero produce
nan. - Treating negative similarity as useful. Many implementations keep only positive-similarity neighbors. Negative neighbors can make predictions unstable, because "they disagree" is weak evidence about what you will like.
- Mixing conventions. Computing Pearson with co-rated means in one place and global means in another gives neighbor lists that do not match.
Exercise
Users X and Y rated the same three movies. X gave 5, 4, 5 and Y gave 2, 1, 2. Compute their cosine similarity (to two decimals) and their Pearson correlation over the co-rated items. What does the difference tell you?
Show answer
Cosine = (10 + 4 + 10) / (√66 · √9) = 24 / (8.124 · 3) = 0.98. Pearson: X's mean is 4.667 and Y's mean is 1.667, so the centered vectors are (0.333, −0.667, 0.333) and (0.333, −0.667, 0.333). They are identical, so Pearson = 1.0. Both measures say the users are highly similar, but they get there differently. Cosine is high because both vectors point in nearly the same direction. Pearson is exactly 1 because it removes the scale gap: Y simply rates about 3 points lower than X. In a prediction, Pearson-based methods would add back each user's own mean, so X's 5 would not be predicted as a 2 for Y.