Algorithm Search⌘K

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.

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
Properties
deterministicexactofflineiterative
Origin
Badrul Sarwar, George Karypis, Joseph Konstan, John Riedl, 2001

Item-based collaborative filtering predicts the rating of a user uu for an item ii from the ratings that uu gave to the items most similar to ii. 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 kk 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 KK of known ratings ruir_{ui} over mm users and nn items, and pairs (u,i)∉K(u, i) \notin K to predict. Let UiU_i be the set of users who rated ii, IuI_u the set of items that uu rated, and μu\mu_u the mean rating of uu. The adjusted cosine similarity of items i≠ji \ne j is

s(i,j)=∑u∈Ui∩Uj(rui−μu)(ruj−μu)∑u∈Ui∩Uj(rui−μu)2 ∑u∈Ui∩Uj(ruj−μu)2,s(i, j) = \frac{\sum_{u \in U_i \cap U_j} (r_{ui} - \mu_u)(r_{uj} - \mu_u)}{\sqrt{\sum_{u \in U_i \cap U_j} (r_{ui} - \mu_u)^2} \, \sqrt{\sum_{u \in U_i \cap U_j} (r_{uj} - \mu_u)^2}},

with s(i,j)=0s(i, j) = 0 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 MiM_i is the list of the kk items j≠ij \ne i with the largest positive s(i,j)s(i, j). With J=Mi∩IuJ = M_i \cap I_u, the prediction is

r^ui=∑j∈Js(i,j) ruj∑j∈Js(i,j),\hat r_{ui} = \frac{\sum_{j \in J} s(i, j)\, r_{uj}}{\sum_{j \in J} s(i, j)},

and r^ui=μu\hat r_{ui} = \mu_u when JJ is empty. This page keeps only positive similarities in MiM_i; the reason is in Pitfalls. The choice of the items to show from these predictions is the recommendation problem.

The algorithm

  1. BUILD(K, k)
  2. 1μ_u ← the mean of the ratings of u, for each user u
  3. 2c_ui ← r_ui - μ_u for each (u, i) in K ▷ centered ratings
  4. 3for each pair of items i < j do
  5. 4U ← U_i ∩ U_j ▷ users who rated both
  6. 5s(i, j) ← s(j, i) ← Σ_U c_ui c_uj / sqrt(Σ_U c_ui² · Σ_U c_uj²), or 0 if a sum is 0
  7. 6for each item i do
  8. 7M_i ← the k items j ≠ i with the largest s(i, j) > 0 (ties: smaller id)
  9. PREDICT(u, i)
  10. 8if u has no rating then return the mean of all ratings
  11. 9J ← the items of M_i that u rated
  12. 10if J is empty then return μ_u
  13. 11return Σ_{j ∈ J} s(i, j) r_uj / Σ_{j ∈ J} s(i, j)

With kk unset, line L7 keeps all items with a positive similarity. BUILD runs offline; PREDICT reads only MiM_i and the ratings of uu.

Example

The toy rating matrix of this group, with the user means:

i1i_1 i2i_2 i3i_3 i4i_4 mean
u1u_1 5 4 - 1 10/3
u2u_2 4 5 4 2 15/4
u3u_3 1 2 2 5 5/2
u4u_4 - 1 1 4 2

Predict ru1i3r_{u_1 i_3}. Item i3i_3 is rated by u2u_2, u3u_3 and u4u_4, with centered values 1/41/4, −1/2-1/2 and −1-1.

jj common users ∑cui3cuj\sum c_{ui_3} c_{uj} ∑cui32\sum c_{ui_3}^2 ∑cuj2\sum c_{uj}^2 s(i3,j)s(i_3, j)
i1i_1 u2,u3u_2, u_3 13/16 5/16 37/16 0.956
i2i_2 u2,u3,u4u_2, u_3, u_4 25/16 21/16 45/16 0.813
i4i_4 u2,u3,u4u_2, u_3, u_4 −59/16-59/16 21/16 213/16 −0.882-0.882

So Mi3=(i1,i2)M_{i_3} = (i_1, i_2), and u1u_1 rated both. The prediction is (0.956⋅5+0.813⋅4)/(0.956+0.813)=4.540(0.956 \cdot 5 + 0.813 \cdot 4) / (0.956 + 0.813) = 4.540. Item i4i_4, which the users rate in the opposite way to i3i_3, does not enter. For (u4,i1)(u_4, i_1), Mi1=(i3,i2)M_{i_1} = (i_3, i_2) with similarities 0.956 and 0.641, and u4u_4 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 i1i_1, i2i_2 and i4i_4: all positive, so it cannot see that i4i_4 is the opposite of i3i_3.

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 s(i,j)s(i, j) for each pair, that ss is symmetric with values in [−1,1][-1, 1] by the Cauchy-Schwarz inequality, that each MiM_i has at most kk items, all with positive similarity, and that PREDICT returns the weighted mean. Because the weights s(i,j)s(i, j) in line L11 are positive, the prediction is a convex combination of ratings of uu, so it lies between the smallest and the largest rating of uu on JJ, 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: UiU_i is the set of users who rated item ii, IuI_u the set of items that user uu rated, μu\mu_u the mean of the ratings of uu, and cui=rui−μuc_{ui} = r_{ui} - \mu_u.

Lemma 1 (the similarity). After lines L1 to L5, for each pair of items i≠ji \ne j the stored value s(i,j)s(i, j) equals the adjusted cosine of the page, s(i,j)=s(j,i)s(i, j) = s(j, i), and −1≤s(i,j)≤1-1 \le s(i, j) \le 1.

Proof. Line L1 computes each μu\mu_u and line L2 each cuic_{ui}. Line L3 visits each unordered pair {i,j}\{i, j\} once, as i<ji < j. Line L4 forms U=Ui∩UjU = U_i \cap U_j, and line L5 evaluates the formula of the page with the sums over UU, or 0 when a sum of squares is 0, and stores it under both orders, so s(i,j)=s(j,i)s(i, j) = s(j, i). When neither sum is 0, the value is ⟨x,y⟩/(∥x∥∥y∥)\langle x, y \rangle / (\lVert x \rVert \lVert y \rVert) for the nonzero vectors x=(cui)u∈Ux = (c_{ui})_{u \in U} and y=(cuj)u∈Uy = (c_{uj})_{u \in U}, and the Cauchy-Schwarz inequality ∣⟨x,y⟩∣≤∥x∥∥y∥|\langle x, y \rangle| \le \lVert x \rVert \lVert y \rVert gives the range. □\square

Lemma 2 (the model). After lines L6 and L7, each list MiM_i holds at most kk items (all such items when kk is not given), each j∈Mij \in M_i has j≠ij \ne i and s(i,j)>0s(i, j) > 0, and no item j′∉Mij' \notin M_i with j′≠ij' \ne i and s(i,j′)>0s(i, j') > 0 comes before an item of MiM_i in the order of decreasing similarity with ties broken by the smaller id.

Proof. Line L7 takes the set of items j≠ij \ne i with s(i,j)>0s(i, j) > 0, sorts it in the stated order, and keeps a prefix of length at most kk. A prefix of a sorted list contains every element that comes before any of its elements. □\square

Theorem 1 (correctness of the prediction). PREDICT(u,i)(u, i) returns the mean of all ratings if uu has no rating, μu\mu_u if J=Mi∩IuJ = M_i \cap I_u is empty, and

r^ui=∑j∈Js(i,j) ruj∑j∈Js(i,j)\hat r_{ui} = \frac{\sum_{j \in J} s(i, j)\, r_{uj}}{\sum_{j \in J} s(i, j)}

otherwise. In the last case

min⁡j∈Jruj≤r^ui≤max⁡j∈Jruj.\min_{j \in J} r_{uj} \le \hat r_{ui} \le \max_{j \in J} r_{uj}.

Proof. Line L8 handles a user with no rating. Line L9 forms JJ by testing each item of MiM_i for a rating of uu. If JJ is empty, line L10 returns μu\mu_u. Else, by Lemma 2, each s(i,j)s(i, j) with j∈Jj \in J is positive, so the denominator S=∑j∈Js(i,j)S = \sum_{j \in J} s(i, j) is positive, and line L11 returns the stated quotient. With αj=s(i,j)/S\alpha_j = s(i, j) / S we have αj>0\alpha_j > 0 and ∑j∈Jαj=1\sum_{j \in J} \alpha_j = 1, so r^ui=∑j∈Jαjruj\hat r_{ui} = \sum_{j \in J} \alpha_j r_{uj} is a convex combination of the numbers rujr_{uj}, and a convex combination lies between the smallest and the largest of its terms. □\square

Corollary 2 (the rating scale). If all ratings lie in an interval [a,b][a, b], then every prediction lies in [a,b][a, b].

Proof. The mean of all ratings and μu\mu_u are means of numbers in [a,b][a, b]. In the third case of Theorem 1, r^ui\hat r_{ui} lies between two ratings of uu, which are in [a,b][a, b]. □\square

The corollary needs the positive similarities of line L7. If a negative s(i,j)s(i, j) enters the sum of Sarwar et al., ∑js(i,j)ruj/∑j∣s(i,j)∣\sum_j s(i, j) r_{uj} / \sum_j |s(i, j)|, the weights s(i,j)/∑∣s∣s(i, j) / \sum |s| are no longer all positive, and the quotient can leave [a,b][a, b]. With one negative neighbor of similarity −1-1 and rating 5, the quotient is −5-5.

Complexity

The model is the word RAM, with hash tables for the ratings of each user and each item. Let nu=∣Iu∣n_u = |I_u|.

  • Build, pair by pair. For a pair (i,j)(i, j), line L5 scans UiU_i and looks up each user in UjU_j, so it costs O(∣Ui∣)O(|U_i|). Summed over all pairs this is O(n∑i∣Ui∣)=O(ns)O(n \sum_i |U_i|) = O(n s), and s≤mns \le m n gives O(mn2)O(m n^2) in the worst case. Line L7 sorts n−1n - 1 values for each item, O(n2log⁡n)O(n^2 \log n) in total, or O(n2log⁡k)O(n^2 \log k) with a heap of size kk.
  • 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 O(∑unu2)O(\sum_u n_u^2). Their paper states the worst case as O(N2M)O(N^2 M) for NN items and MM 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 (n2)\binom{n}{2} entries, O(n2)O(n^2). The model keeps O(nk)O(n k) entries.
  • Prediction. Line L9 looks up each of the at most kk items of MiM_i in the ratings of uu, so PREDICT costs O(k)O(k) expected time, independent of mm and nn. To rank all items for uu, loop over the items jj that uu rated and add s(i,j)s(i, j) and s(i,j)rujs(i, j) r_{uj} to two accumulators for each ii with j∈Mij \in M_i; with the lists MiM_i stored in reverse this costs O(nuk)O(n_u k), 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 rujr_{uj}.
  • Mean-centered prediction. Predict μu+∑js(i,j)(ruj−μu)/∑j∣s(i,j)∣\mu_u + \sum_j s(i, j)(r_{uj} - \mu_u) / \sum_j |s(i, j)|; 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 NN 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 ∑js(i,j)ruj\sum_j s(i, j) r_{uj} by ∑j∣s(i,j)∣\sum_j |s(i, j)|. With a negative similarity in the sum, the result is no longer a mean of ratings: in the example, keeping i4i_4 gives (0.956⋅5+0.813⋅4−0.882⋅1)/2.651=2.697(0.956 \cdot 5 + 0.813 \cdot 4 - 0.882 \cdot 1) / 2.651 = 2.697, 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 kk, many pairs (u,i)(u, i) have no item of MiM_i in IuI_u, and the method falls back to μu\mu_u. 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.

item_based_collaborative_filtering.pyI0RawGitHub
# 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 kk 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

  1. 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)
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example