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.
- Solves
- Recommendation problem
- 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
- Model
- Word RAM
- Properties
- deterministicexactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Daniel Lemire, Anna Maclachlan, 2005
Slope One predicts the rating of a user for an item from the average difference between the ratings of and of each other item , taken over the users who rated both: each item that rated gives the guess , 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 of known ratings over users and items, and a pair to predict. Let be the set of items that rated. For items , let be the set of users who rated both, , and, when
Let . Slope One and Weighted Slope One predict
When is empty, the paper gives no rule; this page returns the mean of , or the mean of all ratings if has none. The name comes from the predictor of the rating of from the rating of : a line of slope one. For the pairs with , the offset that minimizes is (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, and , plus the ratings of each user.
ADD(u, i, v) ▷ the new rating r_ui = v- 1
if u already rated i then REMOVE(u, i) - 2
for each item j that u rated do - 3
diff(i, j) ← diff(i, j) + (v - r_uj); diff(j, i) ← diff(j, i) + (r_uj - v) - 4
count(i, j) ← count(i, j) + 1; count(j, i) ← count(j, i) + 1 - 5
store r_ui ← v PREDICT(u, j, weighted)- 6
R ← the items i ≠ j that u rated with count(j, i) > 0 - 7
if R is empty then return the mean of u (the global mean if u has no rating) - 8
for each i in R do g_i ← diff(j, i) / count(j, i) + r_ui; c_i ← count(j, i) if weighted, else 1 - 9
return Σ_{i ∈ R} c_i g_i / Σ_{i ∈ R} c_i
REMOVE deletes the stored rating 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:
| 5 | 4 | - | 1 | |
| 4 | 5 | 4 | 2 | |
| 1 | 2 | 2 | 5 | |
| - | 1 | 1 | 4 |
Predict . User rated , and .
| users in | differences | guess | |||
|---|---|---|---|---|---|
| 0, 1 | 2 | 1/2 | 11/2 | ||
| , 0, 0 | 3 | 11/3 | |||
| 2, , | 3 |
Slope One gives . Weighted Slope One gives . The guess from is below the scale: users rate and 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 now rates with 4, line L3 adds , and to , and , 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, is the least squares offset of the line of slope one, and . Second, by induction over any sequence of ADD and REMOVE calls, the tables hold and 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 over all pairs with and .
Proof: Slope One keeps exact difference tables under updates and returns the Slope One predictionsfull
The notation is that of the page: is the set of items that user rated, the set of users who rated both and , , and the mean of over . All statements are about exact arithmetic.
Lemma 1 (the offset of slope one). Let be real pairs with . The function has the unique minimizer . With and for the users , .
Proof. is a quadratic polynomial in with leading coefficient . Its derivative is , which is zero exactly at . Since , is strictly convex, so is its unique minimizer.
Lemma 2 (antisymmetry). , and .
Proof. "Rated both and " is symmetric in and , and each term is the negative of .
Lemma 3 (the table invariant). Call the tables exact for a rating set if, for every ordered pair of distinct items , an entry exists exactly when , and then and , with and taken in . If the tables are exact for , then after ADD they are exact for the new rating set, and after REMOVE they are exact for .
Proof. First let ADD be called with , so line L1 does nothing. The new set is . A set changes only if joins it, which happens exactly for the pairs with , the items that rated before the call. For such a pair, , so grows by 1 and the sum for gains the term , and the sum for gains . 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 , so the tables are exact for .
Now let REMOVE be called with and . By the same argument, the sets that change are and for , which lose . REMOVE subtracts 1 from each such count and the term of from each such sum, and deletes the entry when the count becomes 0, which is when becomes empty. So the tables are exact for .
Last, let ADD be called with . Line L1 calls REMOVE, after which the tables are exact for , and the rest of ADD is the first case for this set.
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.
Theorem 5 (the predictions). If the tables are exact, PREDICT returns the Slope One prediction and PREDICT returns the Weighted Slope One prediction of the page when is not empty, and the fallback otherwise. Moreover
the plain mean of the votes over all pairs with and .
Proof. Line L6 forms , which is because the tables are exact. If it is empty, line L7 returns the fallback. Else line L8 computes , and line L9 returns the mean of the with weights 1 or , which are the two formulas of the page. For the identity, ; sum over and divide by .
Proposition 6 (shift of one user). If every rating of one user is shifted by a constant , no changes, and every prediction for by either scheme, including the fallback when has ratings, increases by .
Proof. Each contributes , and for the shift cancels in the difference. The sets do not change, so neither do and the counts. Each grows by , and a weighted mean of numbers that all grow by , with fixed weights, grows by . The mean of also grows by .
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 .
Complexity
The model is the word RAM with hash tables, so each table access costs expected time. Let be the number of items rated by the user of the call.
- ADD and REMOVE. Lines L2 to L4 do work for each item that rated: .
- PREDICT. Lines L6 to L9 do work for each item that rated: , independent of the number of users.
- Batch build. The ratings of user touch each ordered pair of items of once, so the build costs , at most .
- Space. At most ordered pairs, . Since and the counts are symmetric, half of the entries are enough, 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 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 , and shifts that user's predictions by the same constant, because each guess is plus a difference.
- Dense case. If every item has and , then and Slope One equals . 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 in the example.
Variants and improvements
- Weighted Slope One. The weights 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 . BIAS FROM MEAN predicts plus the average over the users of item of their rating of 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 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 and , 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 already rated , the pair must not enter ; the test in line L6 does this.
- Empty . A user whose items share no rater with gets no Slope One prediction. Return a fallback, such as the mean of , 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.
# 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
- 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)
- 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)
- 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.
| 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 2RYX1J Edit this page History Report an error Markdown