Algorithmadvanced
Weighted matrix factorization for implicit feedback
Also called implicit ALS, Hu-Koren-Volinsky model.
Factorizes binary preferences with confidence weights from counts, using a sum over all cells that ALS evaluates in time linear in the data.
- Solves
- Recommendation problem
- Time
- O(T (s r^2 + (m + n) r^3)) worst
- Space
- O((m + n) r + r^2) extra
- Where
- T = the number of sweeps; m = the number of users; n = the number of items; r = the number of factors; s = the number of nonzero counts
- Model
- Word RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Yifan Hu, Yehuda Koren, Chris Volinsky, 2008
Weighted matrix factorization for implicit feedback, often called implicit ALS, fits user vectors and item vectors so that is close to 1 where a user has used an item and close to 0 elsewhere, with a confidence weight on each cell that grows with the count. It differs from alternating least squares for explicit ratings in what the loss sums over: explicit ALS sums only over the known ratings, while here every one of the cells is a data point, because an empty cell also says something. A direct solve would cost time proportional to in each step; the algebraic identity of Hu, Koren and Volinsky (2008) brings the cost of one sweep down to , linear in the number of nonzero counts.
In plain words
A play count or a click count is not a rating. A user who played a song 30 times probably likes it, and a user who never played a song may dislike it, or may never have heard of it. So the method treats every cell as a guess: "used" means a target of 1 and "not used" a target of 0, and a large count makes the method trust the 1 more.
There are many more empty cells than full ones. The trick is that every empty cell has the same weight, so their total effect is one small matrix per step that is shared by all users. Each user then only pays for the items that user actually used.
The problem
The input is a set of counts for pairs of users and items; every other pair has . Hu, Koren and Volinsky define the preference if and otherwise, and the confidence , with in their experiments. Given and , the method minimizes their Equation 3,
over . Write for the matrix with rows , for the diagonal matrix of the of user , and for the vector of the . With fixed, the best is the weighted ridge regression solution (their Equation 4)
and the item step is the same with the roles exchanged (their Equation 5). The output is a ranked list per user: the unused items with the largest .
The algorithm
IMPLICIT-ALS(counts, r, λ, α, T)- 1
for the s observed pairs: p_ui ← 1, c_ui ← 1 + α r_ui ▷ all other cells have p = 0, c = 1 - 2
Y ← small random n × r matrix; X ← 0 - 3
repeat T times - 4
X ← HALF(users, Y) - 5
Y ← HALF(items, X) - 6
return X, Y HALF(rows, Y) ▷ the vectors y_j of the other side are fixed- 7
G ← YᵀY ▷ once per half step, O(n r^2) - 8
for each row u do - 9
A ← G + λI + Σ_{j: r_uj > 0} (c_uj - 1) y_j y_jᵀ - 10
b ← Σ_{j: r_uj > 0} c_uj y_j - 11
x_u ← the solution of A x = b, by Cholesky decomposition - 12
return the vectors x_u
Line L9 is written as : the diagonal matrix is zero on every item the user did not use. Line L10 is , since on those items too. A row with no counts gets and , so .
Example
Three users, three items, counts
| 2 | 1 | 0 | |
| 0 | 1 | 3 | |
| 1 | 0 | 0 |
with , , one factor () and the start for all items. The confidences of the nonzero cells are : 3 and 2 for , 2 and 4 for , and 2 for . Line L7 gives .
| user | (line L9) | (line L10) | |
|---|---|---|---|
The direct form gives the same numbers. For , , a sum over all three items with weight 1 on the empty cell .
The objective at the start, with , is the sum of the confidences of the nonzero cells plus : . A ridge step lowers by , so after the user step . The item step then gives and . The test file checks these values.
Correctness
The proof in proofs/correctness.md shows that the system of lines L9 and L10 is exactly and , because and on the empty cells. With fixed, splits into one strictly convex quadratic per user, so line L4 returns the unique minimizer over , and line L5 the unique minimizer over . Hence does not increase after each half step, the values of converge, the iterates stay in a bounded set, and every limit point is a stationary point. The factors themselves need not converge, and a stationary point need not be the global minimum; the start is a fixed point.
Proof: The fast solve of implicit ALS equals the full weighted ridge solve, each half step minimizes its block, and the objective does not increasefull
The notation is that of the page. There are users and items. For each pair, is the count, if and otherwise, and with , so for every pair. is the set of items with . The objective is
is the matrix with rows , and is the diagonal matrix with entries . All statements are about exact arithmetic.
Lemma 1 (separation). For fixed , with
Proof. Group the terms of the double sum by user. The term of depends on only through , and so does .
Lemma 2 (one weighted ridge regression). Let and , where is the vector of the . Then is symmetric positive definite and has the unique minimizer .
Proof. Expanding, , since and . For , , because every . So is positive definite, is strictly convex, and its gradient vanishes exactly at , which is therefore the unique minimizer.
Lemma 3 (the fast system is the same system). Let . The matrix and the vector built in lines L7, L9 and L10,
satisfy and .
Proof. . The first sum is . For , , so and the term of in the second sum is zero; only remain. For the vector, for and for , so .
Theorem 4 (the half steps are exact). Line L4 returns the unique minimizer of over , and line L5 returns the unique minimizer of over .
Proof. By Lemma 1, minimizing is the same as minimizing each alone, since the last term does not depend on . By Lemma 3, line L11 solves , and the Cholesky decomposition exists because is positive definite by Lemma 2. So each is the unique minimizer of . For the item step, is symmetric in the roles of users and items: exchange and , and and , in Lemmas 1 to 3.
Corollary 5 (the objective does not increase). Let be the start of line L2, , and let and be the results of lines L4 and L5 in sweep . Then
and the values converge to a limit .
Proof. minimizes , so its value is at most that of . minimizes , so its value is at most that of . The sequence does not increase and is bounded below by 0, so it converges.
Proposition 6 (limit points are stationary). The iterates satisfy in the Frobenius norm, and every limit point of the sequence has and .
Proof. and by Corollary 5, which gives the bound, so limit points exist. Let with . Since minimizes , , and by continuity . For , pass to a further subsequence with . For every , , and in the limit minimizes . By Corollary 5, lies between and , so . Then also attains the minimum of , and by the uniqueness of Lemma 2, , so .
Cost of a sweep. Line L7 costs once per user half step. For user , lines L9 and L10 add outer products, in time, and line L11 costs . Since , the user half step costs , and the item half step costs . One sweep costs , because . The direct system of Lemma 2 would cost for each user, so per half step.
What is not claimed. Proposition 6 does not say that the factors converge, and a stationary point need not be a global minimum: gives , so , then , and the run stays at . Whether the ranking that the factors produce is good is a question of measurement on data, not of this proof.
Complexity
The model is the word RAM with real numbers of fixed size.
- Shared part. Line L7 costs per user half step and per item half step.
- Per row. Lines L9 and L10 cost for a user with nonzero counts, and line L11 costs . Hu, Koren and Volinsky give the total as for the user step.
- One sweep. , and sweeps cost . The paper used about 10 sweeps.
- Without the identity. Forming directly costs per user, so per half step, which is the cost of a dense problem.
- Space. for the factors and for and one system.
Computing exactly costs ; it can be done in with the same trick, but it is not needed to run the method.
Properties
- Monotone. does not increase after each half step, with no step size.
- Dense loss, sparse cost. Every cell enters the loss, yet one sweep costs time linear in .
- Parallel. The users of one half step are independent once is known, and so are the items.
- Local. The problem is not convex in , and the result depends on the start.
- Explainable. Section 5 of the paper writes the score as over the items the user used, with weights from , so a recommendation can be traced to past items.
Variants and improvements
- Log confidence. The paper also proposes (Equation 6), with in its experiments.
- Inexact solves. A few steps of the conjugate gradient method, started from the old , in place of line L11 lower the cost per row when is large. Each such step still does not increase , but the half step no longer minimizes it exactly.
- Pairwise loss. Bayesian personalized ranking fits the same scores with a loss on pairs of a used and an unused item, trained by sampling. Rendle et al. (2009, Section 5.1) contrast the two: the weighted least squares loss fits a score to each cell, while BPR optimizes the order.
- Item models. The sparse linear method learns item-to-item weights from the same 0/1 matrix.
When to use it
Use it when the data is counts or events with no negative signal, such as plays, views or purchases, when the catalog is large, and when the factors must be refit in parallel. Hu, Koren and Volinsky measured it on the TV viewing data of about 300,000 set-top boxes and 17,000 programs with the expected percentile ranking of the watched programs, where 50% is random and lower is better. They report 16.46% for ranking by popularity, 10.74% for an item-item neighborhood model, and 8.35% for the factor model with 200 factors, with the factor model improving as the number of factors grew. As with all recommender results, this is a measurement on one data set, not a proved property of the method.
Pitfalls
- Treating zeros as missing. If the sums run only over the nonzero cells, every target is 1 and fits everything. The empty cells must stay in the loss; the identity of line L9 is how they stay in cheaply.
- Forming directly. It is correct but costs per user, so the method becomes as slow as a dense problem.
- The scale of . The confidence weights and interact, so a new usually needs a new .
- Stopping on the factors. The values of converge, but the factors can keep moving; stop on the change in or on a held-out ranking measure.
- Reading as dislike. The model only gives low confidence to the zero. A held-out evaluation should still count an unused item as unknown, not as a true negative.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/implicit-feedback-als/. The authors are listed in prov/84ZRE0.jsonl.
"""Weighted matrix factorization for implicit feedback (Hu, Koren and Volinsky 2008).
The input is a dict of counts r_ui > 0 for the observed (user, item) pairs.
Every other pair has r_ui = 0. The preference is p_ui = 1 if r_ui > 0, else 0,
and the confidence is c_ui = 1 + alpha r_ui. The objective sums over ALL m n
pairs:
J(X, Y) = sum over u, i of c_ui (p_ui - x_u . y_i)^2
+ lam (sum_u |x_u|^2 + sum_i |y_i|^2).
With Y fixed, the best x_u solves (Y^T C^u Y + lam I) x = Y^T C^u p(u). The fast
solve writes Y^T C^u Y = Y^T Y + Y^T (C^u - I) Y. The matrix C^u - I is zero
outside the items of user u, so after one O(n r^2) computation of Y^T Y per
half step, user u costs O(n_u r^2 + r^3), where n_u is its number of items.
"""
import math
import random
Matrix = list[list[float]]
Counts = dict[tuple[int, int], float]
def cholesky_solve(a: Matrix, b: list[float]) -> list[float]:
"""Solve a x = b. Precondition: a is symmetric positive definite. Cost O(r^3)."""
n = len(a)
low = [[0.0] * n for _ in range(n)]
for j in range(n):
s = a[j][j] - sum(low[j][k] ** 2 for k in range(j))
if s <= 0.0:
raise ValueError("matrix is not positive definite")
low[j][j] = math.sqrt(s)
for i in range(j + 1, n):
t = a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))
low[i][j] = t / low[j][j]
y = [0.0] * n
for i in range(n):
y[i] = (b[i] - sum(low[i][k] * y[k] for k in range(i))) / low[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
x[i] = (y[i] - sum(low[k][i] * x[k] for k in range(i + 1, n))) / low[i][i]
return x
def gram(y: Matrix, r: int) -> Matrix:
"""Y^T Y for the rows y_i of Y. Cost O(n r^2)."""
g = [[0.0] * r for _ in range(r)]
for v in y:
for s in range(r):
for t in range(r):
g[s][t] += v[s] * v[t]
return g
def fast_system(rows: dict[int, float], y: Matrix, g: Matrix, lam: float, alpha: float) -> tuple[Matrix, list[float]]:
"""The system (A, b) of one row from Y^T Y and the observed entries only.
rows maps the index on the other side to the count r_ui > 0. Cost O(n_u r^2).
"""
r = len(g)
a = [[g[s][t] for t in range(r)] for s in range(r)]
for s in range(r):
a[s][s] += lam
b = [0.0] * r
for j, count in rows.items():
c = 1.0 + alpha * count
v = y[j]
for s in range(r):
b[s] += c * v[s] # @line L10
for t in range(r):
a[s][t] += (c - 1.0) * v[s] * v[t] # @line L9
return a, b
def direct_system(rows: dict[int, float], y: Matrix, lam: float, alpha: float) -> tuple[Matrix, list[float]]:
"""The system (Y^T C^u Y + lam I, Y^T C^u p(u)) summed over all n entries. Cost O(n r^2)."""
r = len(y[0])
a = [[0.0] * r for _ in range(r)]
b = [0.0] * r
for j, v in enumerate(y):
count = rows.get(j, 0.0)
c = 1.0 + alpha * count
p = 1.0 if count > 0 else 0.0
for s in range(r):
b[s] += c * p * v[s]
for t in range(r):
a[s][t] += c * v[s] * v[t]
for s in range(r):
a[s][s] += lam
return a, b
def half_step(groups: dict[int, dict[int, float]], count: int, y: Matrix, lam: float, alpha: float) -> Matrix:
"""Solve the weighted ridge problem of each of count rows with the other side y fixed."""
r = len(y[0])
g = gram(y, r) # @line L7
out = []
for k in range(count): # @line L8
a, b = fast_system(groups.get(k, {}), y, g, lam, alpha)
out.append(cholesky_solve(a, b)) # @line L11
return out # @line L12
def objective(counts: Counts, x: Matrix, y: Matrix, lam: float, alpha: float) -> float:
"""J(X, Y) summed over all m n pairs. Cost O(m n r); for tests and small data."""
total = 0.0
for u, xu in enumerate(x):
for i, yi in enumerate(y):
count = counts.get((u, i), 0.0)
c = 1.0 + alpha * count
p = 1.0 if count > 0 else 0.0
e = p - sum(a * b for a, b in zip(xu, yi))
total += c * e * e
total += lam * sum(a * a for row in x for a in row)
total += lam * sum(a * a for row in y for a in row)
return total
def group(counts: Counts) -> tuple[dict[int, dict[int, float]], dict[int, dict[int, float]]]:
"""(by_user, by_item): user -> {item: count} and item -> {user: count}."""
bu: dict[int, dict[int, float]] = {}
bi: dict[int, dict[int, float]] = {}
for (u, i), v in counts.items():
if v <= 0:
raise ValueError("counts must be positive; leave unobserved pairs out")
bu.setdefault(u, {})[i] = v
bi.setdefault(i, {})[u] = v
return bu, bi
def implicit_als(
counts: Counts,
m: int,
n: int,
r: int,
lam: float,
alpha: float,
sweeps: int,
seed: int = 1,
y0: Matrix | None = None,
track: bool = False,
) -> tuple[Matrix, Matrix, list[float]]:
"""Run sweeps of (user half step, item half step).
Precondition: lam > 0, alpha >= 0, counts positive. Cost per sweep
O(s r^2 + (m + n) r^3) for s observed pairs. Returns (X, Y, history);
with track=True, history holds J at the start and after each half step,
which costs O(m n r) each time.
"""
if lam <= 0.0 or alpha < 0.0:
raise ValueError("need lam > 0 and alpha >= 0")
bu, bi = group(counts) # @line L1
rng = random.Random(seed)
if y0 is None:
y = [[rng.gauss(0.0, 0.1) for _ in range(r)] for _ in range(n)] # @line L2
else:
y = [row[:] for row in y0]
x = [[0.0] * r for _ in range(m)]
history = [objective(counts, x, y, lam, alpha)] if track else []
for _ in range(sweeps): # @line L3
x = half_step(bu, m, y, lam, alpha) # @line L4
if track:
history.append(objective(counts, x, y, lam, alpha))
y = half_step(bi, n, x, lam, alpha) # @line L5
if track:
history.append(objective(counts, x, y, lam, alpha))
return x, y, history # @line L6
def recommend(rows: dict[int, float], xu: list[float], y: Matrix, k: int) -> list[int]:
"""The k items with the highest x_u . y_i among the items the user has not used. Cost O(n r + n log n)."""
scored = [(-sum(a * b for a, b in zip(xu, yi)), i) for i, yi in enumerate(y) if i not in rows]
scored.sort()
return [i for _, i in scored[:k]]
test_implicit_feedback_als.py 111 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/implicit-feedback-als/. The authors are listed in prov/84ZRE0.jsonl.
import random
from fractions import Fraction
import pytest
import implicit_feedback_als as ials
TOL = 1e-9
def random_counts(m: int, n: int, density: float, seed: int) -> dict[tuple[int, int], float]:
rng = random.Random(seed)
out = {}
for u in range(m):
for i in range(n):
if rng.random() < density:
out[(u, i)] = float(rng.randint(1, 9))
return out
def exact_solve(a, b):
"""Gaussian elimination in exact rational arithmetic."""
n = len(a)
m = [[Fraction(x) for x in row] + [Fraction(y)] for row, y in zip(a, b)]
for c in range(n):
piv = next(k for k in range(c, n) if m[k][c] != 0)
m[c], m[piv] = m[piv], m[c]
for k in range(n):
if k != c and m[k][c] != 0:
f = m[k][c] / m[c][c]
m[k] = [x - f * y for x, y in zip(m[k], m[c])]
return [m[k][n] / m[k][k] for k in range(n)]
def test_fast_solve_equals_direct_solve():
rng = random.Random(7)
for trial in range(20):
n, r = rng.randint(3, 12), rng.randint(1, 5)
y = [[rng.uniform(-1.0, 1.0) for _ in range(r)] for _ in range(n)]
rows = {i: float(rng.randint(1, 20)) for i in range(n) if rng.random() < 0.4}
lam, alpha = rng.uniform(0.01, 2.0), rng.choice([0.0, 1.0, 10.0, 40.0])
g = ials.gram(y, r)
af, bf = ials.fast_system(rows, y, g, lam, alpha)
ad, bd = ials.direct_system(rows, y, lam, alpha)
for s in range(r):
assert abs(bf[s] - bd[s]) <= TOL * (1 + abs(bd[s]))
for t in range(r):
assert abs(af[s][t] - ad[s][t]) <= TOL * (1 + abs(ad[s][t]))
xf = ials.cholesky_solve(af, bf)
xd = ials.cholesky_solve(ad, bd)
xe = exact_solve(ad, bd)
for s in range(r):
assert abs(xf[s] - xd[s]) <= TOL
assert abs(xd[s] - float(xe[s])) <= TOL
def test_half_step_minimizes_its_block():
counts = random_counts(6, 5, 0.4, 3)
lam, alpha, r = 0.5, 2.0, 2
bu, _ = ials.group(counts)
rng = random.Random(5)
y = [[rng.gauss(0, 1) for _ in range(r)] for _ in range(5)]
x = ials.half_step(bu, 6, y, lam, alpha)
best = ials.objective(counts, x, y, lam, alpha)
for _ in range(50):
moved = [[a + rng.gauss(0, 0.05) for a in row] for row in x]
assert ials.objective(counts, moved, y, lam, alpha) >= best - TOL
def test_objective_does_not_increase_after_each_half_step():
for seed in range(5):
counts = random_counts(9, 7, 0.3, seed)
_, _, hist = ials.implicit_als(counts, 9, 7, 3, 0.1, 5.0, 8, seed=seed, track=True)
assert len(hist) == 17
for a, b in zip(hist, hist[1:]):
assert b <= a + TOL * (1 + abs(a))
def test_page_example():
counts = {(0, 0): 2.0, (0, 1): 1.0, (1, 1): 1.0, (1, 2): 3.0, (2, 0): 1.0}
bu, bi = ials.group(counts)
y = [[1.0], [1.0], [1.0]]
x = ials.half_step(bu, 3, y, 1.0, 1.0)
for got, want in zip(x, [5 / 7, 3 / 4, 2 / 5]):
assert abs(got[0] - want) <= TOL
assert abs(ials.objective(counts, [[0.0]] * 3, y, 1.0, 1.0) - 16.0) <= TOL
assert abs(ials.objective(counts, x, y, 1.0, 1.0) - 499 / 70) <= TOL
y2 = ials.half_step(bi, 3, x, 1.0, 1.0)
for got, want in zip(y2, [0.8622210263539472, 0.8859938875683019, 0.7652662814305795]):
assert abs(got[0] - want) <= TOL
assert abs(ials.objective(counts, x, y2, 1.0, 1.0) - 6.804815546192129) <= TOL
def test_recommend_leaves_out_used_items():
counts = random_counts(8, 10, 0.3, 11)
x, y, _ = ials.implicit_als(counts, 8, 10, 2, 0.1, 10.0, 5)
bu, _ = ials.group(counts)
rows = bu.get(0, {})
top = ials.recommend(rows, x[0], y, 3)
assert len(top) == min(3, 10 - len(rows))
assert not set(top) & set(rows)
def test_preconditions():
with pytest.raises(ValueError):
ials.implicit_als({(0, 0): 1.0}, 1, 1, 1, 0.0, 1.0, 1)
with pytest.raises(ValueError):
ials.implicit_als({(0, 0): 0.0}, 1, 1, 1, 1.0, 1.0, 1)
History
Hu, Koren and Volinsky presented the model at ICDM 2008, working with TV viewing data, where only watching time was recorded. The same conference had the one-class collaborative filtering paper of Pan, Zhou, Cao, Liu, Lukose, Scholz and Yang (ICDM 2008, 502-511), which also put weights on the missing cells. Rendle et al. (2009) compared both of these with their pairwise BPR loss, and Koren, Bell and Volinsky (2009) described confidence levels for implicit inputs in their survey of matrix factorization.
References
- Yifan Hu, Yehuda Koren and Chris Volinsky, Collaborative filtering for implicit feedback datasets, Eighth IEEE International Conference on Data Mining (ICDM 2008), 263-272, Section 4 (Equation 3 for the cost, Equation 4 for the user step with the Y^T Y identity and its cost, Equation 5 for the item step, Equation 6 for the log scaling of the confidence), Section 5 (explaining recommendations), Section 6 (expected percentile ranking on the TV data)
- Yehuda Koren, Robert Bell and Chris Volinsky, Matrix factorization techniques for recommender systems, IEEE Computer 42(8), 30-37, 2009, sections Learning algorithms and Inputs with varying confidence levels
- Steffen Rendle, Christoph Freudenthaler, Zeno Gantner and Lars Schmidt-Thieme, BPR, Bayesian personalized ranking from implicit feedback, Proceedings of the 25th Conference on Uncertainty in Artificial Intelligence (UAI 2009), Section 5.1 (relation to weighted regularized matrix factorization)
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 84ZRE0 Edit this page History Report an error Markdown