Algorithm Search⌘K

Algorithmcore

Matrix factorization for recommendation

Also called latent factor model, Funk SVD.

Fits a user vector and an item vector whose dot product predicts each known rating, by regularized least squares and gradient descent.

Time
O(E s r) worst
Space
O((m + n) r) extra
Where
E = the number of epochs; 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
Simon Funk, Yehuda Koren, Robert Bell, Chris Volinsky, 2006

Matrix factorization for recommendation gives each user uu and each item ii a vector of rr numbers, pup_u and qiq_i, and predicts the rating ruir_{ui} by the dot product pu⊤qip_u^\top q_i, usually plus a global mean and a bias for the user and for the item. The vectors are fitted to the known ratings only, by regularized least squares, and the usual training is stochastic gradient descent that visits one rating at a time. Simon Funk made the method known during the Netflix Prize in 2006, which is why it is also called Funk SVD, although it is not the singular value decomposition of any matrix.

In plain words

Each film gets a short list of hidden scores, for example how much action it has and how serious it is. Each viewer gets a list of the same length that says how much the viewer likes each of these qualities. The guess for a viewer and a film multiplies the two lists entry by entry and adds the results, so a viewer who likes action gets a high guess for an action film.

Nobody chooses the qualities. The method starts from small random lists and goes over the known ratings again and again. For each rating it compares the guess with the true value and moves both lists a little in the direction that makes the error smaller. A penalty keeps the lists short, so that a viewer with few ratings does not get extreme scores.

The problem

The input is a set KK of known ratings ruir_{ui} of mm users for nn items, with s=∣K∣s = |K|, a number of factors rr, and a penalty λ>0\lambda > 0. The biased model of Koren, Bell and Volinsky (Equation 4) predicts

r^ui=μ+bu+bi+pu⊤qi,\hat r_{ui} = \mu + b_u + b_i + p_u^\top q_i,

with μ\mu the mean of the known ratings, scalar biases bub_u and bib_i, and pu,qi∈Rrp_u, q_i \in \mathbb{R}^r. With eui=rui−r^uie_{ui} = r_{ui} - \hat r_{ui}, the fit minimizes

J=∑(u,i)∈K[eui2+λ(bu2+bi2+∥pu∥2+∥qi∥2)].J = \sum_{(u, i) \in K} \Bigl[ e_{ui}^2 + \lambda \bigl( b_u^2 + b_i^2 + \lVert p_u \rVert^2 + \lVert q_i \rVert^2 \bigr) \Bigr].

The sum runs over the known entries only. A missing entry is not a zero rating, and filling it in would change the problem. The penalty sits inside the sum, as in Equation 5 of the 2009 paper, so a user with nun_u ratings pays λnu∥pu∥2\lambda n_u \lVert p_u \rVert^2, which is the reading that gives the SGD rule below. The unbiased model drops μ\mu, bub_u and bib_i and predicts pu⊤qip_u^\top q_i (Equations 1 and 2).

JJ is not convex in all parameters together. Without the penalty, finding the best rank rr fit to a partly known matrix is NP-hard already for r=1r = 1 (Gillis and Glineur, 2011). The algorithm below is therefore a local search: it gives a model with a low value of JJ, not a certified minimum.

The algorithm

  1. FIT(K, r, λ, γ, E) ▷ γ: step size, E: number of epochs
  2. 1μ ← the mean of the ratings in K
  3. 2b_u ← 0, b_i ← 0 for all u, i; p_u, q_i ← small random vectors in R^r
  4. 3repeat E times
  5. 4for each (u, i) in K, in a new random order, do
  6. 5e ← r_ui - (μ + b_u + b_i + p_u·q_i)
  7. 6b_u ← b_u + γ (e - λ b_u); b_i ← b_i + γ (e - λ b_i)
  8. 7(p_u, q_i) ← (p_u + γ (e q_i - λ p_u), q_i + γ (e p_u - λ q_i))
  9. 8return μ, b, p, q
  10. PREDICT(u, i)
  11. 9return μ + b_u + b_i + p_u·q_i

Line L7 updates both vectors at once from the old values. This is the rule of Koren, Bell and Volinsky. The code of Funk's post updates the user value first and then uses the new user value for the item, which is a slightly different step that also works. The unbiased model skips line L6 and the bias terms.

Example

Use the toy rating matrix of this group, with μ=41/14≈2.9286\mu = 41/14 \approx 2.9286 over its 14 ratings:

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

Take one factor (r=1r = 1), bu1=bi1=0b_{u_1} = b_{i_1} = 0, pu1=qi1=0.5p_{u_1} = q_{i_1} = 0.5, and γ=λ=0.1\gamma = \lambda = 0.1. One step on the rating ru1i1=5r_{u_1 i_1} = 5:

quantity before after
prediction μ+0.25≈3.1786\mu + 0.25 \approx 3.1786 ≈3.6363\approx 3.6363
error ee ≈1.8214\approx 1.8214 ≈1.3637\approx 1.3637
bu1b_{u_1}, bi1b_{i_1} 0 0.1⋅1.8214≈0.18210.1 \cdot 1.8214 \approx 0.1821
pu1p_{u_1}, qi1q_{i_1} 0.5 0.5+0.1(1.8214⋅0.5−0.05)≈0.58610.5 + 0.1 (1.8214 \cdot 0.5 - 0.05) \approx 0.5861
term e2+λ(bu2+bi2+p2+q2)e^2 + \lambda (b_u^2 + b_i^2 + p^2 + q^2) ≈3.3676\approx 3.3676 ≈1.9349\approx 1.9349

Both biases and both factors rise, because the prediction was too low. The step changes only the four parameters of u1u_1 and i1i_1; the other 12 parameters of the model wait for their own ratings.

The factors are not unique. With r=1r = 1, replacing every pup_u by −pu-p_u and every qiq_i by −qi-q_i keeps all predictions and the penalty, so two different models have the same JJ. With r≥2r \ge 2, any rotation of the factor space does the same. Only the predictions, not the single factors, carry meaning.

Correctness

The proof in proofs/correctness.md shows the following. The term ℓui\ell_{ui} of one rating in JJ has the gradient −2eui+2λbu-2 e_{ui} + 2 \lambda b_u in bub_u, −2euiqi+2λpu-2 e_{ui} q_i + 2 \lambda p_u in pup_u, and the symmetric forms in bib_i and qiq_i, and no other parameter enters it. So lines L5 to L7 make the step θ←θ−(γ/2)∇ℓui(θ)\theta \leftarrow \theta - (\gamma / 2) \nabla \ell_{ui}(\theta), and for a rating drawn uniformly from KK the expected step is −(γ/2s)∇J-(\gamma / 2s) \nabla J: the method is stochastic gradient descent on JJ. The proof also shows that the penalty inside the sum equals λ∑unu(bu2+∥pu∥2)+λ∑ini(bi2+∥qi∥2)\lambda \sum_u n_u (b_u^2 + \lVert p_u \rVert^2) + \lambda \sum_i n_i (b_i^2 + \lVert q_i \rVert^2), that JJ is invariant under orthogonal changes of the factor space, and that all factors equal to zero give a stationary point in the factors, which is why line L2 starts from random vectors. It gives no convergence result for the fixed step size γ\gamma.

Proof: The SGD step of matrix factorization is a scaled gradient step on one term of the regularized objectivefull

The notation is that of the page: KK is the set of known ratings, s=∣K∣s = |K|, r^ui=μ+bu+bi+pu⊤qi\hat r_{ui} = \mu + b_u + b_i + p_u^\top q_i, eui=rui−r^uie_{ui} = r_{ui} - \hat r_{ui}, and θ\theta is the vector of all parameters bu,bi,pu,qib_u, b_i, p_u, q_i, with μ\mu fixed by line L1. For (u,i)∈K(u, i) \in K let

ℓui(θ)=eui2+λ(bu2+bi2+∥pu∥2+∥qi∥2),J(θ)=∑(u,i)∈Kℓui(θ).\ell_{ui}(\theta) = e_{ui}^2 + \lambda \bigl( b_u^2 + b_i^2 + \lVert p_u \rVert^2 + \lVert q_i \rVert^2 \bigr), \qquad J(\theta) = \sum_{(u, i) \in K} \ell_{ui}(\theta).

All statements are about exact arithmetic. For the unbiased model, delete the bias terms and μ\mu everywhere; every proof goes through unchanged.

Lemma 1 (the gradient of one term). ℓui\ell_{ui} depends only on bub_u, bib_i, pup_u and qiq_i, and

∂ℓui∂bu=−2eui+2λbu,∂ℓui∂bi=−2eui+2λbi,∇puℓui=−2euiqi+2λpu,∇qiℓui=−2euipu+2λqi.\frac{\partial \ell_{ui}}{\partial b_u} = -2 e_{ui} + 2 \lambda b_u, \quad \frac{\partial \ell_{ui}}{\partial b_i} = -2 e_{ui} + 2 \lambda b_i, \quad \nabla_{p_u} \ell_{ui} = -2 e_{ui} q_i + 2 \lambda p_u, \quad \nabla_{q_i} \ell_{ui} = -2 e_{ui} p_u + 2 \lambda q_i.

Proof. The prediction r^ui\hat r_{ui} and the penalty of the term use only these four parameters. The derivative of euie_{ui} is −1-1 in bub_u and in bib_i, −qi-q_i in pup_u (since ∇p(p⊤q)=q\nabla_{p} (p^\top q) = q) and −pu-p_u in qiq_i. By the chain rule the derivative of eui2e_{ui}^2 is 2eui2 e_{ui} times these, and the derivative of λ∥pu∥2\lambda \lVert p_u \rVert^2 is 2λpu2 \lambda p_u, and the same for the other three. □\square

Theorem 2 (the step). Let θ\theta be the parameters before lines L5 to L7 for the rating (u,i)(u, i) and θ′\theta' the parameters after them. Then θ′=θ−(γ/2)∇ℓui(θ)\theta' = \theta - (\gamma / 2) \nabla \ell_{ui}(\theta).

Proof. Line L5 computes e=eui(θ)e = e_{ui}(\theta). Line L6 sets bu′=bu+γ(e−λbu)=bu−(γ/2)(−2e+2λbu)b_u' = b_u + \gamma (e - \lambda b_u) = b_u - (\gamma / 2)(-2 e + 2 \lambda b_u), and the same for bib_i; by Lemma 1 these are the stated coordinates. Line L7 computes both new vectors from the old pup_u and qiq_i, so pu′=pu−(γ/2)(−2eqi+2λpu)p_u' = p_u - (\gamma / 2)(-2 e q_i + 2 \lambda p_u) and qi′=qi−(γ/2)(−2epu+2λqi)q_i' = q_i - (\gamma / 2)(-2 e p_u + 2 \lambda q_i), again with all values taken at θ\theta. By Lemma 1 every other coordinate of ∇ℓui(θ)\nabla \ell_{ui}(\theta) is zero, and lines L5 to L7 do not change the other parameters. □\square

Corollary 3 (an unbiased estimate of the full gradient). If (u,i)(u, i) is drawn uniformly from KK, the expected step is E[θ′−θ]=−γ2s∇J(θ)\mathbb{E}[\theta' - \theta] = -\frac{\gamma}{2 s} \nabla J(\theta).

Proof. By Theorem 2 and linearity, E[θ′−θ]=−γ2⋅1s∑(u,i)∈K∇ℓui(θ)=−γ2s∇J(θ)\mathbb{E}[\theta' - \theta] = -\frac{\gamma}{2} \cdot \frac{1}{s} \sum_{(u, i) \in K} \nabla \ell_{ui}(\theta) = -\frac{\gamma}{2 s} \nabla J(\theta). □\square

In line L4 the ratings come in a random order without replacement, so within one epoch the steps are not independent draws. Each rating is still visited once per epoch, and Corollary 3 holds for the first step of each epoch, whose rating is uniform on KK.

Proposition 4 (the penalty counts ratings). Let nun_u be the number of ratings of user uu and nin_i the number of ratings of item ii in KK. Then

J=∑(u,i)∈Keui2+λ∑unu(bu2+∥pu∥2)+λ∑ini(bi2+∥qi∥2).J = \sum_{(u, i) \in K} e_{ui}^2 + \lambda \sum_u n_u \bigl( b_u^2 + \lVert p_u \rVert^2 \bigr) + \lambda \sum_i n_i \bigl( b_i^2 + \lVert q_i \rVert^2 \bigr).

Proof. In the sum over KK the term λ(bu2+∥pu∥2)\lambda (b_u^2 + \lVert p_u \rVert^2) appears once for each rating of uu, that is nun_u times, and the term λ(bi2+∥qi∥2)\lambda (b_i^2 + \lVert q_i \rVert^2) appears nin_i times. □\square

Proposition 5 (rotations). Let QQ be an orthogonal r×rr \times r matrix. Replacing every pup_u by QpuQ p_u and every qiq_i by QqiQ q_i keeps every prediction and the value of JJ. In particular, if some factor is nonzero, then JJ takes the same value at two different points, so a minimizer with a nonzero factor is never unique.

Proof. (Qpu)⊤(Qqi)=pu⊤Q⊤Qqi=pu⊤qi(Q p_u)^\top (Q q_i) = p_u^\top Q^\top Q q_i = p_u^\top q_i, and ∥Qpu∥=∥pu∥\lVert Q p_u \rVert = \lVert p_u \rVert, ∥Qqi∥=∥qi∥\lVert Q q_i \rVert = \lVert q_i \rVert. For Q=−IQ = -I, the point changes whenever some factor is nonzero. □\square

Proposition 6 (zero factors). If pu=0p_u = 0 for all users and qi=0q_i = 0 for all items, then ∇puJ=0\nabla_{p_u} J = 0 and ∇qiJ=0\nabla_{q_i} J = 0 for all uu and ii, whatever the biases, and lines L5 to L7 keep all factors at zero.

Proof. By Lemma 1, ∇puℓui=−2euiqi+2λpu=0\nabla_{p_u} \ell_{ui} = -2 e_{ui} q_i + 2 \lambda p_u = 0 when pu=qi=0p_u = q_i = 0, and likewise for qiq_i. Summing over KK gives the first claim. By Theorem 2 the factor part of each step is −(γ/2)-(\gamma / 2) times these zero vectors, so the factors stay zero, and by induction over the steps they stay zero for the whole run. □\square

So a start with all factors at zero trains only the biases, and line L2 starts from small random vectors. The page claims no convergence for a fixed step size γ\gamma: JJ is not convex, and Theorem 2 only says that each step follows the negative gradient of one term.

Complexity

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

  • One step. Lines L5 to L7 cost O(r)O(r).
  • One epoch. Line L4 visits all ss ratings, and the random order costs O(s)O(s), so an epoch costs O(sr)O(s r). All EE epochs cost O(Esr)O(E s r).
  • Prediction. O(r)O(r) for one pair, and O(nr)O(n r) to score all items for one user.
  • Space. The model has m+nm + n biases and (m+n)r(m + n) r factors, O((m+n)r)O((m + n) r) beside the input.

The number of epochs that gives a good model is not fixed by the method. It depends on the data, γ\gamma and λ\lambda, and is found on held out ratings.

Properties

  • Approximate and randomized. The result depends on the random start and the random order. Runs with different seeds give different factors and, in general, slightly different predictions.
  • Only known ratings. The cost per epoch grows with ss, not with mnm n, so it works on sparse matrices of any shape.
  • Low rank. The matrix of the dot products pu⊤qip_u^\top q_i has rank at most rr. This is the assumption of the method: a few hidden factors explain most of the ratings.
  • Not clipped. r^ui\hat r_{ui} can leave the rating scale.
  • Non-unique factors. Orthogonal changes of the factor space keep JJ, as in the example.

Variants and improvements

  • Alternating least squares. Fixes one side of the factors and solves a ridge regression for each vector of the other side, which parallelizes well and suits implicit feedback.
  • SVD++. Adds to pup_u a sum of item vectors over the items the user rated, so that the fact of rating counts as a signal.
  • Probabilistic matrix factorization. Reads the squared error with the penalty counted once per parameter, not inside the sum as in JJ, as the negative log posterior of a Gaussian model, with λ\lambda as a ratio of variances.
  • Nonnegative factors. Nonnegative matrix factorization keeps all entries at or above zero, which can make the factors easier to read.
  • One factor at a time. Funk's post trains one feature for many epochs, adds it to the finished features, and then trains the next one on what the finished features do not explain.
  • Factorization machines generalize the dot product to any set of features of the user, the item and the context.
  • Ranking losses. For clicks and views, a pairwise loss such as Bayesian personalized ranking replaces the squared error.

When to use it

Use it for explicit ratings on a large sparse matrix, when the goal is to predict ratings or to rank items for each user, and when the model can be retrained from time to time. Koren (2008, Table 1) reports test RMSE on the Netflix data of 0.9046, 0.9025 and 0.9009 for the biased model with 50, 100 and 200 factors, against 0.9514 for the Netflix system Cinematch. These values are measurements on one data set. The method cannot give factors to a user or an item with no rating, see the cold-start problem. When there is no rating at all, only clicks or views, use a method made for implicit data.

Pitfalls

  • Zero start. If all pup_u and qiq_i are zero, every step leaves them at zero, and the model stays a bias model. Start from small random values.
  • Missing entries as zeros. A truncated SVD of the matrix with zeros in the blanks fits the blanks too and predicts low ratings for all unseen items. Sum over KK only.
  • Step size. A large γ\gamma makes the error grow from epoch to epoch. A small one needs many epochs. Watch JJ or the error on held out ratings.
  • The penalty convention. The per rating penalty and a penalty counted once per parameter give different models for the same λ\lambda. Tune λ\lambda again when you change the convention.
  • Tuning on the test set. Choose rr, λ\lambda, γ\gamma and EE by cross-validation or on a held out part of the training ratings, or the reported error is too low. See overfitting.
  • Reading single factors. A factor of one run need not match a factor of another run, because of the rotation freedom.

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.

matrix_factorization_recommendation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/matrix-factorization-recommendation/. The authors are listed in prov/99YS69.jsonl.

"""Matrix factorization for rating prediction, trained by SGD.

The model predicts r_ui by mu + b_u + b_i + p_u . q_i (biased=True) or
by p_u . q_i (biased=False, then mu, b_u and b_i stay 0). The objective
puts the penalty once on each rating:

    J = sum over (u, i) in K of [ e_ui^2 + lam (b_u^2 + b_i^2 + |p_u|^2 + |q_i|^2) ]

with e_ui = r_ui - prediction. One SGD step on the rating (u, i) is

    b_u <- b_u + g (e - lam b_u)        b_i <- b_i + g (e - lam b_i)
    p_u <- p_u + g (e q_i - lam p_u)    q_i <- q_i + g (e p_u - lam q_i)

with the old values on the right side. This is theta - (g / 2) times the
gradient of the term of (u, i) in J.
"""

import random


class Model:
    def __init__(self, m, n, r, mu=0.0, biased=True):
        self.m, self.n, self.r = m, n, r
        self.biased = biased
        self.mu = mu if biased else 0.0
        self.bu = [0.0] * m
        self.bi = [0.0] * n
        self.p = [[0.0] * r for _ in range(m)]
        self.q = [[0.0] * r for _ in range(n)]

    def predict(self, u, i):
        s = sum(a * b for a, b in zip(self.p[u], self.q[i]))
        if self.biased:
            s += self.mu + self.bu[u] + self.bi[i]
        return s  # @line L9

    def copy(self):
        c = Model(self.m, self.n, self.r, self.mu, self.biased)
        c.bu, c.bi = self.bu[:], self.bi[:]
        c.p = [row[:] for row in self.p]
        c.q = [row[:] for row in self.q]
        return c


def init(m, n, r, train, seed, scale=0.1, biased=True):
    """Small random factors, zero biases, mu = the mean of train."""
    rng = random.Random(seed)
    mu = sum(train.values()) / len(train)  # @line L1
    model = Model(m, n, r, mu, biased)
    model.p = [[rng.gauss(0.0, scale) for _ in range(r)] for _ in range(m)]  # @line L2
    model.q = [[rng.gauss(0.0, scale) for _ in range(r)] for _ in range(n)]
    return model


def objective(model, train, lam):
    """J with the penalty once per rating, as in the module docstring."""
    total = 0.0
    for (u, i), v in train.items():
        e = v - model.predict(u, i)
        reg = sum(a * a for a in model.p[u]) + sum(b * b for b in model.q[i])
        if model.biased:
            reg += model.bu[u] ** 2 + model.bi[i] ** 2
        total += e * e + lam * reg
    return total


def gradient(model, train, lam):
    """The exact gradient of J: (d bu, d bi, d p, d q)."""
    gbu = [0.0] * model.m
    gbi = [0.0] * model.n
    gp = [[0.0] * model.r for _ in range(model.m)]
    gq = [[0.0] * model.r for _ in range(model.n)]
    for (u, i), v in train.items():
        e = v - model.predict(u, i)
        if model.biased:
            gbu[u] += -2.0 * e + 2.0 * lam * model.bu[u]
            gbi[i] += -2.0 * e + 2.0 * lam * model.bi[i]
        for f in range(model.r):
            gp[u][f] += -2.0 * e * model.q[i][f] + 2.0 * lam * model.p[u][f]
            gq[i][f] += -2.0 * e * model.p[u][f] + 2.0 * lam * model.q[i][f]
    return gbu, gbi, gp, gq


def sgd_step(model, u, i, v, lam, gamma):
    """One SGD step on the rating r_ui = v, in place."""
    e = v - model.predict(u, i)  # @line L5
    if model.biased:
        model.bu[u] += gamma * (e - lam * model.bu[u])  # @line L6
        model.bi[i] += gamma * (e - lam * model.bi[i])
    pu, qi = model.p[u], model.q[i]
    for f in range(model.r):
        a, b = pu[f], qi[f]
        pu[f] = a + gamma * (e * b - lam * a)  # @line L7
        qi[f] = b + gamma * (e * a - lam * b)


def sgd_epoch(model, train, lam, gamma, order):
    """One pass of SGD over the keys of train in the given order."""
    for u, i in order:
        sgd_step(model, u, i, train[(u, i)], lam, gamma)


def fit(train, m, n, r, lam=0.05, gamma=0.01, epochs=50, seed=1, biased=True):
    """Train by SGD; each epoch visits the ratings in a new random order."""
    rng = random.Random(seed)
    model = init(m, n, r, train, seed, biased=biased)
    keys = sorted(train)
    for _ in range(epochs):  # @line L3
        rng.shuffle(keys)  # @line L4
        sgd_epoch(model, train, lam, gamma, keys)
    return model  # @line L8
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_matrix_factorization_recommendation.py 124 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/matrix-factorization-recommendation/. The authors are listed in prov/99YS69.jsonl.

import random

import recs
import matrix_factorization_recommendation as mf

H = 1e-6  # step of the central differences
TOL = 1e-6  # allowed gap, relative to max(1, |gradient entry|)


def random_model(m, n, r, train, seed, biased=True):
    rng = random.Random(seed)
    model = mf.init(m, n, r, train, seed, scale=0.5, biased=biased)
    if biased:
        model.bu = [rng.uniform(-0.5, 0.5) for _ in range(m)]
        model.bi = [rng.uniform(-0.5, 0.5) for _ in range(n)]
    return model


def params(model):
    """(list, index) handles for each parameter of the model."""
    out = []
    if model.biased:
        out += [(model.bu, u) for u in range(model.m)]
        out += [(model.bi, i) for i in range(model.n)]
    out += [(row, f) for row in model.p for f in range(model.r)]
    out += [(row, f) for row in model.q for f in range(model.r)]
    return out


def flat_gradient(model, train, lam):
    gbu, gbi, gp, gq = mf.gradient(model, train, lam)
    out = []
    if model.biased:
        out += gbu + gbi
    for row in gp + gq:
        out += row
    return out


def test_gradient_matches_central_differences():
    for biased in (True, False):
        full = recs.planted(5, 4, 2, 3, noise=0.2)
        train, _ = recs.split(full, 0.3, 3)
        model = random_model(5, 4, 2, train, 8, biased)
        lam = 0.3
        g = flat_gradient(model, train, lam)
        for (vec, k), gk in zip(params(model), g):
            old = vec[k]
            vec[k] = old + H
            up = mf.objective(model, train, lam)
            vec[k] = old - H
            down = mf.objective(model, train, lam)
            vec[k] = old
            num = (up - down) / (2 * H)
            assert abs(num - gk) <= TOL * max(1.0, abs(gk))


def test_sgd_step_is_half_gradient_step_on_one_rating():
    full = recs.planted(4, 4, 3, 5)
    train, _ = recs.split(full, 0.25, 5)
    lam, gamma = 0.1, 0.05
    for (u, i), v in sorted(train.items()):
        model = random_model(4, 4, 3, train, u * 4 + i)
        g = flat_gradient(model, {(u, i): v}, lam)
        before = [vec[k] for vec, k in params(model)]
        mf.sgd_step(model, u, i, v, lam, gamma)
        after = [vec[k] for vec, k in params(model)]
        for b, a, gk in zip(before, after, g):
            assert abs(a - (b - gamma / 2 * gk)) < 1e-12


def test_hand_example():
    # One factor, no bias: p = 1, q = 2, r = 5, gamma = lam = 0.1.
    model = mf.Model(1, 1, 1, biased=False)
    model.p, model.q = [[1.0]], [[2.0]]
    mf.sgd_step(model, 0, 0, 5.0, 0.1, 0.1)
    assert abs(model.p[0][0] - 1.59) < 1e-12
    assert abs(model.q[0][0] - 2.28) < 1e-12


def test_toy_step_of_the_page():
    # Biased, one factor, mu = 41/14, zero biases, p_u1 = q_i1 = 0.5,
    # the rating r(u1, i1) = 5, gamma = lam = 0.1.
    train = recs.toy()
    model = mf.Model(4, 4, 1, mu=recs.global_mean(train))
    model.p[0], model.q[0] = [0.5], [0.5]
    lam = gamma = 0.1
    before = mf.objective(model, {(0, 0): 5.0}, lam)
    mf.sgd_step(model, 0, 0, 5.0, lam, gamma)
    after = mf.objective(model, {(0, 0): 5.0}, lam)
    e = 5.0 - (41 / 14 + 0.25)
    assert abs(model.bu[0] - 0.1 * e) < 1e-12 and abs(model.bi[0] - 0.1 * e) < 1e-12
    assert abs(model.p[0][0] - (0.5 + 0.1 * (0.5 * e - 0.05))) < 1e-12
    assert abs(model.predict(0, 0) - 3.6363369) < 1e-6
    assert abs(before - 3.3676020) < 1e-6 and abs(after - 1.9349083) < 1e-6


def test_zero_factors_stay_zero():
    # p = q = 0 is a stationary point in the factors: SGD never leaves it.
    train = recs.toy()
    model = mf.Model(4, 4, 2, mu=recs.global_mean(train))
    mf.sgd_epoch(model, train, 0.05, 0.05, sorted(train))
    assert all(a == 0.0 for row in model.p + model.q for a in row)
    assert any(b != 0.0 for b in model.bu)


def test_training_lowers_objective_and_beats_the_mean():
    full = recs.planted(20, 15, 2, 1, noise=0.1)
    train, hidden = recs.split(full, 0.3, 1)
    lam, gamma = 0.02, 0.02
    start = mf.init(20, 15, 2, train, 4)
    model = mf.fit(train, 20, 15, 2, lam=lam, gamma=gamma, epochs=200, seed=4)
    assert mf.objective(model, train, lam) < 0.2 * mf.objective(start, train, lam)
    mu = recs.global_mean(train)
    assert recs.rmse(model.predict, hidden) < recs.rmse(lambda u, i: mu, hidden)


def test_unbiased_model_keeps_zero_biases():
    train, _ = recs.split(recs.planted(6, 5, 2, 2), 0.2, 2)
    model = mf.fit(train, 6, 5, 2, epochs=5, biased=False)
    assert model.mu == 0.0 and set(model.bu) == {0.0} and set(model.bi) == {0.0}

History

Factor models for ratings came before the Netflix Prize; earlier systems often filled in the missing entries and then took an SVD, which Koren, Bell and Volinsky describe as expensive and as a source of distortion. In December 2006, two months after the prize began, Simon Funk published on his blog a short program that fitted one feature at a time by gradient steps on the known ratings only, with a penalty. Koren (2008) states that Funk popularized gradient descent for this model. Koren, Bell and Volinsky, members of the team that won the Netflix Prize in 2009, summarized the method with biases, implicit feedback, temporal effects and confidence weights in IEEE Computer in 2009.

References

  1. Yehuda Koren, Robert Bell and Chris Volinsky, Matrix factorization techniques for recommender systems, IEEE Computer 42(8), 30-37, 2009, sections A basic matrix factorization model (Equations 1 and 2), Learning algorithms (stochastic gradient descent and alternating least squares), Adding biases (Equations 3 to 5) and Netflix Prize competition
  2. Simon Funk, Netflix Update, Try This at Home, blog post, December 11, 2006, the training of one feature at a time, the learning rate 0.001, the initial value 0.1, and the regularized update with the constant K
  3. Yehuda Koren, Factorization meets the neighborhood, a multifaceted collaborative filtering model, Proceedings of the 14th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (KDD 2008), 426-434, Section 2.3 (latent factor models and the remark that Funk popularized gradient descent), Equation 12 (the biased factor model) and Table 1 (RMSE on the Netflix test set)
  4. 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)
  5. 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