Algorithm Search⌘K

Algorithmadvanced

SVD++

Also called Koren SVD++.

Adds to the biased latent factor model an implicit-feedback term, a scaled sum of factors of the items the user rated or viewed, so that the fact of rating counts as a signal.

Time
O(E s d r) worst
Space
O((m + n) r) extra
Where
E = the number of epochs; d = the largest number of implicit items of one user; 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
Yehuda Koren, 2008

SVD++ is a latent factor model for rating prediction in which the vector of a user is the free vector pup_u of matrix factorization plus a normalized sum of item vectors yjy_j over the set N(u)N(u) of items with implicit feedback from uu, such as the items the user rated, rented or viewed. Koren introduced it in 2008 for the Netflix Prize, where N(u)N(u) was the set of rated items: which films a user chose to rate says something about the user, apart from the values of the ratings. The model is trained by stochastic gradient descent on the regularized squared error of the known ratings.

In plain words

Plain matrix factorization learns a taste profile for each user from the ratings alone. SVD++ also uses the list of items that the user touched, even when it does not know what the user thought of them. Each item gets a second profile that says what having touched this item tells about a person. The user's full profile is the learned taste profile plus the average of these second profiles over the items the user touched.

So a user with few ratings but a long history of views still gets a useful profile, and a user's profile changes as soon as a new view enters the history, even before the model learns anything new.

The problem

The input is a set KK of known ratings of mm users for nn items, s=∣K∣s = |K|, and for each user uu a set N(u)N(u) of items with implicit feedback. In Koren's experiments N(u)N(u) is the set of items that uu rated, since the Netflix data had no other implicit data (Section 2.5). The model of Equation 15 predicts

r^ui=μ+bu+bi+qi⊤(pu+∣N(u)∣−1/2∑j∈N(u)yj),\hat r_{ui} = \mu + b_u + b_i + q_i^\top \Bigl( p_u + |N(u)|^{-1/2} \sum_{j \in N(u)} y_j \Bigr),

with μ\mu the mean rating, biases bu,bib_u, b_i, and vectors pu,qi,yj∈Rrp_u, q_i, y_j \in \mathbb{R}^r. Write zuz_u for the vector in the parentheses; the sum is 0 when N(u)N(u) is empty. With eui=rui−r^uie_{ui} = r_{ui} - \hat r_{ui}, training minimizes

J=∑(u,i)∈K[eui2+λb(bu2+bi2)+λf(∥pu∥2+∥qi∥2+∑j∈N(u)∥yj∥2)],J = \sum_{(u, i) \in K} \Bigl[ e_{ui}^2 + \lambda_b \bigl( b_u^2 + b_i^2 \bigr) + \lambda_f \Bigl( \lVert p_u \rVert^2 + \lVert q_i \rVert^2 + \sum_{j \in N(u)} \lVert y_j \rVert^2 \Bigr) \Bigr],

with the penalties inside the sum over the ratings, as in the paper. Like plain matrix factorization, JJ is not convex, and training finds a model with a low value, not a certified minimum.

The algorithm

  1. FIT(K, N, r, λ_b, λ_f, γ, E, decay)
  2. 1μ ← the mean of the ratings in K; b_u, b_i ← 0; p_u, q_i, y_j ← small random vectors
  3. 2repeat E times
  4. 3for each (u, i) in K, in a new random order, do
  5. 4z ← p_u + |N(u)|^(-1/2) Σ_{j ∈ N(u)} y_j
  6. 5e ← r_ui - (μ + b_u + b_i + q_i·z)
  7. 6b_u ← b_u + γ (e - λ_b b_u); b_i ← b_i + γ (e - λ_b b_i)
  8. 7(q_i, p_u) ← (q_i + γ (e z - λ_f q_i), p_u + γ (e q_i - λ_f p_u))
  9. 8y_j ← y_j + γ (e |N(u)|^(-1/2) q_i - λ_f y_j) for each j in N(u) ▷ the old q_i
  10. 9γ ← decay · γ
  11. 10return μ, b, p, q, y
  12. PREDICT(u, i)
  13. 11return μ + b_u + b_i + q_i·(p_u + |N(u)|^(-1/2) Σ_{j ∈ N(u)} y_j)

Lines L6 to L8 are the gradient steps that Koren gives for the factor part of the integrated model of Section 5, with one step size in place of his γ1\gamma_1 for the biases and γ2\gamma_2 for the vectors. For that model he reports γ1=γ2=0.007\gamma_1 = \gamma_2 = 0.007, λ6=0.005\lambda_6 = 0.005 for the biases, λ7=0.015\lambda_7 = 0.015 for the vectors, and a decrease of the step sizes by a factor of 0.9 after each iteration. The defaults of the code on this page follow these values.

Example

Use the toy rating matrix of this group, with N(u)N(u) the items each user rated:

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 and the hand-set parameters μ=3\mu = 3, bu=(0.2,0.5,−0.5,−1)b_u = (0.2, 0.5, -0.5, -1), bi=0b_i = 0, p=(0.5,0.5,−0.5,−0.5)p = (0.5, 0.5, -0.5, -0.5), q=(1,1,1,−1)q = (1, 1, 1, -1) and y=(0.4,0.4,0.4,−0.4)y = (0.4, 0.4, 0.4, -0.4). These values are not trained; they only show how the user vector works.

prediction N(u)N(u) ∑j∈N(u)yj\sum_{j \in N(u)} y_j zuz_u r^ui\hat r_{ui}
u1u_1, i3i_3 i1,i2,i4i_1, i_2, i_4 0.4 0.5+0.4/3≈0.73090.5 + 0.4/\sqrt{3} \approx 0.7309 3+0.2+0.7309≈3.9313 + 0.2 + 0.7309 \approx 3.931
u4u_4, i1i_1 i2,i3,i4i_2, i_3, i_4 0.4 −0.5+0.4/3≈−0.2691-0.5 + 0.4/\sqrt{3} \approx -0.2691 3−1−0.2691≈1.7313 - 1 - 0.2691 \approx 1.731
u4u_4, i1i_1, after a view of i1i_1 i1,i2,i3,i4i_1, i_2, i_3, i_4 0.8 −0.5+0.8/2=−0.1-0.5 + 0.8/2 = -0.1 3−1−0.1=1.93 - 1 - 0.1 = 1.9

In the last row, u4u_4 has viewed i1i_1 without rating it. Nothing was retrained, but i1i_1 entered N(u4)N(u_4), its vector yi1=0.4y_{i_1} = 0.4 entered the sum, and the prediction for u4u_4 rose. Plain matrix factorization with the same pp, qq and biases would give 3−1−0.5=1.53 - 1 - 0.5 = 1.5 in both rows for u4u_4, with or without the view.

Correctness

The proof in proofs/correctness.md shows the following. The term ℓui\ell_{ui} of one rating in JJ depends only on bub_u, bib_i, pup_u, qiq_i and the yjy_j with j∈N(u)j \in N(u). Its gradient is −2euizu+2λfqi-2 e_{ui} z_u + 2 \lambda_f q_i in qiq_i, −2euiqi+2λfpu-2 e_{ui} q_i + 2 \lambda_f p_u in pup_u, and −2eui∣N(u)∣−1/2qi+2λfyj-2 e_{ui} |N(u)|^{-1/2} q_i + 2 \lambda_f y_j in each yjy_j, with the bias parts as in matrix factorization. So lines L4 to L8 make the step θ←θ−(γ/2)∇ℓui(θ)\theta \leftarrow \theta - (\gamma / 2) \nabla \ell_{ui}(\theta), with all parts at the old values, and the method is stochastic gradient descent on JJ. When every N(u)N(u) is empty, the prediction, the objective and the steps are those of biased matrix factorization with λb\lambda_b for the biases and λf\lambda_f for the vectors. As for matrix factorization, no convergence result is claimed.

Proof: The SVD++ update is a scaled gradient step on one term of its objective and reduces to biased matrix factorizationfull

The notation is that of the page. For a user uu let νu=∣N(u)∣−1/2\nu_u = |N(u)|^{-1/2} when N(u)N(u) is not empty and νu=0\nu_u = 0 otherwise, and zu=pu+νu∑j∈N(u)yjz_u = p_u + \nu_u \sum_{j \in N(u)} y_j. Then r^ui=μ+bu+bi+qi⊤zu\hat r_{ui} = \mu + b_u + b_i + q_i^\top z_u, eui=rui−r^uie_{ui} = r_{ui} - \hat r_{ui}, and for (u,i)∈K(u, i) \in K

ℓui=eui2+λb(bu2+bi2)+λf(∥pu∥2+∥qi∥2+∑j∈N(u)∥yj∥2),J=∑(u,i)∈Kℓui.\ell_{ui} = e_{ui}^2 + \lambda_b \bigl( b_u^2 + b_i^2 \bigr) + \lambda_f \Bigl( \lVert p_u \rVert^2 + \lVert q_i \rVert^2 + \sum_{j \in N(u)} \lVert y_j \rVert^2 \Bigr), \qquad J = \sum_{(u, i) \in K} \ell_{ui}.

The parameters are θ=(b,p,q,y)\theta = (b, p, q, y); μ\mu is fixed by line L1, and NN is part of the input. All statements are about exact arithmetic.

Lemma 1 (the gradient of one term). ℓui\ell_{ui} depends only on bub_u, bib_i, pup_u, qiq_i and the yjy_j with j∈N(u)j \in N(u), and

∂ℓui∂bu=−2eui+2λbbu,∂ℓui∂bi=−2eui+2λbbi,\frac{\partial \ell_{ui}}{\partial b_u} = -2 e_{ui} + 2 \lambda_b b_u, \qquad \frac{\partial \ell_{ui}}{\partial b_i} = -2 e_{ui} + 2 \lambda_b b_i,
∇qiℓui=−2euizu+2λfqi,∇puℓui=−2euiqi+2λfpu,∇yjℓui=−2euiνuqi+2λfyj (j∈N(u)).\nabla_{q_i} \ell_{ui} = -2 e_{ui} z_u + 2 \lambda_f q_i, \qquad \nabla_{p_u} \ell_{ui} = -2 e_{ui} q_i + 2 \lambda_f p_u, \qquad \nabla_{y_j} \ell_{ui} = -2 e_{ui} \nu_u q_i + 2 \lambda_f y_j \ (j \in N(u)).

Proof. The prediction uses only the listed parameters, and so do the penalties of the term. Since zuz_u is linear in pup_u and in each yjy_j, with ∂zu/∂pu=I\partial z_u / \partial p_u = I and ∂zu/∂yj=νuI\partial z_u / \partial y_j = \nu_u I, the derivative of euie_{ui} is −zu-z_u in qiq_i, −qi-q_i in pup_u, −νuqi-\nu_u q_i in yjy_j, and −1-1 in each bias. The chain rule gives 2eui2 e_{ui} times these for eui2e_{ui}^2, and the penalties add 2λ2 \lambda times the parameter. Item ii may itself be in N(u)N(u); then qiq_i and yiy_i are still two separate parameters, and the formulas hold as stated. □\square

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

Proof. Line L4 computes z=zu(θ)z = z_u(\theta) and line L5 computes e=eui(θ)e = e_{ui}(\theta). Line L6 sets bu′=bu−(γ/2)(−2e+2λbbu)b_u' = b_u - (\gamma / 2)(-2 e + 2 \lambda_b b_u), and the same for bib_i. Line L7 sets qi′=qi−(γ/2)(−2ez+2λfqi)q_i' = q_i - (\gamma / 2)(-2 e z + 2 \lambda_f q_i) and pu′=pu−(γ/2)(−2eqi+2λfpu)p_u' = p_u - (\gamma / 2)(-2 e q_i + 2 \lambda_f p_u) with the old qiq_i and pup_u, and line L8 sets yj′=yj−(γ/2)(−2eνuqi+2λfyj)y_j' = y_j - (\gamma / 2)(-2 e \nu_u q_i + 2 \lambda_f y_j) with the old qiq_i. By Lemma 1 these are the coordinates of θ−(γ/2)∇ℓui(θ)\theta - (\gamma / 2) \nabla \ell_{ui}(\theta), and all other coordinates of the gradient are 0, matching the parameters that the lines do not touch. □\square

As for matrix factorization, if (u,i)(u, i) is drawn uniformly from KK, the expected step is −(γ/2s)∇J(θ)-(\gamma / 2 s) \nabla J(\theta), by linearity.

Proposition 3 (reduction to biased matrix factorization). If N(u)N(u) is empty for every user, then r^ui=μ+bu+bi+pu⊤qi\hat r_{ui} = \mu + b_u + b_i + p_u^\top q_i, JJ is the objective of biased matrix factorization with the penalty λb\lambda_b on the biases and λf\lambda_f on the vectors, inside the sum over the ratings, and lines L4 to L8 make the step of that method, with no change to any yjy_j.

Proof. With N(u)N(u) empty, νu=0\nu_u = 0 and the sum is empty, so zu=puz_u = p_u and the penalty on yy in ℓui\ell_{ui} is 0. Line L7 becomes qi′=qi+γ(epu−λfqi)q_i' = q_i + \gamma (e p_u - \lambda_f q_i) and pu′=pu+γ(eqi−λfpu)p_u' = p_u + \gamma (e q_i - \lambda_f p_u) with old values, which is line L7 of matrix factorization, and line L8 has no jj to visit. □\square

Proposition 4 (rotations). For an orthogonal r×rr \times r matrix QQ, replacing every pup_u, qiq_i and yjy_j by QpuQ p_u, QqiQ q_i and QyjQ y_j keeps every prediction and JJ.

Proof. zuz_u becomes QzuQ z_u by linearity, (Qqi)⊤(Qzu)=qi⊤zu(Q q_i)^\top (Q z_u) = q_i^\top z_u, and orthogonal matrices keep norms. □\square

Proposition 5 (cost). One step costs O((∣N(u)∣+1)r)O((|N(u)| + 1) r), so one epoch costs O(r∑(u,i)∈K(∣N(u)∣+1))O(r \sum_{(u, i) \in K} (|N(u)| + 1)), which is at most O(sdr)O(s d r) with d=max⁡u∣N(u)∣d = \max_u |N(u)|.

Proof. Line L4 adds ∣N(u)∣|N(u)| vectors of length rr, lines L5 to L7 cost O(r)O(r), and line L8 updates ∣N(u)∣|N(u)| vectors of length rr. Line L3 visits each rating once per epoch, and the random order costs O(s)O(s). □\square

If the ratings of one user are processed together with zuz_u computed once and the updates of the yjy_j added up and applied after the last rating of the user, the cost of an epoch drops to O(sr+r∑u∣N(u)∣)O(s r + r \sum_u |N(u)|). Theorem 2 does not cover that schedule: within one user, its later steps use the old zuz_u and the old yjy_j, so it is a different sequence of steps. No convergence result is claimed for either schedule; JJ is not convex.

Complexity

The model is the word RAM with real numbers of fixed size. Let d=max⁡u∣N(u)∣d = \max_u |N(u)|.

  • One step. Line L4 sums ∣N(u)∣|N(u)| vectors of length rr, and line L8 updates the same vectors, so a step costs O(∣N(u)∣r+r)O(|N(u)| r + r), at most O(dr)O(d r).
  • One epoch. O(r∑(u,i)∈K(∣N(u)∣+1))O(r \sum_{(u, i) \in K} (|N(u)| + 1)), at most O(sdr)O(s d r). All EE epochs cost O(Esdr)O(E s d r). With N(u)N(u) the rated items, the sum is ∑u∣Iu∣(∣Iu∣+1)\sum_u |I_u| (|I_u| + 1), so heavy users dominate the cost.
  • Prediction. O(∣N(u)∣r)O(|N(u)| r) for the first item of a user, and O(r)O(r) for each further item once zuz_u is stored.
  • Space. m+nm + n biases and (m+2n)r(m + 2n) r numbers for pp, qq and yy, so O((m+n)r)O((m + n) r).

A common change to the order of the work processes all ratings of one user together, computes zuz_u once and adds up the updates of the yjy_j, so that an epoch costs O(sr+r∑u∣N(u)∣)O(s r + r \sum_u |N(u)|). This is a different sequence of steps from lines L3 to L8, not the same computation.

Properties

  • More signal per user. The vector zuz_u uses every item in N(u)N(u), including items without a rating, so a user with many views and few ratings gets more than pup_u alone.
  • Reduces to the biased model. With all N(u)N(u) empty, SVD++ is biased matrix factorization.
  • Shared item vectors. Each yjy_j is learned from all users with j∈N(u)j \in N(u), so a new implicit item of a known user changes zuz_u at once. A new user, however, still has no pup_u, and the paper notes that SVD++ needs retraining to handle new users, unlike its Asymmetric-SVD.
  • Not unique. A joint rotation of all pup_u, qiq_i and yjy_j by the same orthogonal matrix keeps every prediction and JJ.
  • Randomized and approximate. The result depends on the random start and the order of the ratings.

Variants and improvements

  • Asymmetric-SVD. Equation 13 of the paper drops pup_u and builds the user from two normalized sums, one over the rated items weighted by the rating minus its baseline, and one over N(u)N(u). It has fewer parameters, handles a new user as soon as the user gives feedback, and explains a prediction by the user's own past actions. It builds on the NSVD model of Paterek, which also represents a user through the items the user rated.
  • The integrated model. Equation 16 adds to SVD++ the global neighborhood model of Section 3 of the paper, with learned item to item weights over the kk most similar items.
  • Time effects. Koren's later timeSVD++ lets the biases and the user vector change over time.
  • Other implicit sets. N(u)N(u) can hold purchases, clicks or views. The model then joins explicit ratings with implicit feedback.
  • Factorization machines. A factorization machine with the user, the item and the normalized set N(u)N(u) as features contains the SVD++ prediction, plus further pairwise terms between the items of N(u)N(u).
  • Training by ALS. With all other parameters fixed, the pp block and the qq block have ridge regression updates as in alternating least squares. The yjy_j of one user enter the same sum, so their problem does not split item by item. The paper trains all parameters by gradient steps.

When to use it

Use SVD++ for explicit ratings when the system also knows which items each user touched, and when accuracy of the rating prediction matters more than the cost of training. Koren (2008, Table 1) reports test RMSE on the Netflix data of 0.8952, 0.8924 and 0.8911 for SVD++ with 50, 100 and 200 factors, against 0.9046, 0.9025 and 0.9009 for the biased factor model and 0.9037, 0.9013 and 0.9000 for Asymmetric-SVD. These are measurements on one data set. When there are no ratings at all, only implicit data, use a model made for implicit data such as ALS for implicit feedback. When new users must be served at once, Asymmetric-SVD or a neighborhood method avoids retraining.

Pitfalls

  • Cost of heavy users. A user with thousands of items in N(u)N(u) makes each of the user's steps cost thousands of vector updates. Group the steps by user, or cap N(u)N(u).
  • The wrong qiq_i in line L8. The steps for pup_u and the yjy_j use the value of qiq_i from before line L7. Using the new value is a different step, close to the old one for small γ\gamma.
  • Leaking the target. When N(u)N(u) is the set of rated items and the model is evaluated on held out ratings, build N(u)N(u) only from information that the system would have at prediction time. If the held out item is in N(u)N(u) only because it was rated, the evaluation tells the model which items the user chose, and the measured error can be too low.
  • Penalty on yy. The penalty λf∑j∈N(u)∥yj∥2\lambda_f \sum_{j \in N(u)} \lVert y_j \rVert^2 appears in the term of every rating of uu, so popular implicit items are penalized many times. Tune λf\lambda_f for this form.
  • Empty N(u)N(u). Skip the normalization when N(u)N(u) is empty, rather than divide by zero.

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.

recs.pyI0RawGitHub
# 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
svd_plus_plus.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/svd-plus-plus/. The authors are listed in prov/87CAT3.jsonl.

"""SVD++ (Koren 2008), trained by SGD.

The prediction is

    mu + b_u + b_i + q_i . (p_u + |N(u)|^(-1/2) sum over j in N(u) of y_j)

where N(u) is the set of items with implicit feedback from user u (by
default the items that u rated in the training set). The objective puts
the penalties once on each rating:

    J = sum over (u, i) in K of [ e_ui^2 + lb (b_u^2 + b_i^2)
          + lf (|p_u|^2 + |q_i|^2 + sum over j in N(u) of |y_j|^2) ]

One SGD step on (u, i), with e = r_ui - prediction, z = p_u + |N(u)|^(-1/2) sum y_j
and the old values on the right side, is

    b_u <- b_u + g (e - lb b_u)          b_i <- b_i + g (e - lb b_i)
    q_i <- q_i + g (e z - lf q_i)        p_u <- p_u + g (e q_i - lf p_u)
    y_j <- y_j + g (e |N(u)|^(-1/2) q_i - lf y_j)   for each j in N(u)

This is theta - (g / 2) times the gradient of the term of (u, i) in J.
"""

import math
import random


class Model:
    def __init__(self, m, n, r, mu, implicit):
        self.m, self.n, self.r, self.mu = m, n, r, mu
        self.implicit = {u: sorted(set(js)) for u, js in implicit.items()}
        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)]
        self.y = [[0.0] * r for _ in range(n)]

    def user_vector(self, u):
        """z_u = p_u + |N(u)|^(-1/2) times the sum of y_j over N(u)."""
        z = self.p[u][:]
        nu = self.implicit.get(u, [])
        if nu:
            s = 1.0 / math.sqrt(len(nu))
            for j in nu:
                yj = self.y[j]
                for f in range(self.r):
                    z[f] += s * yj[f]
        return z

    def predict(self, u, i):
        z = self.user_vector(u)
        return self.mu + self.bu[u] + self.bi[i] + sum(a * b for a, b in zip(self.q[i], z))  # @line L11


def implicit_from(train):
    """N(u) = the items that u rated in train."""
    out = {}
    for u, i in train:
        out.setdefault(u, []).append(i)
    return out


def init(m, n, r, train, seed, implicit=None, scale=0.1):
    rng = random.Random(seed)
    mu = sum(train.values()) / len(train)  # @line L1
    model = Model(m, n, r, mu, implicit_from(train) if implicit is None else implicit)
    model.p = [[rng.gauss(0.0, scale) for _ in range(r)] for _ in range(m)]
    model.q = [[rng.gauss(0.0, scale) for _ in range(r)] for _ in range(n)]
    model.y = [[rng.gauss(0.0, scale) for _ in range(r)] for _ in range(n)]
    return model


def objective(model, train, lb, lf):
    total = 0.0
    for (u, i), v in train.items():
        e = v - model.predict(u, i)
        reg_f = sum(a * a for a in model.p[u]) + sum(b * b for b in model.q[i])
        for j in model.implicit.get(u, []):
            reg_f += sum(c * c for c in model.y[j])
        total += e * e + lb * (model.bu[u] ** 2 + model.bi[i] ** 2) + lf * reg_f
    return total


def gradient(model, train, lb, lf):
    """The exact gradient of J: (d bu, d bi, d p, d q, d y)."""
    r = model.r
    gbu = [0.0] * model.m
    gbi = [0.0] * model.n
    gp = [[0.0] * r for _ in range(model.m)]
    gq = [[0.0] * r for _ in range(model.n)]
    gy = [[0.0] * r for _ in range(model.n)]
    for (u, i), v in train.items():
        z = model.user_vector(u)
        e = v - (model.mu + model.bu[u] + model.bi[i] + sum(a * b for a, b in zip(model.q[i], z)))
        gbu[u] += -2.0 * e + 2.0 * lb * model.bu[u]
        gbi[i] += -2.0 * e + 2.0 * lb * model.bi[i]
        nu = model.implicit.get(u, [])
        s = 1.0 / math.sqrt(len(nu)) if nu else 0.0
        for f in range(r):
            gq[i][f] += -2.0 * e * z[f] + 2.0 * lf * model.q[i][f]
            gp[u][f] += -2.0 * e * model.q[i][f] + 2.0 * lf * model.p[u][f]
            for j in nu:
                gy[j][f] += -2.0 * e * s * model.q[i][f] + 2.0 * lf * model.y[j][f]
    return gbu, gbi, gp, gq, gy


def sgd_step(model, u, i, v, lb, lf, gamma):
    z = model.user_vector(u)  # @line L4
    e = v - (model.mu + model.bu[u] + model.bi[i] + sum(a * b for a, b in zip(model.q[i], z)))  # @line L5
    model.bu[u] += gamma * (e - lb * model.bu[u])  # @line L6
    model.bi[i] += gamma * (e - lb * model.bi[i])
    nu = model.implicit.get(u, [])
    s = 1.0 / math.sqrt(len(nu)) if nu else 0.0
    qi_old = model.q[i][:]
    pu, qi = model.p[u], model.q[i]
    for f in range(model.r):
        qi[f] += gamma * (e * z[f] - lf * qi[f])  # @line L7
        pu[f] += gamma * (e * qi_old[f] - lf * pu[f])
    for j in nu:
        yj = model.y[j]
        for f in range(model.r):
            yj[f] += gamma * (e * s * qi_old[f] - lf * yj[f])  # @line L8


def sgd_epoch(model, train, lb, lf, gamma, order):
    for u, i in order:
        sgd_step(model, u, i, train[(u, i)], lb, lf, gamma)


def fit(train, m, n, r, lb=0.005, lf=0.015, gamma=0.007, epochs=30, seed=1, implicit=None, decay=0.9):
    """Train by SGD; the step size is multiplied by decay after each epoch."""
    rng = random.Random(seed)
    model = init(m, n, r, train, seed, implicit)
    keys = sorted(train)
    for _ in range(epochs):  # @line L2
        rng.shuffle(keys)  # @line L3
        sgd_epoch(model, train, lb, lf, gamma, keys)
        gamma *= decay  # @line L9
    return model  # @line L10
test_svd_plus_plus.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/svd-plus-plus/. The authors are listed in prov/87CAT3.jsonl.

import math
import random

import recs
import svd_plus_plus as spp

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, implicit=None):
    rng = random.Random(seed)
    model = spp.init(m, n, r, train, seed, implicit, scale=0.5)
    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):
    out = [(model.bu, u) for u in range(model.m)]
    out += [(model.bi, i) for i in range(model.n)]
    for mat in (model.p, model.q, model.y):
        out += [(row, f) for row in mat for f in range(model.r)]
    return out


def flat_gradient(model, train, lb, lf):
    gbu, gbi, gp, gq, gy = spp.gradient(model, train, lb, lf)
    out = gbu + gbi
    for row in gp + gq + gy:
        out += row
    return out


def test_gradient_matches_central_differences():
    full = recs.planted(5, 5, 2, 7, noise=0.2)
    train, _ = recs.split(full, 0.3, 7)
    # Implicit sets with an item the user did not rate.
    implicit = spp.implicit_from(train)
    implicit[0] = sorted(set(implicit[0]) | {4})
    model = random_model(5, 5, 2, train, 3, implicit)
    lb, lf = 0.1, 0.3
    g = flat_gradient(model, train, lb, lf)
    for (vec, k), gk in zip(params(model), g):
        old = vec[k]
        vec[k] = old + H
        up = spp.objective(model, train, lb, lf)
        vec[k] = old - H
        down = spp.objective(model, train, lb, lf)
        vec[k] = old
        assert abs((up - down) / (2 * H) - gk) <= TOL * max(1.0, abs(gk))


def test_sgd_step_is_half_gradient_step_on_one_rating():
    full = recs.planted(4, 5, 2, 9)
    train, _ = recs.split(full, 0.3, 9)
    lb, lf, gamma = 0.05, 0.1, 0.03
    for (u, i), v in sorted(train.items()):
        model = random_model(4, 5, 2, train, 10 * u + i)
        g = flat_gradient(model, {(u, i): v}, lb, lf)
        before = [vec[k] for vec, k in params(model)]
        spp.sgd_step(model, u, i, v, lb, lf, 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_reduces_to_biased_factorization():
    """With every N(u) empty, SVD++ is the biased model trained the same way."""
    full = recs.planted(6, 5, 2, 2, noise=0.2)
    train, _ = recs.split(full, 0.3, 2)
    model = random_model(6, 5, 2, train, 5, implicit={})
    lam, gamma = 0.05, 0.02
    twin = {"bu": model.bu[:], "bi": model.bi[:], "p": [r[:] for r in model.p], "q": [r[:] for r in model.q]}
    order = sorted(train)
    random.Random(1).shuffle(order)
    spp.sgd_epoch(model, train, lam, lam, gamma, order)
    for u, i in order:  # the biased factorization step, written out
        v = train[(u, i)]
        e = v - (model.mu + twin["bu"][u] + twin["bi"][i] + sum(a * b for a, b in zip(twin["p"][u], twin["q"][i])))
        twin["bu"][u] += gamma * (e - lam * twin["bu"][u])
        twin["bi"][i] += gamma * (e - lam * twin["bi"][i])
        pu, qi = twin["p"][u], twin["q"][i]
        for f in range(2):
            a, b = pu[f], qi[f]
            pu[f] = a + gamma * (e * b - lam * a)
            qi[f] = b + gamma * (e * a - lam * b)
    assert all(abs(a - b) < 1e-12 for a, b in zip(model.bu, twin["bu"]))
    assert all(abs(a - b) < 1e-12 for a, b in zip(model.bi, twin["bi"]))
    for mat, other in ((model.p, twin["p"]), (model.q, twin["q"])):
        for ra, rb in zip(mat, other):
            assert all(abs(a - b) < 1e-12 for a, b in zip(ra, rb))


def test_toy_user_vector():
    train = recs.toy()
    model = spp.Model(4, 4, 1, 3.0, spp.implicit_from(train))
    model.bu = [0.2, 0.5, -0.5, -1.0]
    model.p = [[0.5], [0.5], [-0.5], [-0.5]]
    model.q = [[1.0], [1.0], [1.0], [-1.0]]
    model.y = [[0.4], [0.4], [0.4], [-0.4]]
    assert abs(model.user_vector(0)[0] - (0.5 + 0.4 / math.sqrt(3))) < 1e-12
    assert abs(model.predict(0, 2) - (3.7 + 0.4 / math.sqrt(3))) < 1e-12
    assert abs(model.predict(3, 0) - (1.5 + 0.4 / math.sqrt(3))) < 1e-12
    model.implicit[3] = [0, 1, 2, 3]  # user 4 also viewed item 1, with no rating
    assert abs(model.predict(3, 0) - 1.9) < 1e-12


def test_training_lowers_objective_and_beats_the_mean():
    full = recs.planted(20, 15, 2, 6, noise=0.1)
    train, hidden = recs.split(full, 0.3, 6)
    lb, lf = 0.005, 0.015
    start = spp.init(20, 15, 2, train, 2)
    model = spp.fit(train, 20, 15, 2, lb=lb, lf=lf, gamma=0.02, epochs=150, seed=2, decay=1.0)
    assert spp.objective(model, train, lb, lf) < 0.2 * spp.objective(start, train, lb, lf)
    mu = recs.global_mean(train)
    assert recs.rmse(model.predict, hidden) < recs.rmse(lambda u, i: mu, hidden)

History

Koren presented SVD++ at KDD 2008 in a paper that also introduced a global neighborhood model and Asymmetric-SVD, and that combined the neighborhood model and SVD++ in one integrated model. The work came out of the Netflix Prize, where his team used the binary information of which films each user rated. Koren, Bell and Volinsky (2009) describe the same normalized sum of item vectors as a way to add implicit inputs to matrix factorization.

References

  1. 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.5 (implicit feedback as the binary matrix of rated and not rated), Section 4 (Asymmetric-SVD, Equation 13, and SVD++, Equation 15, with Table 1), Section 5 (the integrated model, Equation 16, its gradient steps and the values of the meta parameters)
  2. Yehuda Koren, Robert Bell and Chris Volinsky, Matrix factorization techniques for recommender systems, IEEE Computer 42(8), 30-37, 2009, section Additional input sources (the normalized sum of item vectors over the items with implicit preference)
  3. Charu C. Aggarwal, Recommender Systems, The Textbook, Springer, 2016, Chapter 3, Section 3.6 (latent factor models)

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