Algorithm Search⌘K

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.

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
Properties
deterministicexactonlineiterative
Origin
Paul Resnick, Neophytos Iacovou, Mitesh Suchak, Peter Bergstrom, John Riedl, 1994

User-based collaborative filtering predicts the rating of a user uu for an item ii from the ratings that other users gave to ii. Each other user vv gets a weight, the Pearson correlation of uu and vv on the items that both rated, and the prediction is the mean of uu plus the weighted mean of how far each vv rated ii above or below the mean of vv. 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 KK of known ratings rvir_{vi} over mm users and nn items, and a pair (u,i)(u, i) with (u,i)∉K(u, i) \notin K. Let IvI_v be the set of items that vv rated, UiU_i the set of users who rated ii, and μv=1∣Iv∣∑t∈Ivrvt\mu_v = \frac{1}{|I_v|} \sum_{t \in I_v} r_{vt} the mean of vv. The output is a predicted rating r^ui\hat r_{ui}. 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 uu did not rate by r^ui\hat r_{ui}.

For two users with Iuv=Iu∩IvI_{uv} = I_u \cap I_v, the Pearson weight is

w(u,v)=∑t∈Iuv(rut−μu)(rvt−μv)∑t∈Iuv(rut−μu)2 ∑t∈Iuv(rvt−μv)2,w(u, v) = \frac{\sum_{t \in I_{uv}} (r_{ut} - \mu_u)(r_{vt} - \mu_v)}{\sqrt{\sum_{t \in I_{uv}} (r_{ut} - \mu_u)^2 \, \sum_{t \in I_{uv}} (r_{vt} - \mu_v)^2}},

with w(u,v)=0w(u, v) = 0 when IuvI_{uv} is empty or one of the two sums under the root is 0. For a set N⊆Ui∖{u}N \subseteq U_i \setminus \{u\} of neighbors, the prediction is

r^ui=μu+∑v∈Nw(u,v) (rvi−μv)∑v∈N∣w(u,v)∣,\hat r_{ui} = \mu_u + \frac{\sum_{v \in N} w(u, v)\,(r_{vi} - \mu_v)}{\sum_{v \in N} |w(u, v)|},

and r^ui=μu\hat r_{ui} = \mu_u when the denominator is 0. The means here are over all ratings of each user. Some texts take μu\mu_u and μv\mu_v over IuvI_{uv} only in the weight; that is a different number, see Pitfalls.

The algorithm

  1. PREDICT(u, i)
  2. 1if u has no rating then return the mean of all ratings
  3. 2C ← U_i \ {u} ▷ the users who rated i
  4. 3for each v in C do w_v ← WEIGHT(u, v)
  5. 4if a neighborhood size k is given then
  6. 5keep in C the k users with the largest w_v (ties: smaller id first)
  7. 6D ← Σ_{v ∈ C} |w_v|
  8. 7if D = 0 then return μ_u
  9. 8return μ_u + Σ_{v ∈ C} w_v (r_vi - μ_v) / D
  10. WEIGHT(u, v)
  11. 9I ← I_u ∩ I_v ▷ the co-rated items
  12. 10x_t ← r_ut - μ_u and y_t ← r_vt - μ_v for each t in I
  13. 11if Σ x_t² = 0 or Σ y_t² = 0 then return 0
  14. 12return Σ x_t y_t / sqrt(Σ x_t² · Σ y_t²)

The means μv\mu_v are computed once from the rating lists. With kk unset, line L5 does nothing and all users who rated ii 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.

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}. The users who rated i3i_3 are u2u_2, u3u_3 and u4u_4.

vv co-rated items ∑xtyt\sum x_t y_t ∑xt2\sum x_t^2 ∑yt2\sum y_t^2 w(u1,v)w(u_1, v) rvi3−μvr_{v i_3} - \mu_v
u2u_2 i1,i2,i4i_1, i_2, i_4 16/3 26/3 75/16 0.837 0.25
u3u_3 i1,i2,i4i_1, i_2, i_4 −26/3-26/3 26/3 35/4 −0.995-0.995 −0.5-0.5
u4u_4 i2,i4i_2, i_4 −16/3-16/3 53/9 5 −0.983-0.983 −1-1

The numerator is 0.837⋅0.25+(−0.995)(−0.5)+(−0.983)(−1)=1.6900.837 \cdot 0.25 + (-0.995)(-0.5) + (-0.983)(-1) = 1.690 and the denominator is 0.837+0.995+0.983=2.8150.837 + 0.995 + 0.983 = 2.815, so r^u1i3=10/3+0.600=3.934\hat r_{u_1 i_3} = 10/3 + 0.600 = 3.934. The two users with tastes opposite to u1u_1 rated i3i_3 below their means, and their negative weights turn this into evidence for a high rating. With k=1k = 1 only u2u_2 is left, and the prediction is 10/3+0.25=3.58310/3 + 0.25 = 3.583.

The same formula for ru4i1r_{u_4 i_1} uses w(u4,u1)=−0.983w(u_4, u_1) = -0.983, w(u4,u2)=−0.943w(u_4, u_2) = -0.943 and w(u4,u3)=0.943w(u_4, u_3) = 0.943, with deviations 5/35/3, 1/41/4 and −3/2-3/2. The result is 2−3.288/2.868=0.8542 - 3.288 / 2.868 = 0.854, 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 −1≤w(u,v)≤1-1 \le w(u, v) \le 1 and w(u,v)=w(v,u)w(u, v) = w(v, u), by the Cauchy-Schwarz inequality on the centered vectors; that ww does not change when all ratings of one user are multiplied by a positive number or shifted by a constant; and that ∣r^ui−μu∣≤max⁡v∈C∣rvi−μv∣|\hat r_{ui} - \mu_u| \le \max_{v \in C} |r_{vi} - \mu_v|, because the prediction is μu\mu_u plus a weighted mean of the values ±(rvi−μv)\pm (r_{vi} - \mu_v) with the weights ∣wv∣/D|w_v| / D. 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: IvI_v is the set of items that user vv rated, μv\mu_v is the mean of the ratings of vv, Iuv=Iu∩IvI_{uv} = I_u \cap I_v, and CC is the set of users left after line L5.

Lemma 1 (range and symmetry). For all users u,vu, v, −1≤w(u,v)≤1-1 \le w(u, v) \le 1 and w(u,v)=w(v,u)w(u, v) = w(v, u).

Proof. If IuvI_{uv} is empty or one of the sums ∑xt2\sum x_t^2, ∑yt2\sum y_t^2 is 0, line L11 returns 0 for both orders of the pair. Else let x=(rut−μu)t∈Iuvx = (r_{ut} - \mu_u)_{t \in I_{uv}} and y=(rvt−μv)t∈Iuvy = (r_{vt} - \mu_v)_{t \in I_{uv}}, two nonzero vectors. Line L12 returns ⟨x,y⟩/(∥x∥ ∥y∥)\langle x, y \rangle / (\lVert x \rVert \, \lVert y \rVert). By the Cauchy-Schwarz inequality ∣⟨x,y⟩∣≤∥x∥ ∥y∥|\langle x, y \rangle| \le \lVert x \rVert \, \lVert y \rVert, so the value is in [−1,1][-1, 1]. Swapping uu and vv swaps xx and yy, and the inner product and the product of the norms do not change. □\square

Lemma 2 (invariance). Let a>0a > 0 and cc be real numbers, and replace every rating rvtr_{vt} of one user vv by arvt+ca r_{vt} + c. Then w(u,v)w(u, v) does not change for any uu.

Proof. The new mean of vv is aμv+ca \mu_v + c, so each centered value rvt−μvr_{vt} - \mu_v becomes a(rvt−μv)a (r_{vt} - \mu_v), and the vector yy of Lemma 1 becomes aya y. The set IuvI_{uv} does not change. If y=0y = 0 then ay=0a y = 0 and line L11 returns 0 before and after. Else ⟨x,ay⟩/(∥x∥ ∥ay∥)=a⟨x,y⟩/(a∥x∥ ∥y∥)\langle x, a y \rangle / (\lVert x \rVert \, \lVert a y \rVert) = a \langle x, y \rangle / (a \lVert x \rVert \, \lVert y \rVert), because a>0a > 0. The case where vv is the first argument follows by Lemma 1. □\square

Theorem 1 (correctness). PREDICT(u,i)(u, i) returns the global mean if uu has no rating, μu\mu_u if ∑v∈C∣w(u,v)∣=0\sum_{v \in C} |w(u, v)| = 0, and

r^ui=μu+∑v∈Cw(u,v) (rvi−μv)∑v∈C∣w(u,v)∣\hat r_{ui} = \mu_u + \frac{\sum_{v \in C} w(u, v)\,(r_{vi} - \mu_v)}{\sum_{v \in C} |w(u, v)|}

otherwise, where C=Ui∖{u}C = U_i \setminus \{u\} if no kk is given, and CC is the set of the kk users of Ui∖{u}U_i \setminus \{u\} that come first in the order of decreasing weight, ties broken by the smaller id, if kk is given.

Proof. Line L1 handles a user with no rating. Line L2 sets C=Ui∖{u}C = U_i \setminus \{u\}, and line L3 stores wv=w(u,v)w_v = w(u, v) for each v∈Cv \in C, by the definition of WEIGHT in lines L9 to L12. Lines L4 and L5 replace CC by the first kk users in the stated order when kk is given, and leave it unchanged otherwise. Line L6 computes D=∑v∈C∣wv∣D = \sum_{v \in C} |w_v|. If D=0D = 0, line L7 returns μu\mu_u. Else line L8 returns the stated expression. Each v∈Cv \in C is in UiU_i, so rvir_{vi} is known, and each vv rated at least ii, so μv\mu_v is defined. □\square

Theorem 2 (range of the prediction). If D>0D > 0 then

∣r^ui−μu∣≤max⁡v∈C∣rvi−μv∣.|\hat r_{ui} - \mu_u| \le \max_{v \in C} |r_{vi} - \mu_v|.

Proof. Let dv=rvi−μvd_v = r_{vi} - \mu_v and αv=∣wv∣/D\alpha_v = |w_v| / D. Then αv≥0\alpha_v \ge 0 and ∑v∈Cαv=1\sum_{v \in C} \alpha_v = 1. Write wv=∣wv∣σvw_v = |w_v| \sigma_v with σv∈{−1,1}\sigma_v \in \{-1, 1\} (any choice when wv=0w_v = 0). Then

r^ui−μu=∑v∈Cαv (σvdv),\hat r_{ui} - \mu_u = \sum_{v \in C} \alpha_v \, (\sigma_v d_v),

a convex combination of the numbers σvdv\sigma_v d_v, each in [−∣dv∣,∣dv∣][-|d_v|, |d_v|]. A convex combination lies between the smallest and the largest of its terms. □\square

The bound cannot be improved to the rating scale. In the toy matrix of the page, μu4=2\mu_{u_4} = 2 and the prediction for (u4,i1)(u_4, i_1) is 2−3.288/2.868≈0.8542 - 3.288 / 2.868 \approx 0.854, below the smallest rating 1.

Corollary 3 (shift of another user). If every rating of one user v≠uv \ne u is shifted by a constant cc, then r^ui\hat r_{ui} does not change for any item ii. If every rating of uu is shifted by cc, then each r^ui\hat r_{ui} increases by cc.

Proof. By Lemma 2 with a=1a = 1, no weight changes, so the set CC chosen in line L5 is the same. A shift of vv changes rvir_{vi} and μv\mu_v by the same cc, so dvd_v does not change, and μu\mu_u does not change. A shift of uu changes μu\mu_u by cc and no dvd_v with v≠uv \ne u; the global mean of line L1 is not used, since uu has ratings. □\square

Complexity

The model is the word RAM with the ratings of each user in a hash table, so a lookup rvtr_{vt} costs O(1)O(1) expected time. Let nu=∣Iu∣n_u = |I_u| and s=∣K∣s = |K|.

  • One weight. WEIGHT(u,v)(u, v) scans the items of uu and looks each one up in the table of vv: O(nu)O(n_u) time, or O(min⁡(nu,nv))O(\min(n_u, n_v)) when it scans the shorter list.
  • One prediction. Line L3 computes ∣Ui∣≤m|U_i| \le m weights, so PREDICT costs O(∑v∈Uimin⁡(nu,nv))⊆O(mn)O(\sum_{v \in U_i} \min(n_u, n_v)) \subseteq O(m n). Line L5 is top-k selection, O(∣Ui∣log⁡k)O(|U_i| \log k) with a heap. The extra space is O(m)O(m) for the weights.
  • All weights in advance. A table of all (m2)\binom{m}{2} weights costs O(m2)O(m^2) space and O(ms)O(m s) time, since each pair (u,v)(u, v) costs at most O(nu)O(n_u) and ∑v∑unu=ms\sum_v \sum_u n_u = m s. 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 tt the weight is the sign of (rut−μu)(rvt−μv)(r_{ut} - \mu_u)(r_{vt} - \mu_v), so it is −1-1, 00 or 11.

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 kk most similar users, or the users with ww 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 rvi−μvr_{vi} - \mu_v by the standard deviation of vv and multiply the result by the standard deviation of uu.
  • 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, u2u_2 has the mean 11/3 on the items i1,i2,i4i_1, i_2, i_4, and the weight of u1u_1 and u2u_2 becomes 16/364≈0.83916/\sqrt{364} \approx 0.839 in place of 0.837.
  • Division by the plain sum of weights. Dividing by ∑wv\sum w_v in place of ∑∣wv∣\sum |w_v| 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 (u,i)(u, i) is chosen among the users who rated ii. Choosing the kk most similar users first and then dropping those who did not rate ii often leaves too few or no neighbors.
  • Zero weight users in the denominator. A user with w=0w = 0 adds nothing to either sum, so it is harmless; a missing guard for D=0D = 0 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.

recs.pyI0RawGitHub
# 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

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

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