Algorithmcore
User-based collaborative filtering
Also called user-user collaborative filtering, GroupLens algorithm.
Predicts a rating as the user's mean plus a similarity-weighted average of how far other users rated the item above or below their own means.
- Solves
- Recommendation problem
- Time
- O(m n) worst
- Space
- O(m) extra
- Where
- k = the number of neighbors; m = the number of users; n = the number of items
- Model
- Word RAM
- Properties
- deterministicexactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Paul Resnick, Neophytos Iacovou, Mitesh Suchak, Peter Bergstrom, John Riedl, 1994
User-based collaborative filtering predicts the rating of a user for an item from the ratings that other users gave to . Each other user gets a weight, the Pearson correlation of and on the items that both rated, and the prediction is the mean of plus the weighted mean of how far each rated above or below the mean of . It is the method of the GroupLens system of Resnick et al. (1994), and it is the user-to-user form of the general collaborative filtering idea. The item-based form compares columns of the rating matrix in place of rows, and Slope One and matrix factorization replace the weights by fitted offsets or factors.
In plain words
To guess how much you will like a film, look at the people who already saw it. For each of them, check how much your past opinions agree with theirs, on the films that both of you rated. A person who agrees with you counts with a plus sign, a person who always disagrees counts with a minus sign, and a stranger counts for nothing.
People use the scale in different ways: one person gives 4 to a film they find average, another gives 2. So the method looks at how far each person rated the film above or below their own usual rating, takes a weighted average of these shifts, and adds the result to your own usual rating.
The problem
The input is a set of known ratings over users and items, and a pair with . Let be the set of items that rated, the set of users who rated , and the mean of . The output is a predicted rating . The task of choosing the items to show is the recommendation problem; a predictor of single ratings is one way to solve it, by ranking the items that did not rate by .
For two users with , the Pearson weight is
with when is empty or one of the two sums under the root is 0. For a set of neighbors, the prediction is
and when the denominator is 0. The means here are over all ratings of each user. Some texts take and over only in the weight; that is a different number, see Pitfalls.
The algorithm
PREDICT(u, i)- 1
if u has no rating then return the mean of all ratings - 2
C ← U_i \ {u} ▷ the users who rated i - 3
for each v in C do w_v ← WEIGHT(u, v) - 4
if a neighborhood size k is given then - 5
keep in C the k users with the largest w_v (ties: smaller id first) - 6
D ← Σ_{v ∈ C} |w_v| - 7
if D = 0 then return μ_u - 8
return μ_u + Σ_{v ∈ C} w_v (r_vi - μ_v) / D WEIGHT(u, v)- 9
I ← I_u ∩ I_v ▷ the co-rated items - 10
x_t ← r_ut - μ_u and y_t ← r_vt - μ_v for each t in I - 11
if Σ x_t² = 0 or Σ y_t² = 0 then return 0 - 12
return Σ x_t y_t / sqrt(Σ x_t² · Σ y_t²)
The means are computed once from the rating lists. With unset, line L5 does nothing and all users who rated take part, as in GroupLens. Line L5 keeps the most similar users, so users with a negative weight drop out first.
Example
The toy rating matrix of this group has four users and four items; a dash is a missing rating.
| mean | |||||
|---|---|---|---|---|---|
| 5 | 4 | - | 1 | 10/3 | |
| 4 | 5 | 4 | 2 | 15/4 | |
| 1 | 2 | 2 | 5 | 5/2 | |
| - | 1 | 1 | 4 | 2 |
Predict . The users who rated are , and .
| co-rated items | ||||||
|---|---|---|---|---|---|---|
| 16/3 | 26/3 | 75/16 | 0.837 | 0.25 | ||
| 26/3 | 35/4 | |||||
| 53/9 | 5 |
The numerator is and the denominator is , so . The two users with tastes opposite to rated below their means, and their negative weights turn this into evidence for a high rating. With only is left, and the prediction is .
The same formula for uses , and , with deviations , and . The result is , which is below the scale 1 to 5.
Correctness
The method is a definition, not an optimization, so correctness means that PREDICT returns the formula of the problem section, and that the formula has the stated properties. The proof in proofs/correctness.md shows that and , by the Cauchy-Schwarz inequality on the centered vectors; that does not change when all ratings of one user are multiplied by a positive number or shifted by a constant; and that , because the prediction is plus a weighted mean of the values with the weights . The last bound is all that holds: the prediction can leave the rating scale, as in the second example.
Proof: User-based collaborative filtering returns the Pearson-weighted prediction, and its weights and predictions are boundedfull
The notation is that of the page: is the set of items that user rated, is the mean of the ratings of , , and is the set of users left after line L5.
Lemma 1 (range and symmetry). For all users , and .
Proof. If is empty or one of the sums , is 0, line L11 returns 0 for both orders of the pair. Else let and , two nonzero vectors. Line L12 returns . By the Cauchy-Schwarz inequality , so the value is in . Swapping and swaps and , and the inner product and the product of the norms do not change.
Lemma 2 (invariance). Let and be real numbers, and replace every rating of one user by . Then does not change for any .
Proof. The new mean of is , so each centered value becomes , and the vector of Lemma 1 becomes . The set does not change. If then and line L11 returns 0 before and after. Else , because . The case where is the first argument follows by Lemma 1.
Theorem 1 (correctness). PREDICT returns the global mean if has no rating, if , and
otherwise, where if no is given, and is the set of the users of that come first in the order of decreasing weight, ties broken by the smaller id, if is given.
Proof. Line L1 handles a user with no rating. Line L2 sets , and line L3 stores for each , by the definition of WEIGHT in lines L9 to L12. Lines L4 and L5 replace by the first users in the stated order when is given, and leave it unchanged otherwise. Line L6 computes . If , line L7 returns . Else line L8 returns the stated expression. Each is in , so is known, and each rated at least , so is defined.
Theorem 2 (range of the prediction). If then
Proof. Let and . Then and . Write with (any choice when ). Then
a convex combination of the numbers , each in . A convex combination lies between the smallest and the largest of its terms.
The bound cannot be improved to the rating scale. In the toy matrix of the page, and the prediction for is , below the smallest rating 1.
Corollary 3 (shift of another user). If every rating of one user is shifted by a constant , then does not change for any item . If every rating of is shifted by , then each increases by .
Proof. By Lemma 2 with , no weight changes, so the set chosen in line L5 is the same. A shift of changes and by the same , so does not change, and does not change. A shift of changes by and no with ; the global mean of line L1 is not used, since has ratings.
Complexity
The model is the word RAM with the ratings of each user in a hash table, so a lookup costs expected time. Let and .
- One weight. WEIGHT scans the items of and looks each one up in the table of : time, or when it scans the shorter list.
- One prediction. Line L3 computes weights, so PREDICT costs . Line L5 is top-k selection, with a heap. The extra space is for the weights.
- All weights in advance. A table of all weights costs space and time, since each pair costs at most and . For millions of users this table does not fit, which is the main reason for the item-based form.
- Updates. A new rating changes one user's mean and that user's weights, and nothing has to be retrained: the next prediction uses it at once.
Properties
- Memory-based. The ratings are the model. There is no training step, and a new rating is used at the next prediction.
- Invariant to each user's use of the scale. Mean-centering removes a user's offset, and the Pearson weight removes a positive scale factor, from the weight. The prediction is shifted to the target user's mean.
- Explainable. Each prediction comes with the list of neighbors and their ratings, which a system can show to the user.
- Sensitive to sparse overlap. A weight from two co-rated items can be as large as one from two hundred. On one co-rated item the weight is the sign of , so it is , or .
Variants and improvements
- Other weights. Cosine similarity of the raw rating rows, the Spearman rank correlation, or a mean squared difference. Plain cosine on ratings 1 to 5 is always positive, so it cannot express disagreement.
- Significance weighting. Herlocker et al. (1999) multiplied a correlation computed on few co-rated items by a factor that grows with the size of the overlap, so that weights from small overlaps count less.
- Neighborhood selection. Keep the most similar users, or the users with above a threshold. Herlocker et al. studied the effect of the neighborhood size on the accuracy.
- Case amplification. Raise each weight to a power above 1, keeping its sign, so that close neighbors dominate.
- Z-scores. Divide each deviation by the standard deviation of and multiply the result by the standard deviation of .
- Item-based form. Swap the roles of users and items, see item-based collaborative filtering.
When to use it
Use it when the number of users is small or moderate, when ratings change often, and when the system must explain each prediction by real neighbors. For a large catalog with many more users than items, the item-based form gives tables that are smaller and change less. When accuracy matters most, factor models such as matrix factorization are the usual choice: Koren, Bell and Volinsky (2009) report from the Netflix Prize that they were more accurate than the classic neighborhood methods. The method cannot predict for a user with no ratings, see the cold-start problem.
Pitfalls
- Means over the co-rated items. If the weight centers each user on the mean of the co-rated items only, the weight changes, and it no longer matches the mean used in line L8. Both choices appear in the literature; state which one you use. In the toy matrix, has the mean 11/3 on the items , and the weight of and becomes in place of 0.837.
- Division by the plain sum of weights. Dividing by in place of breaks when positive and negative weights cancel, and the prediction can jump far out of range.
- Out of range predictions. The second example gives 0.854 on the scale 1 to 5. Clip the prediction to the scale when ratings are shown to users; for ranking only, clipping is not needed.
- Neighbors who did not rate the item. The neighborhood for is chosen among the users who rated . Choosing the most similar users first and then dropping those who did not rate often leaves too few or no neighbors.
- Zero weight users in the denominator. A user with adds nothing to either sum, so it is harmless; a missing guard for divides by zero.
- Leakage in evaluation. The hidden test ratings must not take part in the means and the weights.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the recommender system pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small rating sets for the tests of the recommender system pages.
A rating set is a dict that maps a pair (user, item) to a float rating.
Users are 0 to m - 1 and items are 0 to n - 1. No real data is used:
the tests plant a low-rank matrix from a seeded random generator, hide
some of its entries, and measure the error on the hidden entries.
"""
import math
import random
# The toy matrix of the pages: four users (rows), four items (columns).
# None marks a missing rating.
TOY = [
[5, 4, None, 1],
[4, 5, 4, 2],
[1, 2, 2, 5],
[None, 1, 1, 4],
]
def from_rows(rows):
"""Turn a list of rows (None for a missing entry) into a rating set."""
return {
(u, i): float(v)
for u, row in enumerate(rows)
for i, v in enumerate(row)
if v is not None
}
def toy():
"""The toy matrix as a rating set."""
return from_rows(TOY)
def planted(m, n, r, seed, mean=3.0, noise=0.0, rounded=False):
"""A full m by n rating set mean + P Q^T (+ noise) with rank r factors.
The factor entries are Gaussian with variance 1 / sqrt(r), so each
product p_u . q_i has variance 1. With rounded=True each rating is
rounded to the nearest integer and clipped to the scale 1 to 5.
"""
rng = random.Random(seed)
s = r ** -0.25
p = [[rng.gauss(0.0, s) for _ in range(r)] for _ in range(m)]
q = [[rng.gauss(0.0, s) for _ in range(r)] for _ in range(n)]
ratings = {}
for u in range(m):
for i in range(n):
v = mean + sum(a * b for a, b in zip(p[u], q[i]))
if noise:
v += rng.gauss(0.0, noise)
if rounded:
v = float(min(5, max(1, round(v))))
ratings[(u, i)] = v
return ratings
def split(ratings, frac, seed):
"""Hide about frac of the entries; return (train, hidden).
An entry is hidden only if its user and its item keep at least one
training entry, so each user and each item stays in the training set.
"""
rng = random.Random(seed)
keys = sorted(ratings)
rng.shuffle(keys)
left_u, left_i = {}, {}
for u, i in keys:
left_u[u] = left_u.get(u, 0) + 1
left_i[i] = left_i.get(i, 0) + 1
target = int(frac * len(keys))
hidden = {}
for u, i in keys:
if len(hidden) >= target:
break
if left_u[u] > 1 and left_i[i] > 1:
hidden[(u, i)] = ratings[(u, i)]
left_u[u] -= 1
left_i[i] -= 1
train = {k: v for k, v in ratings.items() if k not in hidden}
return train, hidden
def rmse(predict, hidden):
"""Root mean square error of predict(u, i) on the hidden entries."""
if not hidden:
raise ValueError("no hidden entries")
total = sum((predict(u, i) - v) ** 2 for (u, i), v in hidden.items())
return math.sqrt(total / len(hidden))
def global_mean(ratings):
"""The mean of all ratings."""
return sum(ratings.values()) / len(ratings)
def by_user(ratings):
"""A dict user -> {item: rating}."""
out = {}
for (u, i), v in ratings.items():
out.setdefault(u, {})[i] = v
return out
def by_item(ratings):
"""A dict item -> {user: rating}."""
out = {}
for (u, i), v in ratings.items():
out.setdefault(i, {})[u] = v
return out
user_based_collaborative_filtering.py 86 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/user-based-collaborative-filtering/. The authors are listed in prov/SEEFZS.jsonl.
"""User-based collaborative filtering with Pearson weights.
The weight of two users is the Pearson correlation of their ratings on
the items that both rated, with each user's mean taken over all of that
user's ratings. The prediction for user u and item i is
mu_u + sum_v w(u, v) (r_vi - mu_v) / sum_v |w(u, v)|
over the users v != u who rated i (or the k of them with the largest
weight). If the sum of the absolute weights is zero, the prediction is
mu_u.
"""
import math
def user_means(by_user):
"""The mean rating of each user."""
return {u: sum(row.values()) / len(row) for u, row in by_user.items()}
def pearson(ru, rv, mu, mv):
"""Pearson weight of two users on their co-rated items.
ru and rv map items to ratings; mu and mv are the users' means.
The weight is 0 when the users share no item or when one of the
centered vectors on the shared items is zero.
"""
common = [i for i in ru if i in rv] # @line L9
num = su = sv = 0.0
for i in common:
a = ru[i] - mu # @line L10
b = rv[i] - mv
num += a * b
su += a * a
sv += b * b
if su == 0.0 or sv == 0.0: # @line L11
return 0.0
return num / math.sqrt(su * sv) # @line L12
class UserBasedCF:
"""Memory-based predictor. k=None uses all users who rated the item."""
def __init__(self, train, k=None):
self.k = k
self.by_user = {}
self.by_item = {}
for (u, i), v in train.items():
self.by_user.setdefault(u, {})[i] = v
self.by_item.setdefault(i, {})[u] = v
self.means = user_means(self.by_user)
self.global_mean = sum(train.values()) / len(train)
self._w = {}
def weight(self, u, v):
key = (u, v) if u <= v else (v, u)
if key not in self._w:
self._w[key] = pearson(
self.by_user[u], self.by_user[v], self.means[u], self.means[v]
)
return self._w[key]
def neighbors(self, u, i):
"""The list of (weight, v) used to predict r_ui."""
raters = self.by_item.get(i, {}) # @line L2
nb = [(self.weight(u, v), v) for v in raters if v != u] # @line L3
if self.k is not None: # @line L4
nb.sort(key=lambda t: (-t[0], t[1])) # @line L5
nb = nb[: self.k]
return nb
def predict(self, u, i):
if u not in self.by_user: # @line L1
return self.global_mean
mu = self.means[u]
num = den = 0.0
for w, v in self.neighbors(u, i):
num += w * (self.by_item[i][v] - self.means[v])
den += abs(w) # @line L6
if den == 0.0: # @line L7
return mu
return mu + num / den # @line L8
test_user_based_collaborative_filtering.py 98 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/user-based-collaborative-filtering/. The authors are listed in prov/SEEFZS.jsonl.
import math
import recs
from user_based_collaborative_filtering import UserBasedCF, pearson
TOL = 1e-9
def dense(train, m, n):
return [[train.get((u, i)) for i in range(n)] for u in range(m)]
def brute(rows, u, i, k=None):
"""The prediction formula written out on a dense matrix with None gaps."""
n = len(rows[0])
def mean(a):
vals = [x for x in rows[a] if x is not None]
return sum(vals) / len(vals)
def w(a, b):
ma, mb = mean(a), mean(b)
co = [t for t in range(n) if rows[a][t] is not None and rows[b][t] is not None]
x = [rows[a][t] - ma for t in co]
y = [rows[b][t] - mb for t in co]
# The same float expression as the module, so that exact ties
# (frequent with integer ratings) stay ties in the top-k choice.
sx = sum(t * t for t in x)
sy = sum(t * t for t in y)
if sx == 0 or sy == 0:
return 0.0
return sum(a1 * b1 for a1, b1 in zip(x, y)) / math.sqrt(sx * sy)
nb = [(w(u, v), v) for v in range(len(rows)) if v != u and rows[v][i] is not None]
if k is not None:
nb = sorted(nb, key=lambda t: (-t[0], t[1]))[:k]
den = sum(abs(t[0]) for t in nb)
if den == 0:
return mean(u)
return mean(u) + sum(t[0] * (rows[t[1]][i] - mean(t[1])) for t in nb) / den
def test_toy_weight_and_prediction():
train = recs.toy()
model = UserBasedCF(train)
# u1 and u2 share items 1, 2 and 4; centered vectors (5/3, 2/3, -7/3), (1/4, 5/4, -7/4).
exact = (16 / 3) / math.sqrt((26 / 3) * (75 / 16))
assert abs(model.weight(0, 1) - exact) < 1e-12
rows = dense(train, 4, 4)
for u, i in [(0, 2), (3, 0)]:
assert abs(model.predict(u, i) - brute(rows, u, i)) < TOL
assert abs(model.predict(0, 2) - 3.933603130898395) < TOL
def test_matches_brute_force_on_planted_matrices():
for seed in range(5):
full = recs.planted(9, 7, 2, seed, rounded=True)
train, hidden = recs.split(full, 0.3, seed)
rows = dense(train, 9, 7)
for k in (None, 1, 3):
model = UserBasedCF(train, k=k)
for u, i in hidden:
assert abs(model.predict(u, i) - brute(rows, u, i, k)) < TOL
def test_weight_symmetric_and_in_range():
full = recs.planted(8, 6, 2, 11, noise=0.3)
train, _ = recs.split(full, 0.4, 11)
model = UserBasedCF(train)
for u in range(8):
for v in range(8):
w = model.weight(u, v)
assert abs(w - model.weight(v, u)) < 1e-15
assert -1 - TOL <= w <= 1 + TOL
def test_shift_of_one_user():
full = recs.planted(7, 6, 2, 5, noise=0.2)
train, hidden = recs.split(full, 0.3, 5)
shifted = {k: (v + 0.7 if k[0] == 2 else v) for k, v in train.items()}
a, b = UserBasedCF(train), UserBasedCF(shifted)
for u in range(7):
for v in range(7):
assert abs(a.weight(u, v) - b.weight(u, v)) < TOL
for u, i in hidden:
extra = 0.7 if u == 2 else 0.0
assert abs(a.predict(u, i) + extra - b.predict(u, i)) < TOL
def test_no_overlap_gives_user_mean():
train = {(0, 0): 4.0, (0, 1): 2.0, (1, 2): 5.0, (1, 3): 1.0}
assert pearson({0: 4.0, 1: 2.0}, {2: 5.0, 3: 1.0}, 3.0, 3.0) == 0.0
model = UserBasedCF(train)
assert model.predict(0, 2) == 3.0
assert model.predict(9, 0) == 3.0
History
Goldberg, Nichols, Oki and Terry (1992) built Tapestry, a mail filter in which users annotated messages for each other. Resnick, Iacovou, Suchak, Bergstrom and Riedl (1994) automated the idea in GroupLens for Usenet news, with the Pearson-weighted prediction of this page. Herlocker, Konstan, Borchers and Riedl (1999) studied the choices of the method in a common framework: the weight, significance weighting, the neighborhood size and the normalization of the ratings. Herlocker, Konstan, Terveen and Riedl (2004) reviewed the ways to measure the accuracy of such predictors.
References
- Paul Resnick, Neophytos Iacovou, Mitesh Suchak, Peter Bergstrom and John Riedl, GroupLens, an open architecture for collaborative filtering of netnews, Proceedings of the ACM Conference on Computer Supported Cooperative Work (CSCW 1994), 175-186, the prediction formula, the user's mean plus the correlation-weighted deviations of the other users, with Pearson correlation over the co-rated articles
- Jonathan L. Herlocker, Joseph A. Konstan, Al Borchers and John Riedl, An algorithmic framework for performing collaborative filtering, Proceedings of SIGIR 1999, 230-237, the three steps (weight all users, select a neighborhood, combine the deviations), the choice of neighborhood size, and the devaluation of correlations based on few co-rated items
- Charu C. Aggarwal, Recommender Systems, The Textbook, Springer, 2016, Chapter 2 (neighborhood-based collaborative filtering, user-based models, similarity functions and the mean-centered prediction)
- Jonathan L. Herlocker, Joseph A. Konstan, Loren G. Terveen and John T. Riedl, Evaluating collaborative filtering recommender systems, ACM Transactions on Information Systems 22(1), 5-53, 2004, the accuracy measures for predicted ratings (mean absolute error, root mean squared error) and for ranked lists
- David Goldberg, David Nichols, Brian M. Oki and Douglas Terry, Using collaborative filtering to weave an information tapestry, Communications of the ACM 35(12), 61-70, 1992, the Tapestry system, in which users annotate documents and filter on the annotations of other users
- Yehuda Koren, Robert Bell and Chris Volinsky, Matrix factorization techniques for recommender systems, IEEE Computer 42(8), 30-37, 2009, the opening comparison of matrix factorization with nearest-neighbor methods in the light of the Netflix Prize
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag SEEFZS Edit this page History Report an error Markdown