Algorithm Search⌘K

Algorithmcore

Alternating least squares for matrix factorization

Also called ALS.

Fixes the item factors and solves a ridge regression for each user, then the reverse, so the regularized error never increases from one half step to the next.

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 known ratings
Properties
randomizednot exactofflineiterative
Origin
Yunhong Zhou, Dennis Wilkinson, Robert Schreiber, Rong Pan, 2008

Alternating least squares (ALS) fits the factor model r^ui=pu⊤qi\hat r_{ui} = p_u^\top q_i of matrix factorization by turns. With the item vectors qiq_i fixed, the regularized squared error splits into one ridge regression for each user, which has a closed form; then the user vectors are fixed and each item gets its ridge regression. Each half step solves its subproblem exactly, so the objective never increases, and the solves of one half step are independent of each other, which makes the method easy to run in parallel.

In plain words

Fitting user scores and item scores at the same time is hard, because each one depends on the other. If the item scores were known, the best scores for one user would be a small, standard fitting problem with an exact answer, and each user could be solved alone. ALS pretends that the item scores are known, solves for all users, then pretends that the new user scores are known and solves for all items, and goes back and forth.

Each turn can only make the fit better or keep it the same. The method can still stop at a fit that is not the best one, so the starting point matters.

The problem

The input is a set KK of known ratings of mm users for nn items, s=∣K∣s = |K|, a number of factors rr, and λ>0\lambda > 0. Let IuI_u be the items that user uu rated and UiU_i the users who rated item ii. ALS minimizes

J(P,Q)=∑(u,i)∈K(rui−pu⊤qi)2+λ(∑ucu∥pu∥2+∑ici∥qi∥2)J(P, Q) = \sum_{(u, i) \in K} \bigl(r_{ui} - p_u^\top q_i\bigr)^2 + \lambda \Bigl( \sum_u c_u \lVert p_u \rVert^2 + \sum_i c_i \lVert q_i \rVert^2 \Bigr)

over the user vectors pu∈Rrp_u \in \mathbb{R}^r and the item vectors qi∈Rrq_i \in \mathbb{R}^r. With cu=ci=1c_u = c_i = 1 this is the plain ridge penalty. With cu=∣Iu∣c_u = |I_u| and ci=∣Ui∣c_i = |U_i| it is the weighted lambda regularization of Zhou et al. (ALS-WR, their Equation 5), which is the same as putting the penalty inside the sum over the ratings, as on the matrix factorization page.

With QQ fixed, JJ is a sum over the users of the separate problems min⁡pu∑i∈Iu(rui−pu⊤qi)2+λcu∥pu∥2\min_{p_u} \sum_{i \in I_u} (r_{ui} - p_u^\top q_i)^2 + \lambda c_u \lVert p_u \rVert^2. Each one is a ridge regression with the vectors qiq_i as rows of the design matrix, and its unique solution satisfies the normal equations

(∑i∈Iuqiqi⊤+λcuI)pu=∑i∈Iurui qi.\Bigl( \sum_{i \in I_u} q_i q_i^\top + \lambda c_u I \Bigr) p_u = \sum_{i \in I_u} r_{ui}\, q_i.

The same holds for each item with PP fixed. The problem of the whole JJ is not convex, and without the penalty the best rank rr fit to a partly known matrix is NP-hard already for r=1r = 1 (Gillis and Glineur, 2011). ALS does not try to find the global minimum; its limit points are points where neither block can be improved alone.

The algorithm

  1. ALS(K, r, λ, T)
  2. 1q_i ← small random vectors in R^r for all items; p_u ← 0 for all users
  3. 2repeat T times (or until J changes by less than a tolerance)
  4. 3P ← SOLVE(the users, Q) ▷ one ridge regression per user
  5. 4Q ← SOLVE(the items, P) ▷ one ridge regression per item
  6. 5return P, Q
  7. SOLVE(rows, Y) ▷ the vectors y_j of the other side are fixed
  8. 6for each row x (a user or an item) do
  9. 7if x has no rating then f_x ← 0 and go to the next row
  10. 8A ← Σ_j y_j y_jᵀ + λ c_x I; b ← Σ_j r_xj y_j ▷ sums over the ratings of x
  11. 9f_x ← the solution of A f = b, by Cholesky decomposition
  12. 10return the vectors f_x

The matrix AA of line L8 is symmetric positive definite because λcx>0\lambda c_x > 0, so the Cholesky decomposition of line L9 exists. The rows of one call of SOLVE do not depend on each other and can run on different processors.

Example

Use the toy rating matrix of this group, with one factor (r=1r = 1), λ=1\lambda = 1, the plain penalty, and the start qi=1q_i = 1 for all items:

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

With every qi=1q_i = 1, line L8 gives A=∣Iu∣+1A = |I_u| + 1 and b=∑i∈Iuruib = \sum_{i \in I_u} r_{ui} for each user:

user AA bb pup_u
u1u_1 4 10 5/2
u2u_2 5 15 3
u3u_3 5 10 2
u4u_4 4 6 3/2

Then each item gets qi=∑u∈Uiruipu/(∑u∈Uipu2+1)q_i = \sum_{u \in U_i} r_{ui} p_u / (\sum_{u \in U_i} p_u^2 + 1). For i1i_1, rated by u1u_1, u2u_2 and u3u_3, this is (5⋅5/2+4⋅3+1⋅2)/(25/4+9+4+1)=26.5/20.25=106/81(5 \cdot 5/2 + 4 \cdot 3 + 1 \cdot 2) / (25/4 + 9 + 4 + 1) = 26.5 / 20.25 = 106/81. The four values are q=(106/81,61/45,14/13,49/45)q = (106/81, 61/45, 14/13, 49/45).

The objective goes from J=155+4=159J = 155 + 4 = 159 at the start, where P=0P = 0, to 6060 after the user step and to about 54.952654.9526 after the item step. With one factor and a start of all ones, the model can only say how much each user likes items in general. The toy matrix has two groups of users with opposite tastes, and r=1r = 1 from this start does not separate them.

With the ALS-WR penalty, cu=∣Iu∣c_u = |I_u|, the user step gives pu=b/(2∣Iu∣)p_u = b / (2 |I_u|), so p=(5/3,15/8,5/4,1)p = (5/3, 15/8, 5/4, 1): every user gets half the mean of their ratings, whatever their number. Against the plain step, pu=b/(∣Iu∣+1)p_u = b / (|I_u| + 1), the ratio is (∣Iu∣+1)/(2∣Iu∣)(|I_u| + 1) / (2 |I_u|), which is 2/32/3 for three ratings and 5/85/8 for four, so the users with more ratings are shrunk more in relative terms.

If the start is qi=0q_i = 0 for all items, every bb is 0, so every pu=0p_u = 0, and then every qi=0q_i = 0. The run stays at P=Q=0P = Q = 0 with J=155J = 155, a stationary point that is not a minimum.

Correctness

The proof in proofs/correctness.md shows four facts. First, with QQ fixed, JJ is the sum of the user problems plus a constant, and the matrix of each normal equation is positive definite, so line L3 returns the unique minimizer of JJ over PP; the same holds for line L4. Second, therefore J(Pk+1,Qk)≤J(Pk,Qk)J(P_{k+1}, Q_k) \le J(P_k, Q_k) and J(Pk+1,Qk+1)≤J(Pk+1,Qk)J(P_{k+1}, Q_{k+1}) \le J(P_{k+1}, Q_k), and the values of JJ converge, since they decrease and are at least 0. Third, the iterates stay in a bounded set, and every limit point of the sequence of sweeps is a stationary point of JJ. Fourth, a stationary point need not be a minimum, as the zero start of the example shows. The factors themselves need not converge.

Proof: Each half step of ALS minimizes the objective over one block, the objective values converge, and limit points are stationaryfull

The notation is that of the page. J(P,Q)J(P, Q) is the regularized objective with weights cu,cic_u, c_i, and λ>0\lambda > 0. For the plain penalty cu=ci=1c_u = c_i = 1. For the weighted penalty cu=∣Iu∣c_u = |I_u| and ci=∣Ui∣c_i = |U_i|, and we assume that every user and every item has at least one rating, so that all weights are at least 1 (a user or item with no rating does not enter JJ under this penalty, and line L7 keeps its vector at 0). Let Q0Q_0 be the start of line L1, and let Pk+1P_{k+1} and Qk+1Q_{k+1} be the results of lines L3 and L4 in sweep k+1k + 1. All statements are about exact arithmetic.

Lemma 1 (separation). For fixed QQ,

J(P,Q)=∑ugu(pu)+λ∑ici∥qi∥2,gu(p)=∑i∈Iu(rui−p⊤qi)2+λcu∥p∥2.J(P, Q) = \sum_u g_u(p_u) + \lambda \sum_i c_i \lVert q_i \rVert^2, \qquad g_u(p) = \sum_{i \in I_u} (r_{ui} - p^\top q_i)^2 + \lambda c_u \lVert p \rVert^2.

Proof. Group the terms of the sum over KK by user: the term of (u,i)(u, i) depends on PP only through pup_u, and so does λcu∥pu∥2\lambda c_u \lVert p_u \rVert^2. □\square

Lemma 2 (one ridge regression). Let Au=∑i∈Iuqiqi⊤+λcuIA_u = \sum_{i \in I_u} q_i q_i^\top + \lambda c_u I and bu=∑i∈Iuruiqib_u = \sum_{i \in I_u} r_{ui} q_i. Then AuA_u is symmetric positive definite, and gug_u has the unique minimizer pu∗=Au−1bup_u^* = A_u^{-1} b_u. If IuI_u is empty and the penalty is plain, pu∗=0p_u^* = 0.

Proof. Expanding, gu(p)=p⊤Aup−2bu⊤p+∑i∈Iurui2g_u(p) = p^\top A_u p - 2 b_u^\top p + \sum_{i \in I_u} r_{ui}^2. For x≠0x \ne 0, x⊤Aux=∑i∈Iu(qi⊤x)2+λcu∥x∥2≥λcu∥x∥2>0x^\top A_u x = \sum_{i \in I_u} (q_i^\top x)^2 + \lambda c_u \lVert x \rVert^2 \ge \lambda c_u \lVert x \rVert^2 > 0, so AuA_u is positive definite. A quadratic function with a positive definite matrix is strictly convex, its gradient 2Aup−2bu2 A_u p - 2 b_u is zero exactly at p=Au−1bup = A_u^{-1} b_u, and this point is its unique minimizer. With IuI_u empty, bu=0b_u = 0 and the minimizer is 0. □\square

Theorem 3 (the half steps are exact). Line L3 returns the unique minimizer of J(⋅,Q)J(\cdot, Q) over PP, and line L4 returns the unique minimizer of J(P,⋅)J(P, \cdot) over QQ.

Proof. By Lemma 1, minimizing J(⋅,Q)J(\cdot, Q) is the same as minimizing each gug_u alone, since the last term does not depend on PP. Lines L7 to L9 compute the matrix and the vector of Lemma 2 and solve the system; the Cholesky decomposition exists because AuA_u is positive definite. So each pup_u is the unique minimizer of gug_u, and PP is the unique minimizer of J(⋅,Q)J(\cdot, Q). The argument for the items is the same with the roles of users and items exchanged. □\square

Corollary 4 (monotone values). For every k≥0k \ge 0,

J(Pk+1,Qk+1)≤J(Pk+1,Qk)≤J(Pk,Qk),J(P_{k+1}, Q_{k+1}) \le J(P_{k+1}, Q_k) \le J(P_k, Q_k),

with P0=0P_0 = 0. The sequence Jk=J(Pk,Qk)J_k = J(P_k, Q_k) converges to a limit J∗≥0J^* \ge 0.

Proof. By Theorem 3, Pk+1P_{k+1} minimizes J(⋅,Qk)J(\cdot, Q_k), so its value is at most that of PkP_k, and Qk+1Q_{k+1} minimizes J(Pk+1,⋅)J(P_{k+1}, \cdot), so its value is at most that of QkQ_k. The sequence JkJ_k does not increase and J≥0J \ge 0, and a monotone sequence bounded below converges. □\square

Lemma 5 (bounded iterates). For all k≥1k \ge 1, ∥Pk∥2+∥Qk∥2≤J0/λ\lVert P_k \rVert^2 + \lVert Q_k \rVert^2 \le J_0 / \lambda, where ∥⋅∥\lVert \cdot \rVert is the Frobenius norm.

Proof. Since every c≥1c \ge 1, J(P,Q)≥λ(∥P∥2+∥Q∥2)J(P, Q) \ge \lambda (\lVert P \rVert^2 + \lVert Q \rVert^2). By Corollary 4, J(Pk,Qk)≤J0J(P_k, Q_k) \le J_0. □\square

Theorem 6 (limit points are stationary). Every limit point (P∗,Q∗)(P^*, Q^*) of the sequence (Pk,Qk)(P_k, Q_k) satisfies ∇PJ(P∗,Q∗)=0\nabla_P J(P^*, Q^*) = 0 and ∇QJ(P∗,Q∗)=0\nabla_Q J(P^*, Q^*) = 0. At least one limit point exists.

Proof. By Lemma 5 the sequence is bounded, so it has a convergent subsequence (Pkj,Qkj)→(P∗,Q∗)(P_{k_j}, Q_{k_j}) \to (P^*, Q^*), with kj≥1k_j \ge 1. JJ and its gradient are continuous, being polynomials.

The gradient in QQ. By Theorem 3, QkQ_{k} minimizes J(Pk,⋅)J(P_{k}, \cdot) for k≥1k \ge 1, so ∇QJ(Pk,Qk)=0\nabla_Q J(P_{k}, Q_{k}) = 0. Taking the limit along the subsequence gives ∇QJ(P∗,Q∗)=0\nabla_Q J(P^*, Q^*) = 0.

The gradient in PP. The points Pkj+1P_{k_j + 1} are bounded by Lemma 5, so after passing to a further subsequence, Pkj+1→P′P_{k_j + 1} \to P'. For every PP, Theorem 3 gives J(Pkj+1,Qkj)≤J(P,Qkj)J(P_{k_j + 1}, Q_{k_j}) \le J(P, Q_{k_j}), and in the limit J(P′,Q∗)≤J(P,Q∗)J(P', Q^*) \le J(P, Q^*). So P′P' minimizes J(⋅,Q∗)J(\cdot, Q^*). By Corollary 4, J(Pkj+1,Qkj)J(P_{k_j + 1}, Q_{k_j}) lies between Jkj+1J_{k_j + 1} and JkjJ_{k_j}, which both tend to J∗J^*, so J(P′,Q∗)=J∗J(P', Q^*) = J^*. Also J(P∗,Q∗)=lim⁡Jkj=J∗J(P^*, Q^*) = \lim J_{k_j} = J^*. Thus P∗P^* reaches the minimum value of J(⋅,Q∗)J(\cdot, Q^*) too, and by the uniqueness of Lemma 2 (applied with Q∗Q^*), P∗=P′P^* = P'. A minimizer of a differentiable function has zero gradient, so ∇PJ(P∗,Q∗)=0\nabla_P J(P^*, Q^*) = 0. □\square

Proposition 7 (stationary is not minimal). If Q0=0Q_0 = 0, then Pk=0P_k = 0 and Qk=0Q_k = 0 for all kk, and (0,0)(0, 0) is a stationary point of JJ. On the toy matrix of the page with λ=1\lambda = 1, r=1r = 1 and the plain penalty, (0,0)(0, 0) is not a minimum.

Proof. With Q=0Q = 0 every bu=0b_u = 0, so P=0P = 0 by Lemma 2, and then every item vector is 0 by the same argument; induction on kk. At (0,0)(0, 0), ∇puJ=−2∑i∈Iuruiqi+2λcupu=0\nabla_{p_u} J = -2 \sum_{i \in I_u} r_{ui} q_i + 2 \lambda c_u p_u = 0 and likewise for qiq_i. On the toy matrix, J(0,0)J(0, 0) is the sum of the squared ratings, 155. With qi=1q_i = 1 for all items and p=(5/2,3,2,3/2)p = (5/2, 3, 2, 3/2) the squared errors sum to 10.75+7+10+6.75=34.510.75 + 7 + 10 + 6.75 = 34.5 and the penalty is 21.5+421.5 + 4, so J=60<155J = 60 < 155. □\square

Cost of a sweep. Line L8 adds one r×rr \times r outer product for each rating of the row, in O(r2)O(r^2) time, and each rating belongs to one user and one item, so forming all systems costs O(sr2)O(s r^2) per half step. Each Cholesky solve costs O(r3)O(r^3). One sweep therefore costs O(sr2+(m+n)r3)O(s r^2 + (m + n) r^3).

What is not claimed. Theorem 6 does not say that the sequence converges, only that its limit points are stationary, and Proposition 7 shows that a stationary point can be far from the minimum. Without the penalty, the global problem is NP-hard already for rank one (Gillis and Glineur, 2011), so no such guarantee should be expected from a method of this kind.

Complexity

The model is the word RAM with real numbers of fixed size.

  • Forming the systems. Line L8 adds an r×rr \times r outer product for each rating of xx. Over all users this costs O(sr2)O(s r^2), and the same over all items.
  • Solving. One Cholesky solve costs O(r3)O(r^3), so a half step costs O(mr3)O(m r^3) or O(nr3)O(n r^3).
  • One sweep. O(sr2+(m+n)r3)O(s r^2 + (m + n) r^3). All TT sweeps cost O(T(sr2+(m+n)r3))O(T (s r^2 + (m + n) r^3)). Computing JJ for a stopping rule adds O(sr)O(s r) per sweep.
  • Space. The factors take O((m+n)r)O((m + n) r), and one system takes O(r2)O(r^2) at a time, or one per processor in a parallel run.

Since rr is usually small next to s/(m+n)s / (m + n), the sr2s r^2 term is often the larger one.

Properties

  • Monotone. JJ never increases, from one half step to the next. This holds without a step size, unlike stochastic gradient descent.
  • Parallel. All users of one half step are independent, and so are all items.
  • Block coordinate descent. ALS is coordinate descent with two blocks, PP and QQ, each minimized exactly.
  • Local. The result depends on the start, and the global minimum is not certified.
  • Deterministic after the start. Given QQ at line L1, the run is fixed.

Variants and improvements

  • ALS-WR. The weights cu=∣Iu∣c_u = |I_u| and ci=∣Ui∣c_i = |U_i| of Zhou et al. Their paper starts the movie matrix with the average rating of each movie in the first row and small random numbers in the other rows, and stops when the RMSE on the probe set changes by less than 1 basis point (0.0001) between rounds.
  • Implicit feedback. ALS for implicit feedback treats every pair as known, with a confidence weight, and uses an algebraic trick to keep the cost close to linear in the nonzero entries.
  • Biases. Add to each item vector a coordinate that the item step keeps at 1, and the matching user coordinate acts as a user bias; the reverse gives item biases.
  • Inexact solves. A few steps of the conjugate gradient method in place of the Cholesky solve lower the cost per row when rr is large. Started from the old vector, conjugate gradient does not increase JJ, but the half step no longer minimizes it.
  • Gradient training. Matrix factorization by SGD fits the same model with cheaper steps and no linear solves.

When to use it

Use ALS when the ratings are on many machines and each machine can hold the factors of the other side, when the data is implicit, so that all pairs count, or when a step size is hard to tune. Koren, Bell and Volinsky (2009) say that SGD is easier and faster in general, and that ALS is the better choice when the system can use parallelization and when the data is implicit. Zhou et al. report Netflix RMSE values from 0.9114 with 50 hidden features to 0.8985 with 1000 features for ALS-WR, and that they did not see overfitting as the number of features grew in their tests. These are measurements on one data set, not guarantees.

Pitfalls

  • No penalty. With λ=0\lambda = 0, a user with fewer than rr ratings has a singular matrix in line L8. Keep λ>0\lambda > 0, or the Cholesky decomposition can break down.
  • Zero start. Q=0Q = 0 is a fixed point of ALS, as in the example. Start from small random values or from item means.
  • Explicit inverses. Compute A−1bA^{-1} b by a Cholesky or QR solve, not by forming A−1A^{-1}.
  • Stopping on the factors. The values of JJ converge, but nothing proved here makes the factors converge, and they can keep moving while JJ hardly changes. Stop on the change in JJ or on the error of held out ratings.
  • Missing entries as zeros. For explicit ratings, the sums of line L8 run over the known ratings of xx only. Summing over all items treats blanks as ratings of zero.
  • Comparing penalties. The plain and the weighted penalty need different values of λ\lambda.

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.

alternating_least_squares.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/alternating-least-squares/. The authors are listed in prov/S7Y3XE.jsonl.

"""Alternating least squares for the factorization R ~ P Q^T.

The objective is

    J(P, Q) = sum over (u, i) in K of (r_ui - p_u . q_i)^2
              + lam (sum_u c_u |p_u|^2 + sum_i c_i |q_i|^2)

with c_u = c_i = 1 (plain ridge penalty) or, with weighted=True, c_u the
number of ratings of user u and c_i the number of ratings of item i (the
ALS-WR weighting of Zhou et al. 2008). With Q fixed, J splits into one
ridge regression for each user, solved exactly by

    (sum over i in I_u of q_i q_i^T + lam c_u I) p_u = sum over i in I_u of r_ui q_i,

and the same holds for the items with P fixed. A user with no rating
gets p_u = 0.
"""

import math
import random


def cholesky_solve(a, b):
    """Solve a x = b for a symmetric positive definite matrix a."""
    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 normal_equations(rows, fixed, lam, weighted, r):
    """The ridge system (A, b) of one user (or item).

    rows maps the other side's index to the rating; fixed holds the
    fixed factor vectors.
    """
    c = len(rows) if weighted else 1
    a = [[0.0] * r for _ in range(r)]
    b = [0.0] * r
    for j, v in rows.items():
        y = fixed[j]
        for s in range(r):
            b[s] += v * y[s]
            for t in range(r):
                a[s][t] += y[s] * y[t]  # @line L8
    for s in range(r):
        a[s][s] += lam * c
    return a, b


def half_step(groups, count, fixed, lam, weighted, r):
    """Solve the ridge problem of each of count rows with the other side fixed."""
    out = []
    for k in range(count):  # @line L6
        rows = groups.get(k)
        if not rows:  # @line L7
            out.append([0.0] * r)
            continue
        a, b = normal_equations(rows, fixed, lam, weighted, r)
        out.append(cholesky_solve(a, b))  # @line L9
    return out  # @line L10


def objective(train, p, q, lam, weighted=False):
    nu, ni = {}, {}
    for u, i in train:
        nu[u] = nu.get(u, 0) + 1
        ni[i] = ni.get(i, 0) + 1
    total = 0.0
    for (u, i), v in train.items():
        e = v - sum(a * b for a, b in zip(p[u], q[i]))
        total += e * e
    for u, pu in enumerate(p):
        c = nu.get(u, 0) if weighted else 1
        total += lam * c * sum(a * a for a in pu)
    for i, qi in enumerate(q):
        c = ni.get(i, 0) if weighted else 1
        total += lam * c * sum(a * a for a in qi)
    return total


def group(train):
    """(by_user, by_item): user -> {item: r} and item -> {user: r}."""
    bu, bi = {}, {}
    for (u, i), v in train.items():
        bu.setdefault(u, {})[i] = v
        bi.setdefault(i, {})[u] = v
    return bu, bi


def als(train, m, n, r, lam, sweeps, seed=1, weighted=False, q0=None):
    """Run sweeps of (user half step, item half step).

    Returns (P, Q, history), where history holds J at the start and after
    each half step. Q starts from q0 if given, else from small random values.
    """
    if lam <= 0.0:
        raise ValueError("lam must be positive")
    rng = random.Random(seed)
    if q0 is None:
        q = [[rng.gauss(0.0, 0.1) for _ in range(r)] for _ in range(n)]  # @line L1
    else:
        q = [row[:] for row in q0]
    p = [[0.0] * r for _ in range(m)]
    bu, bi = group(train)
    history = [objective(train, p, q, lam, weighted)]
    for _ in range(sweeps):  # @line L2
        p = half_step(bu, m, q, lam, weighted, r)  # @line L3
        history.append(objective(train, p, q, lam, weighted))
        q = half_step(bi, n, p, lam, weighted, r)  # @line L4
        history.append(objective(train, p, q, lam, weighted))
    return p, q, history  # @line L5
recs.py 115 lines
# 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
test_alternating_least_squares.py 117 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/alternating-least-squares/. The authors are listed in prov/S7Y3XE.jsonl.

import random
from fractions import Fraction

import recs
import alternating_least_squares as als

TOL = 1e-9


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 ridge_exact(rows, fixed, lam, weighted):
    """The ridge solution of one user from scratch, in Fractions."""
    r = len(next(iter(fixed)))
    c = len(rows) if weighted else 1
    a = [[sum(Fraction(fixed[j][s]) * Fraction(fixed[j][t]) for j in rows) for t in range(r)] for s in range(r)]
    for s in range(r):
        a[s][s] += Fraction(lam) * c
    b = [sum(Fraction(v) * Fraction(fixed[j][s]) for j, v in rows.items()) for s in range(r)]
    return exact_solve(a, b)


def test_half_step_is_exact_ridge_solution():
    for weighted in (False, True):
        full = recs.planted(7, 6, 3, 2, noise=0.3)
        train, _ = recs.split(full, 0.4, 2)
        rng = random.Random(6)
        q = [[rng.gauss(0, 1) for _ in range(3)] for _ in range(6)]
        by_user, by_item = als.group(train)
        p = als.half_step(by_user, 7, q, 0.5, weighted, 3)
        for u in range(7):
            want = ridge_exact(by_user[u], q, 0.5, weighted)
            for x, y in zip(p[u], want):
                assert abs(x - float(y)) < TOL
        q2 = als.half_step(by_item, 6, p, 0.5, weighted, 3)
        for i in range(6):
            want = ridge_exact(by_item[i], p, 0.5, weighted)
            for x, y in zip(q2[i], want):
                assert abs(x - float(y)) < TOL


def test_block_gradient_is_zero_after_half_step():
    full = recs.planted(8, 7, 2, 4, noise=0.2)
    train, _ = recs.split(full, 0.3, 4)
    lam = 0.2
    for weighted in (False, True):
        p, q, _ = als.als(train, 8, 7, 2, lam, 3, seed=1, weighted=weighted)
        # The last half step solved for Q, so the gradient in each q_i is zero.
        by_user, by_item = als.group(train)
        for i, rows in by_item.items():
            c = len(rows) if weighted else 1
            for f in range(2):
                g = 2 * lam * c * q[i][f]
                for u, v in rows.items():
                    e = v - sum(a * b for a, b in zip(p[u], q[i]))
                    g -= 2 * e * p[u][f]
                assert abs(g) < TOL


def test_objective_never_increases():
    for seed in range(3):
        full = recs.planted(12, 10, 3, seed, rounded=True)
        train, _ = recs.split(full, 0.4, seed)
        for weighted in (False, True):
            _, _, hist = als.als(train, 12, 10, 3, 0.1, 25, seed=seed, weighted=weighted)
            for a, b in zip(hist, hist[1:]):
                assert b <= a + TOL * max(1.0, a)


def test_rank_one_hand_example():
    train = recs.toy()
    p, q, hist = als.als(train, 4, 4, 1, 1.0, 1, q0=[[1.0]] * 4)
    for x, y in zip(p, [2.5, 3.0, 2.0, 1.5]):
        assert abs(x[0] - y) < TOL
    for x, y in zip(q, [106 / 81, 61 / 45, 14 / 13, 49 / 45]):
        assert abs(x[0] - y) < TOL
    assert abs(hist[0] - 159) < TOL and abs(hist[1] - 60) < TOL
    assert abs(hist[2] - 54.9526116) < 1e-6
    # The weighted (ALS-WR) user step: p_u = sum of r_ui / (2 n_u).
    p, _, _ = als.als(train, 4, 4, 1, 1.0, 1, q0=[[1.0]] * 4, weighted=True)
    for x, y in zip(p, [5 / 3, 15 / 8, 5 / 4, 1.0]):
        assert abs(x[0] - y) < TOL


def test_zero_start_is_a_fixed_point():
    train = recs.toy()
    p, q, hist = als.als(train, 4, 4, 2, 1.0, 3, q0=[[0.0, 0.0]] * 4)
    assert all(a == 0.0 for row in p + q for a in row)
    assert hist == [155.0] * 7


def test_user_without_ratings_and_cholesky():
    p, _, _ = als.als({(0, 0): 4.0, (0, 1): 2.0}, 2, 2, 2, 0.5, 2)
    assert p[1] == [0.0, 0.0]
    x = als.cholesky_solve([[4.0, 2.0], [2.0, 3.0]], [2.0, 1.0])
    assert abs(4 * x[0] + 2 * x[1] - 2) < 1e-12 and abs(2 * x[0] + 3 * x[1] - 1) < 1e-12
    try:
        als.cholesky_solve([[1.0, 2.0], [2.0, 1.0]], [1.0, 1.0])
    except ValueError:
        pass
    else:
        raise AssertionError("an indefinite matrix was accepted")

History

Zhou, Wilkinson, Schreiber and Pan presented ALS with weighted lambda regularization at AAIM 2008 as a method for the Netflix Prize that runs in parallel. The same year, Hu, Koren and Volinsky adapted ALS to implicit feedback, where every user and item pair enters the loss. In their 2009 survey in IEEE Computer, Koren, Bell and Volinsky listed ALS and stochastic gradient descent as the two learning methods for the factor model.

References

  1. Yunhong Zhou, Dennis Wilkinson, Robert Schreiber and Rong Pan, Large-scale parallel collaborative filtering for the Netflix Prize, Algorithmic Aspects in Information and Management (AAIM 2008), Lecture Notes in Computer Science 5034, 337-348, Equation 5 (the objective with weighted lambda regularization), the solution of the user and the movie least squares problems, the initialization of the movie matrix, the stopping rule on the probe RMSE, and the results with up to 1000 hidden features
  2. Yehuda Koren, Robert Bell and Chris Volinsky, Matrix factorization techniques for recommender systems, IEEE Computer 42(8), 30-37, 2009, section Learning algorithms (alternating least squares, and when it is preferable to stochastic gradient descent)
  3. Nicolas Gillis and François Glineur, Low-rank matrix approximation with weights or missing data is NP-hard, SIAM Journal on Matrix Analysis and Applications 32(4), 1149-1165, 2011, the main result (NP-hardness of low-rank approximation with missing data, already for rank one)
  4. Charu C. Aggarwal, Recommender Systems, The Textbook, Springer, 2016, Chapter 3, Section 3.6 (latent factor models)

Where this leads

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