Algorithmresearch
Sparse linear method for recommendation
Also called SLIM.
Learns a sparse item-item weight matrix with zero diagonal by elastic-net regression of the interaction matrix on itself.
- Solves
- Recommendation problem
- Time
- O(T n s) worst
- Space
- O(n^2 + m) extra
- Where
- T = the number of coordinate descent sweeps per column; m = the number of users; n = the number of items; s = the number of nonzero entries of A
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Xia Ning, George Karypis, 2011
The sparse linear method (SLIM) of Ning and Karypis (2011) recommends items with a learned item-to-item weight matrix . The score of item for user is , a weighted sum of the user's own past items, as in item-based collaborative filtering. The difference is that the weights are not a fixed similarity such as the cosine: they are the solution of an elastic net regression of the user-item matrix on itself, with and a zero diagonal so that an item cannot predict itself. The penalty makes sparse, so scoring stays as cheap as in item kNN.
In plain words
Item kNN says: users who bought this also bought that, and it measures "also" with a fixed formula. SLIM instead asks, for each item, which other items best predict who has it, and it learns the answer from data. It forbids an item from predicting itself, since that would be a trivial perfect fit, and it forbids negative weights.
A penalty pushes most weights to exactly zero, so each item keeps only a few strong neighbors. Each item can be learned on its own, which makes the training easy to split across machines.
The problem
The input is the matrix of users and items, with 0/1 entries for purchases or clicks, or ratings; is column . Given and , SLIM solves
The objective and the constraints split by columns, so this is independent problems,
each a nonnegative elastic net. Without the constraint the problem would have the useless answer close to . The output is , and the recommendation for is the items with the largest entries of among the items has not used.
The algorithm
The page solves each column by cyclic coordinate descent, the standard solver for the elastic net (Friedman, Hastie and Tibshirani, 2010). The step for one coordinate is a soft threshold clipped at zero.
SLIM(A, β, λ, tol)- 1
for each item j do ▷ the columns are independent - 2
w ← 0; e ← a_j ▷ e = a_j - A w, the residual - 3
repeat until no coordinate moves by more than tol in a sweep - 4
for each item k ≠ j with a_k ≠ 0 do - 5
ρ ← a_kᵀ e + ‖a_k‖² w_k - 6
t ← max(0, ρ - λ) / (‖a_k‖² + β) - 7
e ← e - a_k (t - w_k); w_k ← t - 8
column j of W ← w ▷ w_j stayed 0 - 9
return W RECOMMEND(u, N)- 10
return the N items i with a_ui = 0 and the largest (a_uᵀ W)_i
Line L5 is the correlation of with the residual that would remain if were 0. Line L6 shrinks it by , sets it to 0 if it is below , and divides by the curvature. Line L7 keeps the residual current at a cost of one column.
Example
Five users and four items, with :
| 1 | 1 | 0 | 0 | |
| 1 | 1 | 1 | 0 | |
| 0 | 1 | 1 | 0 | |
| 0 | 0 | 1 | 1 | |
| 1 | 0 | 0 | 1 |
For column , . The correlations with the other columns are , and , and the squared norms are 3, 3 and 2. Columns and have no user in common, so they do not interact. The solution has , and . The KKT condition for holds: the residual is , so , which is below , and is optimal.
The full matrix, with the weight of item in the prediction of item , is
| 0 | 1/3 | 0 | 1/9 | |
| 3/7 | 0 | 3/7 | 0 | |
| 0 | 1/3 | 0 | 1/9 | |
| 1/5 | 0 | 1/5 | 0 |
The diagonal is zero, every entry is nonnegative, and 4 of the 12 entries off the diagonal are 0. User has , so the scores are rows plus : . Among the unused items, scores and scores , so SLIM recommends first. The test file checks these numbers.
Correctness
The proof in proofs/correctness.md has four steps. The problem splits into one problem per column. Each column problem is strongly convex on the set because , so it has a unique minimizer, which the KKT conditions characterize: with , every has if and if . Line L6 is the exact minimizer of the objective in one coordinate over , and it lowers the objective by at least times the square of the move. Since the nonsmooth part is a sum of functions of one coordinate each, every limit point of the coordinate descent satisfies the KKT conditions, and the iterates converge to the unique minimizer. The tests check the KKT conditions at the computed solution to , and compare with a brute force that tries every support in exact rational arithmetic.
Proof: SLIM splits into one strongly convex problem per column, and cyclic coordinate descent with the nonnegative soft threshold converges to its unique minimizerfull
The notation is that of the page. is the user-item matrix with columns , and . SLIM minimizes
All statements are about exact arithmetic.
Lemma 1 (columns are independent). , where is column of and
and the constraints are and for each column separately. So is optimal if and only if each column minimizes over .
Proof. Column of is , the squared Frobenius norm is the sum of the squared norms of the columns, and both penalties are sums over the entries. The constraints restrict each column alone.
Fix and write and . On every , so on
a quadratic function. Its Hessian is , which is positive definite since , so is strongly convex on with modulus at least .
Lemma 2 (unique minimizer and its KKT conditions). has a unique minimizer on . A point is if and only if, with , for every
Proof. is closed and convex and is continuous and strongly convex, so its sublevel sets in are bounded, a minimizer exists, and it is unique. is the partial derivative of in , so on . The minimizer of a differentiable convex function over is characterized by for all . Since is a product of the sets for and for , this splits into one condition per coordinate: for , for all , which is the stated pair of conditions; for there is no condition. These are the KKT conditions that the test file checks.
Lemma 3 (the coordinate step is exact). Fix all coordinates but , , with , and let be the residual at the current point. As a function of , is
and its unique minimizer over is , which is line L6. Moreover .
Proof. Let , the residual without coordinate . Then , and expands to the stated with . is a parabola with positive leading coefficient ; its unconstrained minimizer is , and over the minimizer is that value clipped at 0. For the last claim, , and for every by the optimality of on . If , the code skips and keeps ; then is minimized at 0 anyway.
Line L7 updates the residual by , so holds again after the step, and the next step uses the correct .
Theorem 4 (convergence). Let and let be the point after single coordinate steps of lines L4 to L7 in cyclic order. Then does not increase, and .
Proof. Each step stays in , since and coordinate is never changed. By Lemma 3, each step lowers by at least . Since , summing over the steps gives , so the step lengths tend to 0. The iterates lie in the bounded sublevel set , so they have limit points. Let be the limit of a subsequence of points taken at the start of a sweep. Because the steps tend to 0, the points inside the same sweeps converge to as well. Coordinate of the point after its step in that sweep is the clipped value of Lemma 3 at the point before the step, and the clipped value is a continuous function of the point, so in the limit for each with , with computed at . That fixed-point equation says that minimizes in coordinate over , which is exactly the coordinate condition of Lemma 2 at ; for , and . So satisfies the KKT conditions and . Every limit point equals and the sequence is bounded, so the whole sequence converges to .
The step that turns coordinatewise optimality into global optimality uses that the nonsmooth part, plus the constraint , is a sum of functions of one coordinate each. For a nonsmooth term that couples coordinates this step would fail.
The stopping rule. The code stops when no coordinate moves by more than a tolerance in a sweep. Theorem 4 says this happens after finitely many sweeps for any positive tolerance; the error in the KKT conditions at that point is what the tests bound.
Cost. Lines L5 and L7 cost with dense columns, or with sparse columns, so one sweep over a column costs dense or sparse, where is the number of nonzero entries of . All columns cost per sweep.
Complexity
- One coordinate step. Lines L5 and L7 cost with sparse columns.
- One sweep of one column. , since the columns hold nonzero entries in total. With dense columns it is .
- All columns. for sweeps per column, and the columns can run in parallel. Precomputing the Gram matrix once, in time, makes each coordinate step cost instead.
- Space. for the residual of one column, and for in the worst case; a sparse needs space proportional to its nonzero entries.
- Scoring. costs time proportional to the nonzero weights in the rows of the items of .
Properties
- Sparse model. The penalty sets many weights to exactly 0, so is as cheap to apply as an item kNN table.
- Convex. Unlike matrix factorization, each column problem is convex, so the result does not depend on the start.
- Parallel. The column problems are independent.
- Interpretable. Each recommendation is a sum of nonnegative contributions of the user's past items.
Variants and improvements
- fsSLIM. Feature selection: restrict the support of to the columns of the item kNN neighbors of . Each column problem then has a few variables in place of , which cuts the training time.
- Other solvers. Proximal gradient steps, with the proximal operator of plus the constraint, give the same solution. A solver with active sets or warm starts along a path of values speeds up the tuning.
- Ridge only. With and without the sign constraint, the problem has a closed form through , and the zero diagonal can be enforced with a Lagrange multiplier per column. The model is then dense.
When to use it
Use SLIM for top-N recommendation from purchase or click data when the catalog is of moderate size, when fast scoring matters, and when a convex model with no random start is preferred. Ning and Karypis evaluated it on eight data sets with leave-one-out cross-validation, measuring the hit rate HR and the average reciprocal hit rank, and compared it with item kNN and with matrix factorization methods, including the time to learn and to apply each model. Their reported results favor SLIM on their data sets. These are measurements; the method has no guarantee about ranking quality.
Pitfalls
- Forgetting the zero diagonal. Without the minimizer is close to for small penalties, and every user gets their own past items back.
- The scale of . With larger than every , all weights are 0 and SLIM recommends nothing useful. The test file checks this case.
- Dense . For a large catalog, the Gram matrix has up to entries. Use the sparse residual form of lines L5 and L7, or fsSLIM.
- Stopping too early. A loose tolerance leaves small positive weights that the exact solution would set to 0, so the model is less sparse than expected. Check the KKT conditions, not only the change in the objective.
- Ratings as targets. On rating data, holds the ratings, and the regression then fits rating values; the top-N list should still leave out the items the user has rated.
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/sparse-linear-method/. The authors are listed in prov/XKTFZV.jsonl.
"""SLIM, the sparse linear method for top-N recommendation (Ning and Karypis 2011).
A is the m x n user-item matrix (0/1 or counts). SLIM learns an n x n matrix W
with W >= 0 and diag(W) = 0 that minimizes
1/2 |A - A W|_F^2 + beta/2 |W|_F^2 + lam |W|_1.
The problem splits into one elastic net per column j,
min over w >= 0 with w_j = 0 of 1/2 |a_j - A w|^2 + beta/2 |w|^2 + lam sum_k w_k,
solved here by cyclic coordinate descent. The coordinate step for w_k is the
exact minimizer over w_k >= 0 with the other coordinates fixed:
w_k = max(0, a_k . e + |a_k|^2 w_k - lam) / (|a_k|^2 + beta),
where e = a_j - A w is the current residual. The score of item i for user u
is a_u . w_i, the i-th entry of a_u^T W.
"""
Matrix = list[list[float]]
def column(a: Matrix, k: int) -> list[float]:
return [row[k] for row in a]
def dot(x: list[float], y: list[float]) -> float:
return sum(p * q for p, q in zip(x, y))
def column_objective(a: Matrix, j: int, w: list[float], beta: float, lam: float) -> float:
"""1/2 |a_j - A w|^2 + beta/2 |w|^2 + lam |w|_1. Cost O(m n)."""
m, n = len(a), len(a[0])
total = 0.0
for u in range(m):
e = a[u][j] - sum(a[u][k] * w[k] for k in range(n))
total += 0.5 * e * e
return total + 0.5 * beta * dot(w, w) + lam * sum(abs(v) for v in w)
def slim_column(
a: Matrix, j: int, beta: float, lam: float, tol: float = 1e-12, max_sweeps: int = 10000
) -> list[float]:
"""Solve the elastic net of column j by cyclic coordinate descent.
Precondition: beta > 0 and lam >= 0. Stops when no coordinate moves by
more than tol in a sweep. Cost O(m n) per sweep with dense columns.
"""
if beta <= 0.0 or lam < 0.0:
raise ValueError("need beta > 0 and lam >= 0")
m, n = len(a), len(a[0])
cols = [column(a, k) for k in range(n)]
norms = [dot(c, c) for c in cols]
w = [0.0] * n # @line L2
e = cols[j][:]
for _ in range(max_sweeps): # @line L3
moved = 0.0
for k in range(n): # @line L4
if k == j or norms[k] == 0.0:
continue
rho = dot(cols[k], e) + norms[k] * w[k] # @line L5
new = max(0.0, rho - lam) / (norms[k] + beta) # @line L6
d = new - w[k]
if d != 0.0:
for u in range(m): # @line L7
e[u] -= cols[k][u] * d
w[k] = new
moved = max(moved, abs(d))
if moved <= tol:
break
return w # @line L8
def slim(a: Matrix, beta: float, lam: float, tol: float = 1e-12) -> Matrix:
"""The n x n matrix W, one column per item. Cost O(T m n^2) for T sweeps per column."""
n = len(a[0])
cols = [slim_column(a, j, beta, lam, tol) for j in range(n)] # @line L1
return [[cols[j][k] for j in range(n)] for k in range(n)] # @line L9
def scores(a: Matrix, w: Matrix, u: int) -> list[float]:
"""The row a_u^T W. Cost O(n^2)."""
n = len(w)
return [sum(a[u][k] * w[k][i] for k in range(n)) for i in range(n)]
def recommend(a: Matrix, w: Matrix, u: int, k: int) -> list[int]:
"""The k items with the highest score that user u has not used. Cost O(n^2)."""
s = scores(a, w, u) # @line L10
cand = sorted((-s[i], i) for i in range(len(s)) if a[u][i] == 0)
return [i for _, i in cand[:k]]
def kkt_violation(a: Matrix, j: int, w: list[float], beta: float, lam: float) -> float:
"""The largest violation of the KKT conditions of column j.
With g_k = -a_k . (a_j - A w) + beta w_k, the conditions are, for k != j:
g_k + lam = 0 if w_k > 0, and g_k + lam >= 0 if w_k = 0; also w >= 0 and
w_j = 0. Cost O(m n).
"""
m, n = len(a), len(a[0])
e = [a[u][j] - sum(a[u][k] * w[k] for k in range(n)) for u in range(m)]
worst = abs(w[j])
for k in range(n):
if k == j:
continue
worst = max(worst, -w[k])
g = -sum(a[u][k] * e[u] for u in range(m)) + beta * w[k]
if w[k] > 0.0:
worst = max(worst, abs(g + lam))
else:
worst = max(worst, -(g + lam))
return worst
test_sparse_linear_method.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sparse-linear-method/. The authors are listed in prov/XKTFZV.jsonl.
import itertools
import random
from fractions import Fraction
import pytest
import sparse_linear_method as slim
KKT_TOL = 1e-9
REF_TOL = 1e-9
def random_matrix(m: int, n: int, density: float, seed: int) -> list[list[float]]:
rng = random.Random(seed)
return [[1.0 if rng.random() < density else 0.0 for _ in range(n)] for _ in range(m)]
def exact_solve(a, b):
n = len(a)
m = [row[:] + [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 brute_force_column(a, j, beta, lam):
"""The exact minimizer by trying every support, in rational arithmetic.
On a support S the minimizer solves (A_S^T A_S + beta I) w_S = A_S^T a_j - lam 1.
It is the answer if w_S > 0 and the KKT inequality holds off S.
"""
m, n = len(a), len(a[0])
A = [[Fraction(x) for x in row] for row in a]
beta, lam = Fraction(beta), Fraction(lam)
others = [k for k in range(n) if k != j]
found = []
for size in range(len(others) + 1):
for supp in itertools.combinations(others, size):
w = [Fraction(0)] * n
if supp:
g = [[sum(A[u][p] * A[u][q] for u in range(m)) + (beta if p == q else 0) for q in supp] for p in supp]
rhs = [sum(A[u][p] * A[u][j] for u in range(m)) - lam for p in supp]
sol = exact_solve(g, rhs)
if any(v <= 0 for v in sol):
continue
for p, v in zip(supp, sol):
w[p] = v
e = [A[u][j] - sum(A[u][k] * w[k] for k in range(n)) for u in range(m)]
ok = all(-sum(A[u][k] * e[u] for u in range(m)) + lam >= 0 for k in others if k not in supp)
if ok:
found.append(w)
assert len(found) == 1
return [float(v) for v in found[0]]
def test_kkt_conditions_hold_at_the_solution():
for seed in range(6):
a = random_matrix(12, 7, 0.4, seed)
for beta, lam in ((0.5, 0.1), (1.0, 1.0), (0.1, 0.0), (2.0, 3.0)):
for j in range(7):
w = slim.slim_column(a, j, beta, lam)
assert slim.kkt_violation(a, j, w, beta, lam) <= KKT_TOL
def test_matches_brute_force_over_supports():
for seed in range(4):
a = random_matrix(10, 6, 0.45, 100 + seed)
for beta, lam in ((0.5, 0.2), (1.0, 1.5)):
for j in range(6):
w = slim.slim_column(a, j, beta, lam)
ref = brute_force_column(a, j, beta, lam)
for x, y in zip(w, ref):
assert abs(x - y) <= REF_TOL
def test_nonnegative_zero_diagonal_and_sparse():
a = random_matrix(15, 8, 0.35, 42)
w = slim.slim(a, 0.5, 0.5)
for k in range(8):
assert w[k][k] == 0.0
for i in range(8):
assert w[k][i] >= 0.0
big = slim.slim(a, 0.5, 50.0)
assert all(v == 0.0 for row in big for v in row)
def test_coordinate_steps_do_not_increase_the_objective():
a = random_matrix(10, 6, 0.4, 8)
beta, lam = 0.3, 0.2
for j in range(6):
prev = slim.column_objective(a, j, [0.0] * 6, beta, lam)
for sweeps in range(1, 6):
w = slim.slim_column(a, j, beta, lam, tol=-1.0, max_sweeps=sweeps)
cur = slim.column_objective(a, j, w, beta, lam)
assert cur <= prev + 1e-12
prev = cur
def test_page_example():
a = [
[1.0, 1.0, 0.0, 0.0],
[1.0, 1.0, 1.0, 0.0],
[0.0, 1.0, 1.0, 0.0],
[0.0, 0.0, 1.0, 1.0],
[1.0, 0.0, 0.0, 1.0],
]
w = slim.slim(a, 0.5, 0.5)
want = [
[0.0, 1 / 3, 0.0, 1 / 9],
[3 / 7, 0.0, 3 / 7, 0.0],
[0.0, 1 / 3, 0.0, 1 / 9],
[1 / 5, 0.0, 1 / 5, 0.0],
]
for row, ref in zip(w, want):
for x, y in zip(row, ref):
assert abs(x - y) <= REF_TOL
assert slim.recommend(a, w, 0, 2) == [2, 3]
def test_preconditions():
with pytest.raises(ValueError):
slim.slim_column([[1.0, 0.0]], 0, 0.0, 1.0)
History
Ning and Karypis presented SLIM at ICDM 2011 as a way to get the speed of the item-based top-N methods of Deshpande and Karypis together with the quality of learned models. The elastic net is due to Zou and Hastie (2005), and coordinate descent for it was popularized by Friedman, Hastie and Tibshirani (2010).
References
- Xia Ning and George Karypis, SLIM, sparse linear methods for top-N recommender systems, 11th IEEE International Conference on Data Mining (ICDM 2011), 497-506, the SLIM model and its optimization problem with W >= 0 and diag(W) = 0, the split into independent column problems, fsSLIM (feature selection with item kNN), and the leave-one-out evaluation with HR and ARHR on eight data sets
- Jerome Friedman, Trevor Hastie and Robert Tibshirani, Regularization paths for generalized linear models via coordinate descent, Journal of Statistical Software 33(1), 2010, Section 2 (coordinate descent for the elastic net, the soft-thresholding update)
- Trevor Hastie, Robert Tibshirani and Jerome Friedman, The Elements of Statistical Learning, 2nd edition, Springer, 2009, Section 3.4 (shrinkage methods, ridge regression and the lasso)
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 XKTFZV Edit this page History Report an error Markdown