Sub topic 4
Measuring similarity: cosine, Pearson, Jaccard
Neighborhood methods rely on one operation: scoring how alike two users or two items are. This chapter assumes you know NumPy arrays, dot products, and the user-item matrix from the previous chapters. The matrix R below uses 0 for "not rated", as before.
What a similarity function does
A similarity function takes two rows (users) or two columns (items) of the matrix and returns one number. A higher number means the two are more alike. The choice of function decides who counts as a neighbor, so it changes every prediction built on top of it.
Cosine similarity
Cosine similarity is the dot product of two vectors divided by the product of their lengths. It measures the angle between the vectors and ignores their magnitude. With zeros for missing ratings, unrated items add nothing to the dot product, so only co-rated items contribute to the numerator.
Pearson correlation
Pearson correlation is cosine similarity after subtracting each vector's mean. This corrects for users who rate harshly or generously. Someone who gives every liked item a 3 and someone who gives it a 5 look identical after centering. Compute the mean over the items both users rated, not over the zeros.
Jaccard similarity
Jaccard similarity ignores rating values. It treats each user as the set of items they interacted with. The score is the size of the intersection divided by the size of the union. It suits implicit feedback such as clicks or purchases, where there are no ratings to compare.
All three in code
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):
denom = np.linalg.norm(a) * np.linalg.norm(b)
return 0.0 if denom == 0 else float(a @ b / denom)
def pearson(a, b):
both = (a > 0) & (b > 0)
if both.sum() < 2:
return 0.0
x = a[both] - a[both].mean()
y = b[both] - b[both].mean()
denom = np.linalg.norm(x) * np.linalg.norm(y)
return 0.0 if denom == 0 else float(x @ y / denom)
def jaccard(a, b):
ra, rb = a > 0, b > 0
union = (ra | rb).sum()
return 0.0 if union == 0 else float((ra & rb).sum() / union)
print(cosine(R[0], R[2])) # about 0.42
print(pearson(R[0], R[2])) # about -0.87
print(jaccard(R[0], R[2])) # 1.0Users 0 and 2 rated the same three items, so Jaccard returns 1.0. They disagree strongly: user 0 loves item 0 and user 2 dislikes it. Pearson sees this and returns a negative value. Cosine stays positive because all ratings are positive numbers.
Comparing the measures
| Measure | Uses rating values | Corrects for rating scale | Best fit |
|---|---|---|---|
| Cosine | Yes | No | Sparse data, item-item similarity |
| Pearson | Yes | Yes | Explicit ratings with varied user habits |
| Jaccard | No | Not applicable | Implicit, binary feedback |
Common errors
- Treating 0 as a real rating. In cosine, a zero is harmless in the numerator but still affects nothing else. In Pearson, including zeros in the mean pulls every user's average down and distorts the result. Mask to co-rated items first.
- Trusting tiny overlaps. Pearson on two co-rated items is always 1 or -1, because two points always lie on a line. Users 0 and 1 above share only items 0 and 3, so
pearson(R[0], R[1])returns exactly 1.0. Require a minimum overlap, or shrink the score toward zero when the overlap is small. - Dividing by zero. A user with no ratings has a zero-length vector. Return 0.0 explicitly, as the functions above do.
- Mixing up direction. A negative Pearson value means opposite tastes. Neighborhood methods usually drop negative neighbors instead of using them.
Exercise
User a rated items [5, 3, 0, 1] and user b rated [4, 0, 0, 1]. What is their Jaccard similarity, and why might it mislead for explicit ratings?
Show answer
Their rated sets are {0, 1, 3} and {0, 3}. The intersection has 2 items and the union has 3, so Jaccard = 2/3 ≈ 0.67. It misleads because it ignores the rating values. Two users who rate the same items but disagree completely would still score 1.0.