Algorithm Search⌘K

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.

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
Properties
randomizednot exactofflineiterative
Origin
Yifan Hu, Yehuda Koren, Chris Volinsky, 2008

Weighted matrix factorization for implicit feedback, often called implicit ALS, fits user vectors xux_u and item vectors yiy_i so that xu⊤yix_u^\top y_i 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 mnm n cells is a data point, because an empty cell also says something. A direct solve would cost time proportional to mnm n in each step; the algebraic identity Y⊤CuY=Y⊤Y+Y⊤(Cu−I)YY^\top C^u Y = Y^\top Y + Y^\top (C^u - I) Y of Hu, Koren and Volinsky (2008) brings the cost of one sweep down to O(sr2+(m+n)r3)O(s r^2 + (m + n) r^3), linear in the number ss 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 rui>0r_{ui} > 0 for ss pairs of mm users and nn items; every other pair has rui=0r_{ui} = 0. Hu, Koren and Volinsky define the preference pui=1p_{ui} = 1 if rui>0r_{ui} > 0 and pui=0p_{ui} = 0 otherwise, and the confidence cui=1+αruic_{ui} = 1 + \alpha r_{ui}, with α=40\alpha = 40 in their experiments. Given rr and λ>0\lambda > 0, the method minimizes their Equation 3,

J(X,Y)=∑u=1m∑i=1ncui(pui−xu⊤yi)2+λ(∑u∥xu∥2+∑i∥yi∥2),J(X, Y) = \sum_{u=1}^{m} \sum_{i=1}^{n} c_{ui} \bigl(p_{ui} - x_u^\top y_i\bigr)^2 + \lambda \Bigl( \sum_u \lVert x_u \rVert^2 + \sum_i \lVert y_i \rVert^2 \Bigr),

over xu,yi∈Rrx_u, y_i \in \mathbb{R}^r. Write YY for the n×rn \times r matrix with rows yi⊤y_i^\top, CuC^u for the diagonal n×nn \times n matrix of the cuic_{ui} of user uu, and p(u)p(u) for the vector of the puip_{ui}. With YY fixed, the best xux_u is the weighted ridge regression solution (their Equation 4)

xu=(Y⊤CuY+λI)−1Y⊤Cup(u),x_u = \bigl(Y^\top C^u Y + \lambda I\bigr)^{-1} Y^\top C^u p(u),

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 xu⊤yix_u^\top y_i.

The algorithm

  1. IMPLICIT-ALS(counts, r, λ, α, T)
  2. 1for the s observed pairs: p_ui ← 1, c_ui ← 1 + α r_ui ▷ all other cells have p = 0, c = 1
  3. 2Y ← small random n × r matrix; X ← 0
  4. 3repeat T times
  5. 4X ← HALF(users, Y)
  6. 5Y ← HALF(items, X)
  7. 6return X, Y
  8. HALF(rows, Y) ▷ the vectors y_j of the other side are fixed
  9. 7G ← YᵀY ▷ once per half step, O(n r^2)
  10. 8for each row u do
  11. 9A ← G + λI + Σ_{j: r_uj > 0} (c_uj - 1) y_j y_jᵀ
  12. 10b ← Σ_{j: r_uj > 0} c_uj y_j
  13. 11x_u ← the solution of A x = b, by Cholesky decomposition
  14. 12return the vectors x_u

Line L9 is Y⊤CuY+λIY^\top C^u Y + \lambda I written as Y⊤Y+Y⊤(Cu−I)Y+λIY^\top Y + Y^\top (C^u - I) Y + \lambda I: the diagonal matrix Cu−IC^u - I is zero on every item the user did not use. Line L10 is Y⊤Cup(u)Y^\top C^u p(u), since puj=0p_{uj} = 0 on those items too. A row with no counts gets A=G+λIA = G + \lambda I and b=0b = 0, so xu=0x_u = 0.

Example

Three users, three items, counts

i1i_1 i2i_2 i3i_3
u1u_1 2 1 0
u2u_2 0 1 3
u3u_3 1 0 0

with α=1\alpha = 1, λ=1\lambda = 1, one factor (r=1r = 1) and the start yi=1y_i = 1 for all items. The confidences of the nonzero cells are c=1+ruic = 1 + r_{ui}: 3 and 2 for u1u_1, 2 and 4 for u2u_2, and 2 for u3u_3. Line L7 gives G=1+1+1=3G = 1 + 1 + 1 = 3.

user AA (line L9) bb (line L10) xux_u
u1u_1 3+1+2+1=73 + 1 + 2 + 1 = 7 3+2=53 + 2 = 5 5/75/7
u2u_2 3+1+1+3=83 + 1 + 1 + 3 = 8 2+4=62 + 4 = 6 3/43/4
u3u_3 3+1+1=53 + 1 + 1 = 5 22 2/52/5

The direct form gives the same numbers. For u1u_1, Y⊤CuY+λ=3+2+1+1=7Y^\top C^u Y + \lambda = 3 + 2 + 1 + 1 = 7, a sum over all three items with weight 1 on the empty cell i3i_3.

The objective at the start, with X=0X = 0, is the sum of the confidences of the nonzero cells plus λ∥Y∥2\lambda \lVert Y \rVert^2: 13+3=1613 + 3 = 16. A ridge step lowers gug_u by b2/Ab^2 / A, so after the user step J=16−25/7−9/2−4/5=499/70≈7.1286J = 16 - 25/7 - 9/2 - 4/5 = 499/70 \approx 7.1286. The item step then gives y≈(0.8622,0.8860,0.7653)y \approx (0.8622, 0.8860, 0.7653) and J≈6.8048J \approx 6.8048. The test file checks these values.

Correctness

The proof in proofs/correctness.md shows that the system of lines L9 and L10 is exactly Y⊤CuY+λIY^\top C^u Y + \lambda I and Y⊤Cup(u)Y^\top C^u p(u), because cui−1=0c_{ui} - 1 = 0 and pui=0p_{ui} = 0 on the empty cells. With YY fixed, JJ splits into one strictly convex quadratic per user, so line L4 returns the unique minimizer over XX, and line L5 the unique minimizer over YY. Hence JJ does not increase after each half step, the values of JJ 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 Y=0Y = 0 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 mm users and nn items. For each pair, rui≥0r_{ui} \ge 0 is the count, pui=1p_{ui} = 1 if rui>0r_{ui} > 0 and pui=0p_{ui} = 0 otherwise, and cui=1+αruic_{ui} = 1 + \alpha r_{ui} with α≥0\alpha \ge 0, so cui≥1c_{ui} \ge 1 for every pair. IuI_u is the set of items with rui>0r_{ui} > 0. The objective is

J(X,Y)=∑u=1m∑i=1ncui(pui−xu⊤yi)2+λ(∑u∥xu∥2+∑i∥yi∥2),λ>0.J(X, Y) = \sum_{u=1}^{m} \sum_{i=1}^{n} c_{ui} (p_{ui} - x_u^\top y_i)^2 + \lambda \Bigl( \sum_u \lVert x_u \rVert^2 + \sum_i \lVert y_i \rVert^2 \Bigr), \qquad \lambda > 0.

YY is the n×rn \times r matrix with rows yi⊤y_i^\top, and CuC^u is the n×nn \times n diagonal matrix with entries cuic_{ui}. All statements are about exact arithmetic.

Lemma 1 (separation). For fixed YY, J(X,Y)=∑ugu(xu)+λ∑i∥yi∥2J(X, Y) = \sum_u g_u(x_u) + \lambda \sum_i \lVert y_i \rVert^2 with

gu(x)=∑i=1ncui(pui−x⊤yi)2+λ∥x∥2.g_u(x) = \sum_{i=1}^{n} c_{ui} (p_{ui} - x^\top y_i)^2 + \lambda \lVert x \rVert^2.

Proof. Group the terms of the double sum by user. The term of (u,i)(u, i) depends on XX only through xux_u, and so does λ∥xu∥2\lambda \lVert x_u \rVert^2. □\square

Lemma 2 (one weighted ridge regression). Let Au=Y⊤CuY+λIA_u = Y^\top C^u Y + \lambda I and bu=Y⊤Cup(u)b_u = Y^\top C^u p(u), where p(u)p(u) is the vector of the puip_{ui}. Then AuA_u is symmetric positive definite and gug_u has the unique minimizer xu∗=Au−1bux_u^* = A_u^{-1} b_u.

Proof. Expanding, gu(x)=x⊤Aux−2bu⊤x+∑icuipui2g_u(x) = x^\top A_u x - 2 b_u^\top x + \sum_i c_{ui} p_{ui}^2, since ∑icuiyiyi⊤=Y⊤CuY\sum_i c_{ui} y_i y_i^\top = Y^\top C^u Y and ∑icuipuiyi=Y⊤Cup(u)\sum_i c_{ui} p_{ui} y_i = Y^\top C^u p(u). For z≠0z \ne 0, z⊤Auz=∑icui(yi⊤z)2+λ∥z∥2≥λ∥z∥2>0z^\top A_u z = \sum_i c_{ui} (y_i^\top z)^2 + \lambda \lVert z \rVert^2 \ge \lambda \lVert z \rVert^2 > 0, because every cui≥0c_{ui} \ge 0. So AuA_u is positive definite, gug_u is strictly convex, and its gradient 2Aux−2bu2 A_u x - 2 b_u vanishes exactly at Au−1buA_u^{-1} b_u, which is therefore the unique minimizer. □\square

Lemma 3 (the fast system is the same system). Let G=Y⊤YG = Y^\top Y. The matrix and the vector built in lines L7, L9 and L10,

A^u=G+λI+∑i∈Iu(cui−1)yiyi⊤,b^u=∑i∈Iucuiyi,\hat A_u = G + \lambda I + \sum_{i \in I_u} (c_{ui} - 1) y_i y_i^\top, \qquad \hat b_u = \sum_{i \in I_u} c_{ui} y_i,

satisfy A^u=Au\hat A_u = A_u and b^u=bu\hat b_u = b_u.

Proof. Y⊤CuY=∑i=1ncuiyiyi⊤=∑i=1nyiyi⊤+∑i=1n(cui−1)yiyi⊤Y^\top C^u Y = \sum_{i=1}^{n} c_{ui} y_i y_i^\top = \sum_{i=1}^{n} y_i y_i^\top + \sum_{i=1}^{n} (c_{ui} - 1) y_i y_i^\top. The first sum is GG. For i∉Iui \notin I_u, rui=0r_{ui} = 0, so cui=1c_{ui} = 1 and the term of ii in the second sum is zero; only i∈Iui \in I_u remain. For the vector, pui=0p_{ui} = 0 for i∉Iui \notin I_u and pui=1p_{ui} = 1 for i∈Iui \in I_u, so ∑icuipuiyi=∑i∈Iucuiyi\sum_i c_{ui} p_{ui} y_i = \sum_{i \in I_u} c_{ui} y_i. □\square

Theorem 4 (the half steps are exact). Line L4 returns the unique minimizer of J(⋅,Y)J(\cdot, Y) over XX, and line L5 returns the unique minimizer of J(X,⋅)J(X, \cdot) over YY.

Proof. By Lemma 1, minimizing J(⋅,Y)J(\cdot, Y) is the same as minimizing each gug_u alone, since the last term does not depend on XX. By Lemma 3, line L11 solves Aux=buA_u x = b_u, and the Cholesky decomposition exists because AuA_u is positive definite by Lemma 2. So each xux_u is the unique minimizer of gug_u. For the item step, JJ is symmetric in the roles of users and items: exchange uu and ii, and XX and YY, in Lemmas 1 to 3. □\square

Corollary 5 (the objective does not increase). Let Y0Y_0 be the start of line L2, X0=0X_0 = 0, and let Xk+1X_{k+1} and Yk+1Y_{k+1} be the results of lines L4 and L5 in sweep k+1k + 1. Then

J(Xk+1,Yk+1)≤J(Xk+1,Yk)≤J(Xk,Yk),J(X_{k+1}, Y_{k+1}) \le J(X_{k+1}, Y_k) \le J(X_k, Y_k),

and the values Jk=J(Xk,Yk)J_k = J(X_k, Y_k) converge to a limit J∗≥0J^* \ge 0.

Proof. Xk+1X_{k+1} minimizes J(⋅,Yk)J(\cdot, Y_k), so its value is at most that of XkX_k. Yk+1Y_{k+1} minimizes J(Xk+1,⋅)J(X_{k+1}, \cdot), so its value is at most that of YkY_k. The sequence JkJ_k does not increase and is bounded below by 0, so it converges. □\square

Proposition 6 (limit points are stationary). The iterates satisfy ∥Xk∥2+∥Yk∥2≤J0/λ\lVert X_k \rVert^2 + \lVert Y_k \rVert^2 \le J_0 / \lambda in the Frobenius norm, and every limit point (X∗,Y∗)(X^*, Y^*) of the sequence (Xk,Yk)(X_k, Y_k) has ∇XJ=0\nabla_X J = 0 and ∇YJ=0\nabla_Y J = 0.

Proof. J≥λ(∥X∥2+∥Y∥2)J \ge \lambda (\lVert X \rVert^2 + \lVert Y \rVert^2) and Jk≤J0J_k \le J_0 by Corollary 5, which gives the bound, so limit points exist. Let (Xkj,Ykj)→(X∗,Y∗)(X_{k_j}, Y_{k_j}) \to (X^*, Y^*) with kj≥1k_j \ge 1. Since YkY_k minimizes J(Xk,⋅)J(X_k, \cdot), ∇YJ(Xk,Yk)=0\nabla_Y J(X_k, Y_k) = 0, and by continuity ∇YJ(X∗,Y∗)=0\nabla_Y J(X^*, Y^*) = 0. For XX, pass to a further subsequence with Xkj+1→X′X_{k_j + 1} \to X'. For every XX, J(Xkj+1,Ykj)≤J(X,Ykj)J(X_{k_j + 1}, Y_{k_j}) \le J(X, Y_{k_j}), and in the limit X′X' minimizes J(⋅,Y∗)J(\cdot, Y^*). By Corollary 5, J(Xkj+1,Ykj)J(X_{k_j + 1}, Y_{k_j}) lies between Jkj+1J_{k_j + 1} and JkjJ_{k_j}, so J(X′,Y∗)=J∗=J(X∗,Y∗)J(X', Y^*) = J^* = J(X^*, Y^*). Then X∗X^* also attains the minimum of J(⋅,Y∗)J(\cdot, Y^*), and by the uniqueness of Lemma 2, X∗=X′X^* = X', so ∇XJ(X∗,Y∗)=0\nabla_X J(X^*, Y^*) = 0. □\square

Cost of a sweep. Line L7 costs O(nr2)O(n r^2) once per user half step. For user uu, lines L9 and L10 add ∣Iu∣|I_u| outer products, in O(∣Iu∣r2)O(|I_u| r^2) time, and line L11 costs O(r3)O(r^3). Since ∑u∣Iu∣=s\sum_u |I_u| = s, the user half step costs O(nr2+sr2+mr3)O(n r^2 + s r^2 + m r^3), and the item half step costs O(mr2+sr2+nr3)O(m r^2 + s r^2 + n r^3). One sweep costs O(sr2+(m+n)r3)O(s r^2 + (m + n) r^3), because (m+n)r2≤(m+n)r3(m + n) r^2 \le (m + n) r^3. The direct system of Lemma 2 would cost O(nr2)O(n r^2) for each user, so O(mnr2)O(m n r^2) 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: Y0=0Y_0 = 0 gives bu=0b_u = 0, so X1=0X_1 = 0, then Y1=0Y_1 = 0, and the run stays at (0,0)(0, 0). Whether the ranking that the factors produce is good is a question of measurement on data, not of this proof. ■\blacksquare

Complexity

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

  • Shared part. Line L7 costs O(nr2)O(n r^2) per user half step and O(mr2)O(m r^2) per item half step.
  • Per row. Lines L9 and L10 cost O(nur2)O(n_u r^2) for a user with nun_u nonzero counts, and line L11 costs O(r3)O(r^3). Hu, Koren and Volinsky give the total as O(r2s+r3m)O(r^2 s + r^3 m) for the user step.
  • One sweep. O(sr2+(m+n)r3)O(s r^2 + (m + n) r^3), and TT sweeps cost O(T(sr2+(m+n)r3))O(T (s r^2 + (m + n) r^3)). The paper used about 10 sweeps.
  • Without the identity. Forming Y⊤CuYY^\top C^u Y directly costs O(nr2)O(n r^2) per user, so O(mnr2)O(m n r^2) per half step, which is the cost of a dense problem.
  • Space. O((m+n)r)O((m + n) r) for the factors and O(r2)O(r^2) for GG and one system.

Computing JJ exactly costs O(mnr)O(m n r); it can be done in O(sr+(m+n)r2)O(s r + (m + n) r^2) with the same trick, but it is not needed to run the method.

Properties

  • Monotone. JJ 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 ss.
  • Parallel. The users of one half step are independent once GG is known, and so are the items.
  • Local. The problem is not convex in (X,Y)(X, Y), and the result depends on the start.
  • Explainable. Section 5 of the paper writes the score as ∑jsijucuj\sum_{j} s^u_{ij} c_{uj} over the items jj the user used, with weights from (Y⊤CuY+λI)−1(Y^\top C^u Y + \lambda I)^{-1}, so a recommendation can be traced to past items.

Variants and improvements

  • Log confidence. The paper also proposes cui=1+αlog⁡(1+rui/ϵ)c_{ui} = 1 + \alpha \log(1 + r_{ui} / \epsilon) (Equation 6), with ϵ=10−8\epsilon = 10^{-8} in its experiments.
  • Inexact solves. A few steps of the conjugate gradient method, started from the old xux_u, in place of line L11 lower the cost per row when rr is large. Each such step still does not increase JJ, 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 xu⊤yi=1x_u^\top y_i = 1 fits everything. The empty cells must stay in the loss; the identity of line L9 is how they stay in cheaply.
  • Forming Y⊤CuYY^\top C^u Y directly. It is correct but costs O(nr2)O(n r^2) per user, so the method becomes as slow as a dense problem.
  • The scale of α\alpha. The confidence weights and λ\lambda interact, so a new α\alpha usually needs a new λ\lambda.
  • Stopping on the factors. The values of JJ converge, but the factors can keep moving; stop on the change in JJ or on a held-out ranking measure.
  • Reading pui=0p_{ui} = 0 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.

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

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

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