Algorithmcore
Item-based collaborative filtering
Also called item-item collaborative filtering.
Precomputes similarities between items from co-ratings and predicts a user's rating from the user's ratings of the most similar items.
- Solves
- Recommendation problem
- Time
- O(n s + n^2 log n) worst
- Space
- O(n^2) extra
- Where
- k = the model size (neighbors kept per item); m = the number of users; n = the number of items; s = the number of known ratings
- Model
- Word RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Badrul Sarwar, George Karypis, Joseph Konstan, John Riedl, 2001
Item-based collaborative filtering predicts the rating of a user for an item from the ratings that gave to the items most similar to . The similarity of two items is computed from the users who rated both, for example by the adjusted cosine of Sarwar et al. (2001), and the most similar items of each item are stored in advance as the model. Where user-based collaborative filtering compares rows of the rating matrix at prediction time, this method compares columns once, offline. Slope One uses the same item pairs but stores an average rating difference in place of a similarity.
In plain words
To guess how much you will like a film, look at the films you already rated, and keep those that resemble it most. Two films resemble each other when the same people liked both and the same people disliked both. Your guess is the average of your own ratings of the close films, with the closer ones counting more.
The resemblance between films changes slowly, because each film has many ratings. So the system computes, once a day or once a week, a short list of close films for each film. A guess then needs only a few lookups in your own ratings, which is fast enough to do while a page loads.
The problem
The input is a set of known ratings over users and items, and pairs to predict. Let be the set of users who rated , the set of items that rated, and the mean rating of . The adjusted cosine similarity of items is
with when a sum under a root is 0. It is the cosine similarity of the two columns on their common users after each rating has its user's mean subtracted. The model is the list of the items with the largest positive . With , the prediction is
and when is empty. This page keeps only positive similarities in ; the reason is in Pitfalls. The choice of the items to show from these predictions is the recommendation problem.
The algorithm
BUILD(K, k)- 1
μ_u ← the mean of the ratings of u, for each user u - 2
c_ui ← r_ui - μ_u for each (u, i) in K ▷ centered ratings - 3
for each pair of items i < j do - 4
U ← U_i ∩ U_j ▷ users who rated both - 5
s(i, j) ← s(j, i) ← Σ_U c_ui c_uj / sqrt(Σ_U c_ui² · Σ_U c_uj²), or 0 if a sum is 0 - 6
for each item i do - 7
M_i ← the k items j ≠ i with the largest s(i, j) > 0 (ties: smaller id) PREDICT(u, i)- 8
if u has no rating then return the mean of all ratings - 9
J ← the items of M_i that u rated - 10
if J is empty then return μ_u - 11
return Σ_{j ∈ J} s(i, j) r_uj / Σ_{j ∈ J} s(i, j)
With unset, line L7 keeps all items with a positive similarity. BUILD runs offline; PREDICT reads only and the ratings of .
Example
The toy rating matrix of this group, with the user means:
| mean | |||||
|---|---|---|---|---|---|
| 5 | 4 | - | 1 | 10/3 | |
| 4 | 5 | 4 | 2 | 15/4 | |
| 1 | 2 | 2 | 5 | 5/2 | |
| - | 1 | 1 | 4 | 2 |
Predict . Item is rated by , and , with centered values , and .
| common users | |||||
|---|---|---|---|---|---|
| 13/16 | 5/16 | 37/16 | 0.956 | ||
| 25/16 | 21/16 | 45/16 | 0.813 | ||
| 21/16 | 213/16 |
So , and rated both. The prediction is . Item , which the users rate in the opposite way to , does not enter. For , with similarities 0.956 and 0.641, and gave 1 to both, so the prediction is 1.
The plain cosine of the raw columns on the common users gives 0.976, 0.996 and 0.716 for , and : all positive, so it cannot see that is the opposite of .
Correctness
Correctness here means that the algorithm computes the formulas of the problem section. The proof in proofs/correctness.md shows that lines L3 to L5 compute for each pair, that is symmetric with values in by the Cauchy-Schwarz inequality, that each has at most items, all with positive similarity, and that PREDICT returns the weighted mean. Because the weights in line L11 are positive, the prediction is a convex combination of ratings of , so it lies between the smallest and the largest rating of on , and inside the rating scale.
Proof: Item-based collaborative filtering computes the adjusted cosine model and a prediction inside the user's ratingsfull
The notation is that of the page: is the set of users who rated item , the set of items that user rated, the mean of the ratings of , and .
Lemma 1 (the similarity). After lines L1 to L5, for each pair of items the stored value equals the adjusted cosine of the page, , and .
Proof. Line L1 computes each and line L2 each . Line L3 visits each unordered pair once, as . Line L4 forms , and line L5 evaluates the formula of the page with the sums over , or 0 when a sum of squares is 0, and stores it under both orders, so . When neither sum is 0, the value is for the nonzero vectors and , and the Cauchy-Schwarz inequality gives the range.
Lemma 2 (the model). After lines L6 and L7, each list holds at most items (all such items when is not given), each has and , and no item with and comes before an item of in the order of decreasing similarity with ties broken by the smaller id.
Proof. Line L7 takes the set of items with , sorts it in the stated order, and keeps a prefix of length at most . A prefix of a sorted list contains every element that comes before any of its elements.
Theorem 1 (correctness of the prediction). PREDICT returns the mean of all ratings if has no rating, if is empty, and
otherwise. In the last case
Proof. Line L8 handles a user with no rating. Line L9 forms by testing each item of for a rating of . If is empty, line L10 returns . Else, by Lemma 2, each with is positive, so the denominator is positive, and line L11 returns the stated quotient. With we have and , so is a convex combination of the numbers , and a convex combination lies between the smallest and the largest of its terms.
Corollary 2 (the rating scale). If all ratings lie in an interval , then every prediction lies in .
Proof. The mean of all ratings and are means of numbers in . In the third case of Theorem 1, lies between two ratings of , which are in .
The corollary needs the positive similarities of line L7. If a negative enters the sum of Sarwar et al., , the weights are no longer all positive, and the quotient can leave . With one negative neighbor of similarity and rating 5, the quotient is .
Complexity
The model is the word RAM, with hash tables for the ratings of each user and each item. Let .
- Build, pair by pair. For a pair , line L5 scans and looks up each user in , so it costs . Summed over all pairs this is , and gives in the worst case. Line L7 sorts values for each item, in total, or with a heap of size .
- Build, user by user. Linden, Smith and York loop over the items, the users of each item and the other items of each user. In this order only pairs with a common user are touched, and the work is . Their paper states the worst case as for items and customers, and notes that in practice it is much lower, because most customers rate or buy few items.
- Space. The full similarity table has up to entries, . The model keeps entries.
- Prediction. Line L9 looks up each of the at most items of in the ratings of , so PREDICT costs expected time, independent of and . To rank all items for , loop over the items that rated and add and to two accumulators for each with ; with the lists stored in reverse this costs , plus top-k selection at the end.
Properties
- Model-based in its cost, memory-based in its form. The model is a table of similarities, built offline. A prediction is still a weighted mean of real ratings, so it can be explained as "because you rated these items".
- Stable similarities. When an item has many ratings, a few new ratings change its similarities little, so the table can be rebuilt on a schedule and not at each new rating.
- Uses the target user's own scale. The prediction is a mean of the user's own ratings, so no mean-centering of the result is needed.
- No prediction for a new item. An item with no rating has no similarities, see the cold-start problem.
Variants and improvements
- Other similarities. Sarwar et al. compared the plain cosine of the columns (3.1.1), the Pearson correlation of the two items on their common users (3.1.2) and the adjusted cosine (3.1.3); in their experiments on MovieLens data, the adjusted cosine gave the lowest mean absolute error. For 0 and 1 data, such as purchases, the cosine of the binary columns or the Jaccard similarity are common.
- Regression in place of the raw rating. Section 3.2.2 of Sarwar et al. fits a linear model from the ratings of the neighbor item to those of the target item and uses its output in place of .
- Mean-centered prediction. Predict ; with this form, negative similarities can be kept.
- Learned weights. SLIM learns the item-item weights by sparse regression in place of a fixed similarity formula.
- Top-N lists for implicit data. For clicks or purchases there are no ratings to average. The score of an item is the sum of its similarities to the items in the user's history, and the list is the items with the largest score, see implicit feedback.
When to use it
Use it when there are many more users than items, when items get many ratings each, and when the system must answer in a few milliseconds with an explanation: this is the setting of Linden, Smith and York. It is a strong baseline for top-N lists from purchases or clicks. When the data are very sparse and ratings must be predicted accurately, factor models such as matrix factorization are the usual next step.
Pitfalls
- Negative similarities with a plain weighted sum. Section 3.2.1 of Sarwar et al. divides by . With a negative similarity in the sum, the result is no longer a mean of ratings: in the example, keeping gives , and with larger negative weights the value can fall below the scale. Keep only positive similarities, as on this page, or use the mean-centered form.
- Plain cosine on ratings. On a scale of 1 to 5 all entries are positive, so the plain cosine is positive for every pair; the example shows 0.716 for two items with opposite ratings. Center the ratings first.
- Similarities on few common users. A pair with one or two common users can get a similarity near 1 by chance. Require a minimum number of common users, or shrink the similarity toward 0 by a factor that grows with the overlap.
- Centering by the item mean. The adjusted cosine subtracts the user mean. Subtracting the item mean gives the Pearson correlation of the two items, a different measure.
- A model that is too small. With a small , many pairs have no item of in , and the method falls back to . Sarwar et al. measured the accuracy as a function of the model size.
- Stale tables. New items stay without neighbors until the next build.
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
# Part of https://algorithm.tamnd.com/item-based-collaborative-filtering/. The authors are listed in prov/Z4THKH.jsonl.
"""Item-based collaborative filtering with adjusted cosine similarity.
The similarity of items i and j is the cosine of the two columns after
each rating has its user's mean subtracted, with all three sums over the
users who rated both items (Sarwar et al. 2001, adjusted cosine). The
model keeps, for each item, the k items with the largest positive
similarity (all of them when k is None). The prediction for user u and
item i is the weighted mean
sum_j s(i, j) r_uj / sum_j s(i, j)
over the items j of the model of i that u rated. Only positive
similarities enter, so the prediction lies between the smallest and the
largest of the ratings it uses. With no such item the prediction is the
mean of user u.
"""
import math
def adjusted_cosine(ci, cj):
"""Adjusted cosine of two items.
ci and cj map users to centered ratings r_ui - mu_u. The value is 0
when the items share no user or a centered vector on the shared
users is zero.
"""
num = si = sj = 0.0
for u, a in ci.items():
if u in cj: # @line L4
b = cj[u]
num += a * b
si += a * a
sj += b * b
if si == 0.0 or sj == 0.0:
return 0.0
return num / math.sqrt(si * sj) # @line L5
class ItemBasedCF:
"""Model-based form: the item neighbor lists are built once."""
def __init__(self, train, k=None):
self.k = k
self.by_user = {}
for (u, i), v in train.items():
self.by_user.setdefault(u, {})[i] = v
self.means = {u: sum(r.values()) / len(r) for u, r in self.by_user.items()} # @line L1
self.global_mean = sum(train.values()) / len(train)
centered = {}
for (u, i), v in train.items():
centered.setdefault(i, {})[u] = v - self.means[u] # @line L2
items = sorted(centered)
sim = {}
for a in range(len(items)): # @line L3
for b in range(a + 1, len(items)):
i, j = items[a], items[b]
s = adjusted_cosine(centered[i], centered[j])
sim[(i, j)] = sim[(j, i)] = s
self.sim = sim
self.model = {}
for i in items: # @line L6
cand = [(sim[(i, j)], j) for j in items if j != i and sim[(i, j)] > 0.0] # @line L7
cand.sort(key=lambda t: (-t[0], t[1]))
if k is not None:
cand = cand[:k]
self.model[i] = cand
def similarity(self, i, j):
return self.sim.get((i, j), 0.0)
def predict(self, u, i):
if u not in self.by_user: # @line L8
return self.global_mean
row = self.by_user[u]
num = den = 0.0
for s, j in self.model.get(i, []):
if j in row: # @line L9
num += s * row[j]
den += s
if den == 0.0: # @line L10
return self.means[u]
return num / den # @line L11
recs.py 115 lines
# 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
test_item_based_collaborative_filtering.py 93 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/item-based-collaborative-filtering/. The authors are listed in prov/Z4THKH.jsonl.
import math
import recs
from item_based_collaborative_filtering import ItemBasedCF
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):
"""Adjusted cosine and the weighted sum, written out on a dense matrix."""
m, n = len(rows), len(rows[0])
def mean(a):
vals = [x for x in rows[a] if x is not None]
return sum(vals) / len(vals)
def sim(a, b):
co = [v for v in range(m) if rows[v][a] is not None and rows[v][b] is not None]
x = [rows[v][a] - mean(v) for v in co]
y = [rows[v][b] - mean(v) for v 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(p * q for p, q in zip(x, y)) / math.sqrt(sx * sy)
cand = sorted(((sim(i, j), j) for j in range(n) if j != i), key=lambda t: (-t[0], t[1]))
cand = [t for t in cand if t[0] > 0]
if k is not None:
cand = cand[:k]
used = [(s, j) for s, j in cand if rows[u][j] is not None]
den = sum(s for s, _ in used)
if den == 0:
return mean(u)
return sum(s * rows[u][j] for s, j in used) / den
def test_toy():
train = recs.toy()
model = ItemBasedCF(train)
rows = dense(train, 4, 4)
for u, i in [(0, 2), (3, 0)]:
assert abs(model.predict(u, i) - brute(rows, u, i)) < TOL
# Items 1 and 3 (indices 0 and 2) are rated by users 2 and 3 (indices 1 and 2).
a = [4 - 3.75, 1 - 2.5]
b = [4 - 3.75, 2 - 2.5]
exact = (a[0] * b[0] + a[1] * b[1]) / math.sqrt((a[0] ** 2 + a[1] ** 2) * (b[0] ** 2 + b[1] ** 2))
assert abs(model.similarity(0, 2) - exact) < 1e-12
assert abs(model.predict(0, 2) - 4.540284512670781) < TOL
def test_matches_brute_force_on_planted_matrices():
for seed in range(5):
full = recs.planted(10, 8, 2, seed, rounded=True)
train, hidden = recs.split(full, 0.3, seed)
rows = dense(train, 10, 8)
for k in (None, 1, 3):
model = ItemBasedCF(train, k=k)
for u, i in hidden:
assert abs(model.predict(u, i) - brute(rows, u, i, k)) < TOL
def test_prediction_inside_range_of_used_ratings():
full = recs.planted(12, 9, 3, 7, noise=0.4)
train, hidden = recs.split(full, 0.3, 7)
model = ItemBasedCF(train, k=4)
for u, i in hidden:
row = {j: v for (w, j), v in train.items() if w == u}
used = [row[j] for _, j in model.model[i] if j in row]
p = model.predict(u, i)
if used:
assert min(used) - TOL <= p <= max(used) + TOL
def test_model_size_and_symmetry():
full = recs.planted(10, 8, 2, 3, noise=0.3)
train, _ = recs.split(full, 0.2, 3)
model = ItemBasedCF(train, k=2)
for i in range(8):
assert len(model.model[i]) <= 2
for j in range(8):
if i != j:
assert model.similarity(i, j) == model.similarity(j, i)
assert -1 - TOL <= model.similarity(i, j) <= 1 + TOL
History
Sarwar, Karypis, Konstan and Riedl (2001) studied item-based algorithms as a way to scale collaborative filtering beyond the user-based methods of GroupLens: they compared three item similarities and two prediction rules, and introduced the precomputed model of the most similar items. Linden, Smith and York (2003) described the item-to-item method that Amazon.com used for its recommendations, with an offline table of similar items and an online step whose cost does not depend on the numbers of customers and items.
References
- Badrul Sarwar, George Karypis, Joseph Konstan and John Riedl, Item-based collaborative filtering recommendation algorithms, Proceedings of the 10th International World Wide Web Conference (WWW 2001), 285-295, Section 3.1 (cosine, correlation and adjusted cosine similarity, 3.1.1 to 3.1.3), Section 3.2.1 (the weighted sum prediction), Section 3.3 (the precomputed model of the k most similar items and its size), Section 4 (the experiments with mean absolute error)
- Greg Linden, Brent Smith and Jeremy York, Amazon.com recommendations, item-to-item collaborative filtering, IEEE Internet Computing 7(1), 76-80, 2003, the offline table of similar items built from the items that customers buy together, cosine similarity on customer vectors, the worst case cost of the build and the online cost
- Charu C. Aggarwal, Recommender Systems, The Textbook, Springer, 2016, Chapter 2 (neighborhood-based collaborative filtering, item-based neighborhood models and the comparison with user-based models)
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 Z4THKH Edit this page History Report an error Markdown