Algorithm Search⌘K

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.

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
Properties
deterministicnot exactofflineiterative
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 WW. The score of item ii for user uu is a~ui=au⊤wi\tilde a_{ui} = a_u^\top w_i, 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 AA on itself, with W≥0W \ge 0 and a zero diagonal so that an item cannot predict itself. The ℓ1\ell_1 penalty makes WW 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 m×nm \times n matrix AA of users and items, with 0/1 entries for purchases or clicks, or ratings; aja_j is column jj. Given β>0\beta > 0 and λ≥0\lambda \ge 0, SLIM solves

min⁡W  12∥A−AW∥F2+β2∥W∥F2+λ∥W∥1subject to W≥0,  diag⁡(W)=0.\min_{W} \; \tfrac12 \lVert A - A W \rVert_F^2 + \tfrac{\beta}{2} \lVert W \rVert_F^2 + \lambda \lVert W \rVert_1 \quad \text{subject to } W \ge 0, \; \operatorname{diag}(W) = 0.

The objective and the constraints split by columns, so this is nn independent problems,

min⁡wj  12∥aj−Awj∥2+β2∥wj∥2+λ∥wj∥1subject to wj≥0,  wjj=0,\min_{w_j} \; \tfrac12 \lVert a_j - A w_j \rVert^2 + \tfrac{\beta}{2} \lVert w_j \rVert^2 + \lambda \lVert w_j \rVert_1 \quad \text{subject to } w_j \ge 0, \; w_{jj} = 0,

each a nonnegative elastic net. Without the constraint wjj=0w_{jj} = 0 the problem would have the useless answer close to W=IW = I. The output is WW, and the recommendation for uu is the items with the largest entries of au⊤Wa_u^\top W among the items uu 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.

  1. SLIM(A, β, λ, tol)
  2. 1for each item j do ▷ the columns are independent
  3. 2w ← 0; e ← a_j ▷ e = a_j - A w, the residual
  4. 3repeat until no coordinate moves by more than tol in a sweep
  5. 4for each item k ≠ j with a_k ≠ 0 do
  6. 5ρ ← a_kᵀ e + ‖a_k‖² w_k
  7. 6t ← max(0, ρ - λ) / (‖a_k‖² + β)
  8. 7e ← e - a_k (t - w_k); w_k ← t
  9. 8column j of W ← w ▷ w_j stayed 0
  10. 9return W
  11. RECOMMEND(u, N)
  12. 10return the N items i with a_ui = 0 and the largest (a_uᵀ W)_i

Line L5 is the correlation of aka_k with the residual that would remain if wkw_k were 0. Line L6 shrinks it by λ\lambda, sets it to 0 if it is below λ\lambda, and divides by the curvature. Line L7 keeps the residual current at a cost of one column.

Example

Five users and four items, with β=λ=0.5\beta = \lambda = 0.5:

i1i_1 i2i_2 i3i_3 i4i_4
u1u_1 1 1 0 0
u2u_2 1 1 1 0
u3u_3 0 1 1 0
u4u_4 0 0 1 1
u5u_5 1 0 0 1

For column i1i_1, a1=(1,1,0,0,1)a_1 = (1, 1, 0, 0, 1). The correlations with the other columns are a2⊤a1=2a_2^\top a_1 = 2, a3⊤a1=1a_3^\top a_1 = 1 and a4⊤a1=1a_4^\top a_1 = 1, and the squared norms are 3, 3 and 2. Columns a2a_2 and a4a_4 have no user in common, so they do not interact. The solution has w21=(2−0.5)/(3+0.5)=3/7w_{21} = (2 - 0.5) / (3 + 0.5) = 3/7, w41=(1−0.5)/(2+0.5)=1/5w_{41} = (1 - 0.5) / (2 + 0.5) = 1/5 and w31=0w_{31} = 0. The KKT condition for i3i_3 holds: the residual is e=(4/7,4/7,−3/7,−1/5,4/5)e = (4/7, 4/7, -3/7, -1/5, 4/5), so a3⊤e=−2/35a_3^\top e = -2/35, which is below λ\lambda, and w31=0w_{31} = 0 is optimal.

The full matrix, with WkjW_{kj} the weight of item kk in the prediction of item jj, is

i1i_1 i2i_2 i3i_3 i4i_4
i1i_1 0 1/3 0 1/9
i2i_2 3/7 0 3/7 0
i3i_3 0 1/3 0 1/9
i4i_4 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 u1u_1 has au1=(1,1,0,0)a_{u_1} = (1, 1, 0, 0), so the scores are rows i1i_1 plus i2i_2: (3/7,1/3,3/7,1/9)(3/7, 1/3, 3/7, 1/9). Among the unused items, i3i_3 scores 3/73/7 and i4i_4 scores 1/91/9, so SLIM recommends i3i_3 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 {w≥0,wj=0}\{w \ge 0, w_j = 0\} because β>0\beta > 0, so it has a unique minimizer, which the KKT conditions characterize: with gk=−ak⊤(aj−Aw)+βwkg_k = -a_k^\top(a_j - A w) + \beta w_k, every k≠jk \ne j has gk+λ=0g_k + \lambda = 0 if wk>0w_k > 0 and gk+λ≥0g_k + \lambda \ge 0 if wk=0w_k = 0. Line L6 is the exact minimizer of the objective in one coordinate over wk≥0w_k \ge 0, and it lowers the objective by at least β2\frac{\beta}{2} 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 10−910^{-9}, 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. AA is the m×nm \times n user-item matrix with columns a1,…,ana_1, \dots, a_n, β>0\beta > 0 and λ≥0\lambda \ge 0. SLIM minimizes

F(W)=12∥A−AW∥F2+β2∥W∥F2+λ∥W∥1subject to W≥0,  diag⁡(W)=0.F(W) = \tfrac12 \lVert A - A W \rVert_F^2 + \tfrac{\beta}{2} \lVert W \rVert_F^2 + \lambda \lVert W \rVert_1 \quad \text{subject to } W \ge 0, \; \operatorname{diag}(W) = 0.

All statements are about exact arithmetic.

Lemma 1 (columns are independent). F(W)=∑jfj(wj)F(W) = \sum_j f_j(w_j), where wjw_j is column jj of WW and

fj(w)=12∥aj−Aw∥2+β2∥w∥2+λ∑k∣wk∣,f_j(w) = \tfrac12 \lVert a_j - A w \rVert^2 + \tfrac{\beta}{2} \lVert w \rVert^2 + \lambda \sum_k |w_k|,

and the constraints are w≥0w \ge 0 and wj=0w_j = 0 for each column separately. So WW is optimal if and only if each column wjw_j minimizes fjf_j over Cj={w∈Rn:w≥0,wj=0}C_j = \{w \in \mathbb{R}^n : w \ge 0, w_j = 0\}.

Proof. Column jj of A−AWA - AW is aj−Awja_j - A w_j, 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. □\square

Fix jj and write f=fjf = f_j and C=CjC = C_j. On CC every ∣wk∣=wk|w_k| = w_k, so on CC

f(w)=h(w)+λ1⊤w,h(w)=12∥aj−Aw∥2+β2∥w∥2,f(w) = h(w) + \lambda \mathbf{1}^\top w, \qquad h(w) = \tfrac12 \lVert a_j - A w \rVert^2 + \tfrac{\beta}{2} \lVert w \rVert^2,

a quadratic function. Its Hessian is A⊤A+βIA^\top A + \beta I, which is positive definite since β>0\beta > 0, so ff is strongly convex on CC with modulus at least β\beta.

Lemma 2 (unique minimizer and its KKT conditions). ff has a unique minimizer w∗w^* on CC. A point w∈Cw \in C is w∗w^* if and only if, with gk=−ak⊤(aj−Aw)+βwkg_k = -a_k^\top (a_j - A w) + \beta w_k, for every k≠jk \ne j

gk+λ=0 if wk>0,gk+λ≥0 if wk=0.g_k + \lambda = 0 \text{ if } w_k > 0, \qquad g_k + \lambda \ge 0 \text{ if } w_k = 0.

Proof. CC is closed and convex and ff is continuous and strongly convex, so its sublevel sets in CC are bounded, a minimizer exists, and it is unique. gkg_k is the partial derivative of hh in wkw_k, so ∇f=g+λ1\nabla f = g + \lambda \mathbf{1} on CC. The minimizer of a differentiable convex function over CC is characterized by ∇f(w)⊤(v−w)≥0\nabla f(w)^\top (v - w) \ge 0 for all v∈Cv \in C. Since CC is a product of the sets [0,∞)[0, \infty) for k≠jk \ne j and {0}\{0\} for k=jk = j, this splits into one condition per coordinate: for k≠jk \ne j, (gk+λ)(vk−wk)≥0(g_k + \lambda)(v_k - w_k) \ge 0 for all vk≥0v_k \ge 0, which is the stated pair of conditions; for k=jk = j there is no condition. These are the KKT conditions that the test file checks. □\square

Lemma 3 (the coordinate step is exact). Fix all coordinates but wkw_k, k≠jk \ne j, with ∥ak∥>0\lVert a_k \rVert > 0, and let e=aj−Awe = a_j - A w be the residual at the current point. As a function of t=wk≥0t = w_k \ge 0, ff is

ϕ(t)=12(∥ak∥2+β)t2−ρ t+λt+const,ρ=ak⊤e+∥ak∥2wk,\phi(t) = \tfrac12 (\lVert a_k \rVert^2 + \beta) t^2 - \rho\, t + \lambda t + \text{const}, \qquad \rho = a_k^\top e + \lVert a_k \rVert^2 w_k,

and its unique minimizer over t≥0t \ge 0 is t∗=max⁡(0,ρ−λ)/(∥ak∥2+β)t^* = \max(0, \rho - \lambda) / (\lVert a_k \rVert^2 + \beta), which is line L6. Moreover ϕ(wk)−ϕ(t∗)≥12(∥ak∥2+β)(wk−t∗)2\phi(w_k) - \phi(t^*) \ge \frac12 (\lVert a_k \rVert^2 + \beta) (w_k - t^*)^2.

Proof. Let e0=e+akwke_0 = e + a_k w_k, the residual without coordinate kk. Then aj−Aw=e0−akta_j - A w = e_0 - a_k t, and 12∥e0−akt∥2+β2t2+λt\frac12 \lVert e_0 - a_k t \rVert^2 + \frac{\beta}{2} t^2 + \lambda t expands to the stated ϕ\phi with ρ=ak⊤e0=ak⊤e+∥ak∥2wk\rho = a_k^\top e_0 = a_k^\top e + \lVert a_k \rVert^2 w_k. ϕ\phi is a parabola with positive leading coefficient c=∥ak∥2+βc = \lVert a_k \rVert^2 + \beta; its unconstrained minimizer is (ρ−λ)/c(\rho - \lambda) / c, and over t≥0t \ge 0 the minimizer is that value clipped at 0. For the last claim, ϕ(t)=ϕ(t∗)+ϕ′(t∗)(t−t∗)+c2(t−t∗)2\phi(t) = \phi(t^*) + \phi'(t^*)(t - t^*) + \frac{c}{2} (t - t^*)^2, and ϕ′(t∗)(t−t∗)≥0\phi'(t^*)(t - t^*) \ge 0 for every t≥0t \ge 0 by the optimality of t∗t^* on [0,∞)[0, \infty). If ∥ak∥=0\lVert a_k \rVert = 0, the code skips kk and keeps wk=0w_k = 0; then ϕ(t)=β2t2+λt+const\phi(t) = \frac{\beta}{2} t^2 + \lambda t + \text{const} is minimized at 0 anyway. □\square

Line L7 updates the residual by −ak(t∗−wk)-a_k (t^* - w_k), so e=aj−Awe = a_j - A w holds again after the step, and the next step uses the correct ρ\rho.

Theorem 4 (convergence). Let w(0)=0w^{(0)} = 0 and let w(s)w^{(s)} be the point after ss single coordinate steps of lines L4 to L7 in cyclic order. Then f(w(s))f(w^{(s)}) does not increase, and w(s)→w∗w^{(s)} \to w^*.

Proof. Each step stays in CC, since t∗≥0t^* \ge 0 and coordinate jj is never changed. By Lemma 3, each step lowers ff by at least β2∥w(s+1)−w(s)∥2\frac{\beta}{2} \lVert w^{(s+1)} - w^{(s)} \rVert^2. Since f≥0f \ge 0, summing over the steps gives ∑s∥w(s+1)−w(s)∥2≤2f(0)/β<∞\sum_s \lVert w^{(s+1)} - w^{(s)} \rVert^2 \le 2 f(0) / \beta < \infty, so the step lengths tend to 0. The iterates lie in the bounded sublevel set {w∈C:f(w)≤f(0)}\{w \in C : f(w) \le f(0)\}, so they have limit points. Let wˉ\bar w 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 wˉ\bar w as well. Coordinate kk 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 wˉk=max⁡(0,ρˉk−λ)/(∥ak∥2+β)\bar w_k = \max(0, \bar\rho_k - \lambda) / (\lVert a_k \rVert^2 + \beta) for each k≠jk \ne j with ak≠0a_k \ne 0, with ρˉk\bar \rho_k computed at wˉ\bar w. That fixed-point equation says that wˉk\bar w_k minimizes ff in coordinate kk over [0,∞)[0, \infty), which is exactly the coordinate condition of Lemma 2 at wˉ\bar w; for ak=0a_k = 0, wˉk=0\bar w_k = 0 and gk+λ=λ≥0g_k + \lambda = \lambda \ge 0. So wˉ\bar w satisfies the KKT conditions and wˉ=w∗\bar w = w^*. Every limit point equals w∗w^* and the sequence is bounded, so the whole sequence converges to w∗w^*. □\square

The step that turns coordinatewise optimality into global optimality uses that the nonsmooth part, λ∑k∣wk∣\lambda \sum_k |w_k| plus the constraint w∈Cw \in C, 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 O(m)O(m) with dense columns, or O(nnz(ak))O(\text{nnz}(a_k)) with sparse columns, so one sweep over a column costs O(mn)O(m n) dense or O(s)O(s) sparse, where ss is the number of nonzero entries of AA. All nn columns cost O(ns)O(n s) per sweep. ■\blacksquare

Complexity

  • One coordinate step. Lines L5 and L7 cost O(nnz(ak))O(\text{nnz}(a_k)) with sparse columns.
  • One sweep of one column. O(s)O(s), since the columns hold ss nonzero entries in total. With dense columns it is O(mn)O(m n).
  • All columns. O(Tns)O(T n s) for TT sweeps per column, and the nn columns can run in parallel. Precomputing the Gram matrix A⊤AA^\top A once, in O(∑u∣Iu∣2)O(\sum_u |I_u|^2) time, makes each coordinate step cost O(n)O(n) instead.
  • Space. O(m)O(m) for the residual of one column, and O(n2)O(n^2) for WW in the worst case; a sparse WW needs space proportional to its nonzero entries.
  • Scoring. au⊤Wa_u^\top W costs time proportional to the nonzero weights in the rows of the items of uu.

Properties

  • Sparse model. The ℓ1\ell_1 penalty sets many weights to exactly 0, so WW 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 nn 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 wjw_j to the columns of the item kNN neighbors of jj. Each column problem then has a few variables in place of n−1n - 1, which cuts the training time.
  • Other solvers. Proximal gradient steps, with the proximal operator of λ∥w∥1\lambda \lVert w \rVert_1 plus the constraint, give the same solution. A solver with active sets or warm starts along a path of λ\lambda values speeds up the tuning.
  • Ridge only. With λ=0\lambda = 0 and without the sign constraint, the problem has a closed form through (A⊤A+βI)−1(A^\top A + \beta I)^{-1}, 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 =#hits/#users= \#\text{hits} / \#\text{users} 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 wjj=0w_{jj} = 0 the minimizer is close to W=IW = I for small penalties, and every user gets their own past items back.
  • The scale of λ\lambda. With λ\lambda larger than every ak⊤aja_k^\top a_j, all weights are 0 and SLIM recommends nothing useful. The test file checks this case.
  • Dense A⊤AA^\top A. For a large catalog, the Gram matrix has up to n2n^2 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, AA 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.

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

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

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