Algorithm Search⌘K

Algorithmcore

Slope One

Also called weighted Slope One.

Predicts a rating from the average rating difference between each pair of items, a simple scheme that updates online.

Time
O(d) worst
Space
O(n^2) extra
Where
d = the number of items rated by the user; n = the number of items; s = the number of known ratings
Properties
deterministicexactonlineiterative
Origin
Daniel Lemire, Anna Maclachlan, 2005

Slope One predicts the rating of a user uu for an item jj from the average difference between the ratings of jj and of each other item ii, taken over the users who rated both: each item ii that uu rated gives the guess rui+dev⁡(j,i)r_{ui} + \operatorname{dev}(j, i), and the prediction is the mean of these guesses, or in Weighted Slope One their mean weighted by the number of users behind each difference. Lemire and Maclachlan published it in 2005. Like item-based collaborative filtering it works on pairs of items, but it stores a fitted offset in place of a similarity, so it needs no similarity measure and no neighborhood size, and a new rating updates the model in time linear in the number of items its user rated.

In plain words

Suppose that people who saw two films rated the second one, on average, half a point higher than the first. If you gave the first film a 3, a fair guess for the second is 3.5. Each film that you rated gives one such guess for the target film. Slope One takes the average of all these guesses.

Some guesses rest on many people and some on only one or two. The weighted version gives each guess a weight equal to the number of people behind its average difference, so guesses from well-known pairs count more.

The model is a table of sums and counts, one entry for each pair of films. A new rating only adds to the entries of the pairs it forms with the other films of its user.

The problem

The input is a set KK of known ratings over mm users and nn items, and a pair (u,j)(u, j) to predict. Let IuI_u be the set of items that uu rated. For items j≠ij \ne i, let S(j,i)S(j, i) be the set of users who rated both, c(j,i)=∣S(j,i)∣c(j, i) = |S(j, i)|, and, when c(j,i)>0,c(j, i) > 0,

dev⁡(j,i)=1c(j,i)∑w∈S(j,i)(rwj−rwi).\operatorname{dev}(j, i) = \frac{1}{c(j, i)} \sum_{w \in S(j, i)} (r_{wj} - r_{wi}).

Let Rj={i∈Iu:i≠j, c(j,i)>0}R_j = \{ i \in I_u : i \ne j,\ c(j, i) > 0 \}. Slope One and Weighted Slope One predict

r^uj=1∣Rj∣∑i∈Rj(dev⁡(j,i)+rui),r^uj w=∑i∈Rj(dev⁡(j,i)+rui) c(j,i)∑i∈Rjc(j,i).\hat r_{uj} = \frac{1}{|R_j|} \sum_{i \in R_j} \bigl(\operatorname{dev}(j, i) + r_{ui}\bigr), \qquad \hat r^{\,w}_{uj} = \frac{\sum_{i \in R_j} \bigl(\operatorname{dev}(j, i) + r_{ui}\bigr)\, c(j, i)}{\sum_{i \in R_j} c(j, i)}.

When RjR_j is empty, the paper gives no rule; this page returns the mean of uu, or the mean of all ratings if uu has none. The name comes from the predictor f(x)=x+bf(x) = x + b of the rating of jj from the rating of ii: a line of slope one. For the pairs (rwi,rwj)(r_{wi}, r_{wj}) with w∈S(j,i)w \in S(j, i), the offset bb that minimizes ∑w(rwi+b−rwj)2\sum_w (r_{wi} + b - r_{wj})^2 is dev⁡(j,i)\operatorname{dev}(j, i) (Lemire and Maclachlan, Section 3.4; proof in proofs/correctness.md). It is linear regression with the slope fixed to 1.

The algorithm

The model is two tables over ordered pairs of items, diff(j,i)=∑w∈S(j,i)(rwj−rwi)\mathit{diff}(j, i) = \sum_{w \in S(j, i)} (r_{wj} - r_{wi}) and count(j,i)=c(j,i)\mathit{count}(j, i) = c(j, i), plus the ratings of each user.

  1. ADD(u, i, v) ▷ the new rating r_ui = v
  2. 1if u already rated i then REMOVE(u, i)
  3. 2for each item j that u rated do
  4. 3diff(i, j) ← diff(i, j) + (v - r_uj); diff(j, i) ← diff(j, i) + (r_uj - v)
  5. 4count(i, j) ← count(i, j) + 1; count(j, i) ← count(j, i) + 1
  6. 5store r_ui ← v
  7. PREDICT(u, j, weighted)
  8. 6R ← the items i ≠ j that u rated with count(j, i) > 0
  9. 7if R is empty then return the mean of u (the global mean if u has no rating)
  10. 8for each i in R do g_i ← diff(j, i) / count(j, i) + r_ui; c_i ← count(j, i) if weighted, else 1
  11. 9return Σ_{i ∈ R} c_i g_i / Σ_{i ∈ R} c_i

REMOVE(u,i)(u, i) deletes the stored rating v=ruiv = r_{ui} and runs lines L2 to L4 with the signs reversed; an entry whose count reaches 0 is deleted. A batch build is a call of ADD for each rating.

Example

The toy rating matrix of this group:

i1i_1 i2i_2 i3i_3 i4i_4
u1u_1 5 4 - 1
u2u_2 4 5 4 2
u3u_3 1 2 2 5
u4u_4 - 1 1 4

Predict ru1i3r_{u_1 i_3}. User u1u_1 rated i1i_1, i2i_2 and i4i_4.

ii users in S(i3,i)S(i_3, i) differences rwi3−rwir_{w i_3} - r_{w i} cc dev⁡(i3,i)\operatorname{dev}(i_3, i) guess dev⁡+ru1i\operatorname{dev} + r_{u_1 i}
i1i_1 u2,u3u_2, u_3 0, 1 2 1/2 11/2
i2i_2 u2,u3,u4u_2, u_3, u_4 −1-1, 0, 0 3 −1/3-1/3 11/3
i4i_4 u2,u3,u4u_2, u_3, u_4 2, −3-3, −3-3 3 −4/3-4/3 −1/3-1/3

Slope One gives (11/2+11/3−1/3)/3=53/18≈2.944(11/2 + 11/3 - 1/3) / 3 = 53/18 \approx 2.944. Weighted Slope One gives (2⋅11/2+3⋅11/3−3⋅1/3)/8=21/8=2.625(2 \cdot 11/2 + 3 \cdot 11/3 - 3 \cdot 1/3) / 8 = 21/8 = 2.625. The guess from i4i_4 is below the scale: users rate i3i_3 and i4i_4 in opposite ways, and an offset cannot express that the two ratings move in opposite directions. On the same matrix, user-based collaborative filtering predicts 3.934, because a negative correlation can turn a low rating into evidence for a high one.

An online step: if u1u_1 now rates i3i_3 with 4, line L3 adds 4−54 - 5, 4−44 - 4 and 4−14 - 1 to diff(i3,i1)\mathit{diff}(i_3, i_1), diff(i3,i2)\mathit{diff}(i_3, i_2) and diff(i3,i4)\mathit{diff}(i_3, i_4), and the opposite values to the reverse entries, and line L4 adds 1 to the six counts. Nothing else changes.

Correctness

The proof in proofs/correctness.md shows three facts. First, dev⁡(j,i)\operatorname{dev}(j, i) is the least squares offset of the line of slope one, and dev⁡(j,i)=−dev⁡(i,j)\operatorname{dev}(j, i) = -\operatorname{dev}(i, j). Second, by induction over any sequence of ADD and REMOVE calls, the tables hold diff(j,i)=∑w∈S(j,i)(rwj−rwi)\mathit{diff}(j, i) = \sum_{w \in S(j, i)} (r_{wj} - r_{wi}) and count(j,i)=c(j,i)\mathit{count}(j, i) = c(j, i) for the current ratings, so the result does not depend on the order in which the ratings arrived. Third, PREDICT returns the two formulas, and Weighted Slope One equals the plain mean of the votes rui+rwj−rwir_{ui} + r_{wj} - r_{wi} over all pairs (i,w)(i, w) with i∈Rji \in R_j and w∈S(j,i)w \in S(j, i).

Proof: Slope One keeps exact difference tables under updates and returns the Slope One predictionsfull

The notation is that of the page: IuI_u is the set of items that user uu rated, S(j,i)S(j, i) the set of users who rated both jj and ii, c(j,i)=∣S(j,i)∣c(j, i) = |S(j, i)|, and dev⁡(j,i)\operatorname{dev}(j, i) the mean of rwj−rwir_{wj} - r_{wi} over w∈S(j,i)w \in S(j, i). All statements are about exact arithmetic.

Lemma 1 (the offset of slope one). Let (x1,y1),…,(xc,yc)(x_1, y_1), \ldots, (x_c, y_c) be real pairs with c≥1c \ge 1. The function L(b)=∑t=1c(xt+b−yt)2L(b) = \sum_{t=1}^{c} (x_t + b - y_t)^2 has the unique minimizer b∗=1c∑t=1c(yt−xt)b^* = \frac{1}{c} \sum_{t=1}^{c} (y_t - x_t). With xt=rwix_t = r_{wi} and yt=rwjy_t = r_{wj} for the users w∈S(j,i)w \in S(j, i), b∗=dev⁡(j,i)b^* = \operatorname{dev}(j, i).

Proof. LL is a quadratic polynomial in bb with leading coefficient c>0c > 0. Its derivative is L′(b)=2∑t(xt+b−yt)=2cb−2∑t(yt−xt)L'(b) = 2 \sum_t (x_t + b - y_t) = 2 c b - 2 \sum_t (y_t - x_t), which is zero exactly at b=b∗b = b^*. Since L′′(b)=2c>0L''(b) = 2c > 0, LL is strictly convex, so b∗b^* is its unique minimizer. □\square

Lemma 2 (antisymmetry). S(j,i)=S(i,j)S(j, i) = S(i, j), c(j,i)=c(i,j)c(j, i) = c(i, j) and dev⁡(j,i)=−dev⁡(i,j)\operatorname{dev}(j, i) = -\operatorname{dev}(i, j).

Proof. "Rated both jj and ii" is symmetric in ii and jj, and each term rwj−rwir_{wj} - r_{wi} is the negative of rwi−rwjr_{wi} - r_{wj}. □\square

Lemma 3 (the table invariant). Call the tables exact for a rating set KK if, for every ordered pair of distinct items (j,i)(j, i), an entry exists exactly when c(j,i)>0c(j, i) > 0, and then count(j,i)=c(j,i)\mathit{count}(j, i) = c(j, i) and diff(j,i)=∑w∈S(j,i)(rwj−rwi)\mathit{diff}(j, i) = \sum_{w \in S(j, i)} (r_{wj} - r_{wi}), with SS and cc taken in KK. If the tables are exact for KK, then after ADD(u,i,v)(u, i, v) they are exact for the new rating set, and after REMOVE(u,i)(u, i) they are exact for K∖{(u,i)}K \setminus \{(u, i)\}.

Proof. First let ADD be called with (u,i)∉K(u, i) \notin K, so line L1 does nothing. The new set is K′=K∪{(u,i)}K' = K \cup \{(u, i)\}. A set S(a,b)S(a, b) changes only if uu joins it, which happens exactly for the pairs {a,b}={i,j}\{a, b\} = \{i, j\} with j∈Iuj \in I_u, the items that uu rated before the call. For such a pair, S′(i,j)=S(i,j)∪{u}S'(i, j) = S(i, j) \cup \{u\}, so cc grows by 1 and the sum for (i,j)(i, j) gains the term v−rujv - r_{uj}, and the sum for (j,i)(j, i) gains ruj−vr_{uj} - v. Lines L2 to L4 make exactly these changes, creating an entry with the value 0 first when none exists. No other pair changes, and line L5 stores ruir_{ui}, so the tables are exact for K′K'.

Now let REMOVE(u,i)(u, i) be called with (u,i)∈K(u, i) \in K and v=ruiv = r_{ui}. By the same argument, the sets that change are S(i,j)S(i, j) and S(j,i)S(j, i) for j∈Iu∖{i}j \in I_u \setminus \{i\}, which lose uu. REMOVE subtracts 1 from each such count and the term of uu from each such sum, and deletes the entry when the count becomes 0, which is when SS becomes empty. So the tables are exact for K∖{(u,i)}K \setminus \{(u, i)\}.

Last, let ADD be called with (u,i)∈K(u, i) \in K. Line L1 calls REMOVE, after which the tables are exact for K∖{(u,i)}K \setminus \{(u, i)\}, and the rest of ADD is the first case for this set. □\square

Corollary 4 (order independence). Start from empty tables, which are exact for the empty set. After any sequence of ADD and REMOVE calls, the tables are exact for the current rating set. In particular, they do not depend on the order of the calls.

Proof. Induction on the number of calls, with Lemma 3 for the step. □\square

Theorem 5 (the predictions). If the tables are exact, PREDICT(u,j,false)(u, j, \text{false}) returns the Slope One prediction and PREDICT(u,j,true)(u, j, \text{true}) returns the Weighted Slope One prediction of the page when RjR_j is not empty, and the fallback otherwise. Moreover

r^uj w=1∑i∈Rjc(j,i)∑i∈Rj∑w∈S(j,i)(rui+rwj−rwi),\hat r^{\,w}_{uj} = \frac{1}{\sum_{i \in R_j} c(j, i)} \sum_{i \in R_j} \sum_{w \in S(j, i)} \bigl(r_{ui} + r_{wj} - r_{wi}\bigr),

the plain mean of the votes rui+rwj−rwir_{ui} + r_{wj} - r_{wi} over all pairs (i,w)(i, w) with i∈Rji \in R_j and w∈S(j,i)w \in S(j, i).

Proof. Line L6 forms R={i∈Iu:i≠j,count(j,i)>0}R = \{ i \in I_u : i \ne j, \mathit{count}(j, i) > 0 \}, which is RjR_j because the tables are exact. If it is empty, line L7 returns the fallback. Else line L8 computes gi=diff(j,i)/count(j,i)+rui=dev⁡(j,i)+ruig_i = \mathit{diff}(j, i) / \mathit{count}(j, i) + r_{ui} = \operatorname{dev}(j, i) + r_{ui}, and line L9 returns the mean of the gig_i with weights 1 or c(j,i)c(j, i), which are the two formulas of the page. For the identity, c(j,i) gi=c(j,i) rui+∑w∈S(j,i)(rwj−rwi)=∑w∈S(j,i)(rui+rwj−rwi)c(j, i) \, g_i = c(j, i) \, r_{ui} + \sum_{w \in S(j, i)} (r_{wj} - r_{wi}) = \sum_{w \in S(j, i)} (r_{ui} + r_{wj} - r_{wi}); sum over i∈Rji \in R_j and divide by ∑ic(j,i)\sum_i c(j, i). □\square

Proposition 6 (shift of one user). If every rating of one user uu is shifted by a constant aa, no dev⁡\operatorname{dev} changes, and every prediction for uu by either scheme, including the fallback when uu has ratings, increases by aa.

Proof. Each w∈S(j,i)w \in S(j, i) contributes rwj−rwir_{wj} - r_{wi}, and for w=uw = u the shift cancels in the difference. The sets SS do not change, so neither do RjR_j and the counts. Each gi=dev⁡(j,i)+ruig_i = \operatorname{dev}(j, i) + r_{ui} grows by aa, and a weighted mean of numbers that all grow by aa, with fixed weights, grows by aa. The mean of uu also grows by aa. □\square

In floating point, Lemma 3 holds up to rounding: REMOVE subtracts a term that was added before, and the result can differ from the exact sum in the last bits. The tests compare the online tables with a batch build within 10−910^{-9}.

Complexity

The model is the word RAM with hash tables, so each table access costs O(1)O(1) expected time. Let d=∣Iu∣d = |I_u| be the number of items rated by the user of the call.

  • ADD and REMOVE. Lines L2 to L4 do O(1)O(1) work for each item that uu rated: O(d)O(d).
  • PREDICT. Lines L6 to L9 do O(1)O(1) work for each item that uu rated: O(d)O(d), independent of the number of users.
  • Batch build. The ratings of user uu touch each ordered pair of items of IuI_u once, so the build costs O(∑u∣Iu∣2)O(\sum_u |I_u|^2), at most O(ns)O(n s).
  • Space. At most n(n−1)n(n - 1) ordered pairs, O(n2)O(n^2). Since diff(i,j)=−diff(j,i)\mathit{diff}(i, j) = -\mathit{diff}(j, i) and the counts are symmetric, half of the entries are enough, n(n−1)/2n(n-1)/2 pairs. Only pairs with a common user are stored, so on sparse data the table is often much smaller.

Properties

  • Online. A new rating, a changed rating and a deleted rating cost O(d)O(d) each, and the model after any sequence of updates is the same as the one built from scratch.
  • No parameters. There is no similarity measure, neighborhood size, learning rate or penalty to choose.
  • Additive. Adding a constant to all ratings of one user does not change any dev⁡\operatorname{dev}, and shifts that user's predictions by the same constant, because each guess is ruir_{ui} plus a difference.
  • Dense case. If every item i∈Iui \in I_u has c(j,i)>0c(j, i) > 0 and j∉Iuj \notin I_u, then Rj=IuR_j = I_u and Slope One equals μu+1∣Iu∣∑i∈Iudev⁡(j,i)\mu_u + \frac{1}{|I_u|} \sum_{i \in I_u} \operatorname{dev}(j, i). The paper uses this form as an approximation when most pairs have common users.
  • Blind to the sign of the relation. All lines have slope one. Two items that users rate in opposite ways give a large offset of the wrong kind, as for i4i_4 in the example.

Variants and improvements

  • Weighted Slope One. The weights c(j,i)c(j, i) of the problem section (Section 3.5 of the paper).
  • Bi-Polar Slope One. Section 3.6 splits the items of each user into those rated above and below the user's mean, and computes the differences separately on the liked and on the disliked items, so that a pair is used only when the user's opinion of the two items agrees in kind.
  • Baselines of the paper. PER USER AVERAGE predicts μu\mu_u. BIAS FROM MEAN predicts μu\mu_u plus the average over the users of item jj of their rating of jj minus their mean (Section 3.2). Slope One adds the pairwise item offsets to this idea.
  • Distributed update. The tables are sums, so partial tables from parts of the data add up to the full table.

When to use it

Use it when the model must take new ratings at once, when the system must be easy to build, check and explain ("users who rated this item rated the other one half a point higher"), and when tuning is not possible. The Table 1 of Lemire and Maclachlan reports All But One mean absolute errors, measured on EachMovie and MovieLens with the MovieLens values divided by 4: on EachMovie 0.194 for Bi-Polar, 0.198 for Weighted and 0.200 for plain Slope One, against 0.194 for their Pearson scheme and 0.203 for BIAS FROM MEAN; on MovieLens 0.188 for all three Slope One schemes and 0.190 for Pearson. These are measurements on two data sets, not guarantees. For the best accuracy on large data, factor models such as matrix factorization are the usual choice.

Pitfalls

  • Float drift under updates. REMOVE subtracts in floating point, so after many updates diff\mathit{diff} can differ from the exact sum by rounding. With integer ratings, keep the sums as integers.
  • Updating only one direction. Lines L3 and L4 must update both (i,j)(i, j) and (j,i)(j, i), or keep one triangle and read the other with a minus sign. Mixing the two conventions doubles or cancels the offsets.
  • Including the target item. If uu already rated jj, the pair (j,j)(j, j) must not enter RjR_j; the test i≠ji \ne j in line L6 does this.
  • Empty RjR_j. A user whose items share no rater with jj gets no Slope One prediction. Return a fallback, such as the mean of uu, and do not divide by zero.
  • Opposite items. As in the example, a strongly opposite pair gives guesses outside the scale. Clip the result, or use Bi-Polar Slope One.

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
slope_one.py 101 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/slope-one/. The authors are listed in prov/2RYX1J.jsonl.

"""Slope One and Weighted Slope One (Lemire and Maclachlan 2005).

For two items j and i, S(j, i) is the set of users who rated both, and

    dev(j, i) = sum over S(j, i) of (r_uj - r_ui) / |S(j, i)|.

The tables keep the sum of the differences and the count c(j, i) for
each pair, so a new or removed rating updates them in time linear in the
number of items its user rated. For user u and item j, R_j is the set of
items i != j that u rated with c(j, i) > 0. Slope One predicts

    mean over i in R_j of (dev(j, i) + r_ui)

and Weighted Slope One predicts

    sum over i in R_j of (dev(j, i) + r_ui) c(j, i) / sum of c(j, i).

If R_j is empty, both return the mean of user u, or the mean of all
ratings if u has none.
"""


class SlopeOne:
    def __init__(self):
        self.ratings = {}  # user -> {item: rating}
        self.diff = {}  # (j, i) -> sum of r_uj - r_ui over S(j, i)
        self.count = {}  # (j, i) -> |S(j, i)|
        self.total = 0.0
        self.n = 0

    def add(self, u, i, v):
        """Add the rating v of user u for item i (replaces an old one)."""
        row = self.ratings.setdefault(u, {})
        if i in row:  # @line L1
            self.remove(u, i)
            row = self.ratings.setdefault(u, {})
        for j, w in row.items():  # @line L2
            self.diff[(i, j)] = self.diff.get((i, j), 0.0) + (v - w)  # @line L3
            self.diff[(j, i)] = self.diff.get((j, i), 0.0) + (w - v)
            self.count[(i, j)] = self.count.get((i, j), 0) + 1  # @line L4
            self.count[(j, i)] = self.count.get((j, i), 0) + 1
        row[i] = float(v)  # @line L5
        self.total += v
        self.n += 1

    def remove(self, u, i):
        """Remove the rating of user u for item i."""
        row = self.ratings[u]
        v = row.pop(i)
        for j, w in row.items():
            for key, d in (((i, j), v - w), ((j, i), w - v)):
                c = self.count[key] - 1
                if c == 0:
                    del self.count[key]
                    del self.diff[key]
                else:
                    self.count[key] = c
                    self.diff[key] -= d
        if not row:
            del self.ratings[u]
        self.total -= v
        self.n -= 1

    def dev(self, j, i):
        """The average of r_uj - r_ui over the users who rated both."""
        return self.diff[(j, i)] / self.count[(j, i)]

    def _fallback(self, u):
        row = self.ratings.get(u)
        if row:
            return sum(row.values()) / len(row)
        if self.n == 0:
            raise ValueError("no ratings")
        return self.total / self.n

    def predict(self, u, j, weighted=False):
        row = self.ratings.get(u, {})
        num = den = 0.0
        for i, r in row.items():
            if i == j:  # @line L6
                continue
            c = self.count.get((j, i), 0)
            if c == 0:
                continue
            w = c if weighted else 1  # @line L8
            num += (self.dev(j, i) + r) * w
            den += w
        if den == 0:  # @line L7
            return self._fallback(u)
        return num / den  # @line L9


def fit(train):
    """A SlopeOne model with all ratings of the dict train added."""
    model = SlopeOne()
    for (u, i), v in sorted(train.items()):
        model.add(u, i, v)
    return model
test_slope_one.py 95 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/slope-one/. The authors are listed in prov/2RYX1J.jsonl.

import random
from fractions import Fraction

import recs
from slope_one import SlopeOne, fit

TOL = 1e-9


def closed_form(train, u, j, weighted=False):
    """The Slope One formulas computed from scratch, in exact arithmetic."""
    rows = recs.by_user(train)
    row = rows.get(u, {})
    num = den = Fraction(0)
    for i, r in row.items():
        if i == j:
            continue
        both = [w for w, rw in rows.items() if i in rw and j in rw]
        if not both:
            continue
        dev = sum(Fraction(rows[w][j]) - Fraction(rows[w][i]) for w in both) / len(both)
        c = len(both) if weighted else 1
        num += (dev + Fraction(r)) * c
        den += c
    if den == 0:
        return float(sum(row.values()) / len(row))
    return float(num / den)


def test_toy():
    model = fit(recs.toy())
    assert abs(model.dev(2, 3) - (-4 / 3)) < 1e-12
    # u1 rated items 1, 2, 4: (0.5 + 5) + (-1/3 + 4) + (-4/3 + 1) over 3.
    assert abs(model.predict(0, 2) - 53 / 18) < 1e-12
    # Weighted: counts 2, 3, 3.
    assert abs(model.predict(0, 2, weighted=True) - 2.625) < 1e-12


def test_matches_closed_form():
    for seed in range(6):
        full = recs.planted(9, 7, 2, seed, rounded=True)
        train, hidden = recs.split(full, 0.4, seed)
        model = fit(train)
        for u, j in hidden:
            for weighted in (False, True):
                assert abs(model.predict(u, j, weighted) - closed_form(train, u, j, weighted)) < TOL


def test_incremental_order_and_removal():
    rng = random.Random(4)
    full = recs.planted(8, 6, 2, 9, noise=0.3)
    train, hidden = recs.split(full, 0.3, 9)
    keys = list(train)
    rng.shuffle(keys)
    model = SlopeOne()
    for k in keys:
        model.add(k[0], k[1], train[k])
    for (u, i), v in hidden.items():  # add the hidden ratings, then take them out again
        model.add(u, i, v)
    for u, i in hidden:
        model.remove(u, i)
    first = keys[0]  # replace a rating, then restore it
    model.add(first[0], first[1], 1.0)
    model.add(first[0], first[1], train[first])
    batch = fit(train)
    assert set(model.count) == set(batch.count)
    for key in batch.count:
        assert model.count[key] == batch.count[key]
        assert abs(model.diff[key] - batch.diff[key]) < TOL
    for u, j in hidden:
        assert abs(model.predict(u, j, True) - batch.predict(u, j, True)) < TOL


def test_offset_is_least_squares_fit():
    rng = random.Random(2)
    v = [rng.uniform(1, 5) for _ in range(7)]
    w = [rng.uniform(1, 5) for _ in range(7)]
    b = sum(y - x for x, y in zip(v, w)) / len(v)

    def loss(c):
        return sum((x + c - y) ** 2 for x, y in zip(v, w))

    for d in (1e-3, 0.1, 1.0):
        assert loss(b) < loss(b + d) and loss(b) < loss(b - d)
    # The derivative 2 sum (v + b - w) is zero at b.
    assert abs(sum(x + b - y for x, y in zip(v, w))) < TOL


def test_fallback_to_means():
    model = fit({(0, 0): 4.0, (1, 1): 2.0})
    assert model.predict(0, 1) == 4.0
    assert model.predict(5, 1) == 3.0

History

Lemire and Maclachlan presented Slope One at the SIAM International Conference on Data Mining in 2005, with the aim of predictors that are easy to implement, update on the fly and explain, and that are accurate with little data from a new user. They compared the three schemes with PER USER AVERAGE, BIAS FROM MEAN, adjusted cosine item-based filtering and a Pearson scheme, on EachMovie and MovieLens. The paper reports that the Weighted scheme was used by the music site inDiscover.net in November 2004.

References

  1. Daniel Lemire and Anna Maclachlan, Slope One predictors for online rating-based collaborative filtering, Proceedings of the 2005 SIAM International Conference on Data Mining (SDM 2005), 471-475, Section 3.4 (the Slope One scheme, the average deviation of two items and its least squares derivation), Section 3.5 (Weighted Slope One), Section 3.6 (Bi-Polar Slope One), Section 4 and Table 1 (All But One mean absolute error on EachMovie and MovieLens)
  2. Daniel Lemire and Anna Maclachlan, Slope One predictors for online rating-based collaborative filtering, arXiv preprint cs/0702144, the same paper; Section 3.2 (the baselines Per User Average and Bias From Mean) and Section 3.3 (the Pearson reference scheme)
  3. Charu C. Aggarwal, Recommender Systems, The Textbook, Springer, 2016, Chapter 2 (neighborhood-based collaborative filtering and its item-based forms)

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