Algorithm Search⌘K

Algorithmresearch

Neural collaborative filtering

Also called NCF, NeuMF.

Replaces the dot product of matrix factorization by a neural network over user and item embeddings, trained on implicit feedback.

Time
O(E s (q + 1) (k + P)) worst
Space
O((m + n) k + P) extra
Where
E = the number of epochs; P = the number of weights of the hidden layers; k = the embedding size; m = the number of users; n = the number of items; q = the number of negatives per positive; s = the number of positive pairs
Properties
randomizednot exactofflineiterative
Origin
Xiangnan He, Lizi Liao, Hanwang Zhang, Liqiang Nie, Xia Hu, Tat Seng Chua, 2017

Neural collaborative filtering (NCF) is a family of models of He, Liao, Zhang, Nie, Hu and Chua (2017) that score a user and an item with a neural network over their embeddings in place of the dot product of matrix factorization. GMF multiplies the two embeddings entry by entry and applies learned weights; the MLP part feeds the concatenated embeddings through layers of ReLU units; and NeuMF adds the two, each with its own embeddings. The models are trained on implicit feedback with the log loss, with sampled unused items as negatives. The paper reported that NeuMF ranked better than the baselines it tested. Rendle, Krichene, Zhang and Anderson (2020) reran the same experiments and measured a different result: a well-tuned dot product did better than the learned MLP similarity in their experiments.

In plain words

Matrix factorization scores a user and an item by multiplying their profiles number by number and adding up. NCF asks whether a small neural network could learn a better way to combine the two profiles. It keeps the multiply-and-add path, adds a second path that runs the profiles through a network, and learns how much to trust each.

A network can in theory represent the dot product and much more. Whether it learns something better from real data is a question of experiment, and the experiments disagree with the original claim when the simple baseline is tuned with care.

The problem

The input is a set SS of positive pairs of mm users and nn items, an embedding size kk, the widths of the hidden layers, and a number qq of negatives per positive. NeuMF (Section 3.4, Equation 12) computes

φG=puG⊙qiG,z0=[puM;qiM],zl=ReLU(Wlzl−1+bl)    (l=1,…,L),\varphi^{G} = p_u^G \odot q_i^G, \qquad z_0 = [p_u^M ; q_i^M], \qquad z_l = \mathrm{ReLU}(W_l z_{l-1} + b_l) \;\; (l = 1, \dots, L),
y^ui=σ(h⊤[φG;zL]),\hat y_{ui} = \sigma\bigl(h^\top [\varphi^{G} ; z_L]\bigr),

with separate embeddings pG,qGp^G, q^G for the GMF part and pM,qMp^M, q^M for the MLP part. The training set has label y=1y = 1 for each pair of SS, and label y=0y = 0 for qq items drawn uniformly from the items the user has not used. The loss is the log loss of Equation 7,

L=−∑(u,i)∈Sln⁡y^ui−∑(u,j)∈S−ln⁡(1−y^uj).L = -\sum_{(u, i) \in S} \ln \hat y_{ui} - \sum_{(u, j) \in S^-} \ln(1 - \hat y_{uj}).

The output is a score for each user and item, and the recommendation is the unused items in order of score.

The algorithm

  1. NCF-TRAIN(S, k, widths, q, E, η)
  2. 1draw all embeddings and weights from a Gaussian with a small spread
  3. 2repeat E times
  4. 3D ← {(u, i, 1) : (u, i) ∈ S} ∪ {(u, j, 0) : q random unused j for each (u, i) ∈ S}
  5. 4for each (u, i, y) in D, in random order do
  6. 5s ← SCORE(u, i)
  7. 6step every parameter used in L5 against the gradient of -y ln σ(s) - (1 - y) ln σ(-s)
  8. 7return the parameters
  9. SCORE(u, i)
  10. 8g ← p_u^G ⊙ q_i^G ▷ GMF part
  11. 9z ← [p_u^M ; q_i^M] ▷ MLP part
  12. 10for each hidden layer l do z ← ReLU(W_l z + b_l)
  13. 11return hᵀ[g ; z] ▷ the logit; the prediction is σ of it

The gradient of line L6 comes from backpropagation: the derivative of the loss in the logit is σ(s)−y\sigma(s) - y, the top layer passes (σ(s)−y)h(\sigma(s) - y) h down, and each ReLU layer passes Wl⊤W_l^\top times the derivative of its active units. The code writes all of it by hand and checks every entry against finite differences. The paper uses Adam, and for NeuMF it first trains GMF and the MLP alone and then joins them with weight α=0.5\alpha = 0.5 on each part (Section 3.4.1). The code uses plain stochastic gradient steps and no pre-training.

Example

Take k=2k = 2 and one hidden layer of width 2. Let puG=(1,2)p_u^G = (1, 2), qiG=(0.5,−1)q_i^G = (0.5, -1), puM=(1,0)p_u^M = (1, 0), qiM=(0,1)q_i^M = (0, 1),

W1=(1−1100111),b1=(0,−0.5),h=(1,0.5,2,−1).W_1 = \begin{pmatrix} 1 & -1 & 1 & 0 \\ 0 & 1 & 1 & 1 \end{pmatrix}, \qquad b_1 = (0, -0.5), \qquad h = (1, 0.5, 2, -1).
  • Line L8: g=(0.5,−2)g = (0.5, -2).
  • Line L9: z0=(1,0,0,1)z_0 = (1, 0, 0, 1).
  • Line L10: W1z0+b1=(1,1−0.5)=(1,0.5)W_1 z_0 + b_1 = (1, 1 - 0.5) = (1, 0.5), and both units are active, so z1=(1,0.5)z_1 = (1, 0.5).
  • Line L11: s=1⋅0.5+0.5⋅(−2)+2⋅1+(−1)⋅0.5=1s = 1 \cdot 0.5 + 0.5 \cdot (-2) + 2 \cdot 1 + (-1) \cdot 0.5 = 1, so y^=σ(1)≈0.7311\hat y = \sigma(1) \approx 0.7311.

For a positive example, ∂L/∂s=σ(1)−1≈−0.2689\partial L / \partial s = \sigma(1) - 1 \approx -0.2689. The gradient for the third entry of hh is that times z1,1=1z_{1,1} = 1, and the gradient for W1W_1 in row 2, column 4 is that times h4=−1h_4 = -1 times z0,4=1z_{0,4} = 1, about 0.26890.2689. A step against these gradients raises ss. The test file checks these values.

With h=(1,1,0,0)h = (1, 1, 0, 0) the MLP part is switched off and the score is puG⊤qiG=0.5−2=−1.5p_u^{G\top} q_i^G = 0.5 - 2 = -1.5, the plain dot product.

Correctness

The proof in proofs/correctness.md shows that the hand-written backward pass is the exact gradient of the log loss at every point where no hidden unit is exactly at 0, by the chain rule applied layer by layer from the top. It also shows that matrix factorization is the special case hG=1h^G = \mathbf{1}, hM=0h^M = 0, so NeuMF can represent every score that matrix factorization can. That does not mean that training finds a better model: the loss is not convex, and which model ranks better on held-out data is measured, not proved.

Proof: The hand-written backward pass of NeuMF is the gradient of the log loss, and matrix factorization is a special case of the modelfull

The notation is that of the page. For one example (u,i,y)(u, i, y) with y∈{0,1}y \in \{0, 1\}, the forward pass computes

g=puG⊙qiG,z0=[puM;qiM],al=Wlzl−1+bl,zl=ReLU(al)  (l=1,…,L),φ=[g;zL],s=h⊤φ,g = p_u^G \odot q_i^G, \quad z_0 = [p_u^M; q_i^M], \quad a_l = W_l z_{l-1} + b_l, \quad z_l = \mathrm{ReLU}(a_l) \; (l = 1, \dots, L), \quad \varphi = [g; z_L], \quad s = h^\top \varphi,

and the loss is ℓ=−yln⁡σ(s)−(1−y)ln⁡(1−σ(s))\ell = -y \ln \sigma(s) - (1 - y) \ln(1 - \sigma(s)). The claims are about exact arithmetic and about points where no entry of any ala_l is 0; at such a point every function in the chain is differentiable. At an entry al=0a_l = 0 the code uses the derivative 0 for ReLU, which is one element of its subdifferential.

Lemma 1 (the output). ∂ℓ/∂s=σ(s)−y\partial \ell / \partial s = \sigma(s) - y.

Proof. 1−σ(s)=σ(−s)1 - \sigma(s) = \sigma(-s), so ℓ=yln⁡(1+e−s)+(1−y)ln⁡(1+es)\ell = y \ln(1 + e^{-s}) + (1 - y) \ln(1 + e^{s}). The derivative of ln⁡(1+e−s)\ln(1 + e^{-s}) is −σ(−s)=σ(s)−1-\sigma(-s) = \sigma(s) - 1 and that of ln⁡(1+es)\ln(1 + e^{s}) is σ(s)\sigma(s). So ∂ℓ/∂s=y(σ(s)−1)+(1−y)σ(s)=σ(s)−y\partial \ell / \partial s = y (\sigma(s) - 1) + (1 - y) \sigma(s) = \sigma(s) - y. □\square

Write δ=σ(s)−y\delta = \sigma(s) - y.

Lemma 2 (the top layer and the GMF part). ∂ℓ/∂h=δ φ\partial \ell / \partial h = \delta\, \varphi and ∂ℓ/∂φ=δ h\partial \ell / \partial \varphi = \delta\, h. With h=[hG;hM]h = [h^G; h^M] split like φ\varphi, ∂ℓ/∂g=δhG\partial \ell / \partial g = \delta h^G, and

∂ℓ∂puG=δ hG⊙qiG,∂ℓ∂qiG=δ hG⊙puG.\frac{\partial \ell}{\partial p_u^G} = \delta\, h^G \odot q_i^G, \qquad \frac{\partial \ell}{\partial q_i^G} = \delta\, h^G \odot p_u^G.

Proof. s=h⊤φs = h^\top \varphi is bilinear, so its partial derivatives are φ\varphi and hh; multiply by δ\delta (chain rule). Entry cc of gg is pucGqicGp_{uc}^G q_{ic}^G, which depends only on entry cc of each vector, with partial derivatives qicGq_{ic}^G and pucGp_{uc}^G. □\square

Lemma 3 (one ReLU layer). Let dl=∂ℓ/∂zld_l = \partial \ell / \partial z_l be known. Then, with DlD_l the diagonal matrix with entries 11 where al>0a_l > 0 and 00 where al<0a_l < 0,

∂ℓ∂al=Dldl,∂ℓ∂Wl=(Dldl)zl−1⊤,∂ℓ∂bl=Dldl,dl−1=Wl⊤Dldl.\frac{\partial \ell}{\partial a_l} = D_l d_l, \qquad \frac{\partial \ell}{\partial W_l} = (D_l d_l) z_{l-1}^\top, \qquad \frac{\partial \ell}{\partial b_l} = D_l d_l, \qquad d_{l-1} = W_l^\top D_l d_l.

Proof. zl=ReLU(al)z_l = \mathrm{ReLU}(a_l) acts entry by entry with derivative 1 or 0 away from 0, which gives the first formula. Entry rr of ala_l is ∑cWl,rczl−1,c+bl,r\sum_c W_{l, rc} z_{l-1, c} + b_{l, r}, so ∂al,r/∂Wl,rc=zl−1,c\partial a_{l, r} / \partial W_{l, rc} = z_{l-1, c}, ∂al,r/∂bl,r=1\partial a_{l, r} / \partial b_{l, r} = 1, and ∂al,r/∂zl−1,c=Wl,rc\partial a_{l, r} / \partial z_{l-1, c} = W_{l, rc}; no other entry of ala_l depends on Wl,rcW_{l, rc} or bl,rb_{l, r}. The chain rule gives the three formulas. □\square

Theorem 4 (the backward pass is the gradient). The function backward adds to its buffers exactly ∂ℓ/∂θ\partial \ell / \partial \theta for every parameter θ\theta: the entries of hh, WlW_l, blb_l, of the rows puG,qiG,puM,qiMp_u^G, q_i^G, p_u^M, q_i^M, and zero for every other row of the embedding tables.

Proof. backward receives δ\delta (Lemma 1) and computes the derivatives of Lemma 2. It sets dL=δhMd_L = \delta h^M and applies Lemma 3 for l=L,L−1,…,1l = L, L - 1, \dots, 1, which is induction on the layers from the top: each step uses dld_l, correct by the previous step, and produces dl−1d_{l-1}. At the end d0=∂ℓ/∂z0d_0 = \partial \ell / \partial z_0, and since z0=[puM;qiM]z_0 = [p_u^M; q_i^M] is a concatenation, its first half is ∂ℓ/∂puM\partial \ell / \partial p_u^M and its second half is ∂ℓ/∂qiM\partial \ell / \partial q_i^M. The other rows of the tables do not appear in the forward pass of (u,i)(u, i), so their derivative is 0. For a set of examples the loss is a sum, and gradient adds the per-example gradients. □\square

The tests compare every entry of this gradient with a central finite difference on a model with two hidden layers, one hidden layer, and no hidden layer.

Proposition 5 (matrix factorization is a special case). If hG=1h^G = \mathbf{1} and hM=0h^M = 0, then s=(puG)⊤qiGs = (p_u^G)^\top q_i^G, the score of matrix factorization. If only hM=0h^M = 0, then s=∑chcG pucGqicGs = \sum_c h^G_c\, p_{uc}^G q_{ic}^G, the GMF model of He et al.

Proof. s=hG⊤(puG⊙qiG)+hM⊤zLs = h^{G\top} (p_u^G \odot q_i^G) + h^{M\top} z_L, and with hM=0h^M = 0 the second term vanishes; with hG=1h^G = \mathbf{1} the first term is ∑cpucGqicG\sum_c p_{uc}^G q_{ic}^G. □\square

So the set of score functions of NeuMF contains those of matrix factorization. This does not imply that training NeuMF finds a better score function than training matrix factorization does: the training problem is not convex, the larger model has more parameters to fit from the same data, and the comparison is an empirical question.

A training step. One step of train computes the gradient of the loss of one example by Theorem 4 and moves the parameters that the example uses against it. For an example drawn uniformly from the examples of an epoch, the expected gradient at fixed parameters is the gradient of the mean loss over those examples, by the linearity of the gradient. This page does not prove that the steps converge, or that they reach a good minimum. ■\blacksquare

Complexity

  • One example. The forward and backward passes cost O(k+P)O(k + P), where PP is the number of weights in the hidden layers.
  • One epoch. s(q+1)s (q + 1) examples, so O(s(q+1)(k+P))O(s (q + 1)(k + P)). The paper uses q=4q = 4.
  • Training. O(Es(q+1)(k+P))O(E s (q + 1)(k + P)) for EE epochs.
  • Space. O((m+n)k)O((m + n) k) for the four embedding tables and O(P)O(P) for the weights; a step touches only the four rows of uu and ii.
  • Serving. Ranking all nn items for one user costs nn forward passes, O(n(k+P))O(n (k + P)). A dot product model can use maximum inner product search instead, which is the cost argument of Section 5 of Rendle et al. (2020).

Properties

  • Contains matrix factorization. With the MLP weights of hh at 0 and the GMF weights at 1, the score is the dot product.
  • Not convex. The products of embeddings and the hidden layers make the loss non-convex.
  • Pointwise loss. Each example is scored alone, unlike the pairwise loss of BPR.
  • Costly to serve. The score is not an inner product of a user vector and an item vector, so standard fast retrieval does not apply.

Variants and improvements

  • GMF. Only the product part, σ(h⊤(pu⊙qi))\sigma(h^\top (p_u \odot q_i)); with h=1h = \mathbf{1} and no output nonlinearity it is matrix factorization.
  • MLP only. Only the concatenation part. The paper used a tower of layers that halve in width.
  • Pre-training. Train GMF and the MLP alone, then start NeuMF from both with α=0.5\alpha = 0.5 on each part.
  • Other losses. The pairwise loss of BPR can replace the log loss.
  • Sequence models. SASRec and GRU4Rec use neural networks over the item history in place of a user embedding.

When to use it

He et al. evaluated on MovieLens 1M (6,040 users, 3,706 items) and Pinterest (55,187 users, 9,916 items) with one held-out item per user ranked against 100 sampled items, measuring HR@10 and NDCG@10, and reported that NeuMF did better than their baselines.

Rendle, Krichene, Zhang and Anderson (2020) reran these experiments on the same splits and metrics, with a dot product model with biases trained by the same log loss and negative sampling, and with the hyperparameters chosen on a validation set. In their experiments the dot product beat the MLP on all data sets, metrics and embedding sizes they tried (dd from 16 to 192), and beat NeuMF except at one point, HR on MovieLens with d=192d = 192, where the pre-trained NeuMF was ahead. They also reported that the NCF numbers had been selected at the best iteration on the test set, as found by Ferrari Dacrema, Boglio, Cremonesi and Jannach (2019), and that an MLP trained only to fit a dot product still had a large error, which grew with the embedding size (their Section 4 and Figure 3). These are measurements on two data sets with one protocol. They do not prove that a dot product is always better, but they show that a tuned dot product is the baseline to beat. Use NCF when there is a reason to expect that the plain dot product is the wrong form, and compare it with a well-tuned matrix factorization.

Pitfalls

  • A weak baseline. The main lesson of the 2020 rerun: a matrix factorization baseline with poorly chosen hyperparameters makes any new model look good.
  • Selecting on the test set. Picking the best epoch by the test metric inflates the result. Use a validation split.
  • Sampled metrics. Ranking a held-out item among 100 sampled items is a different measure from ranking it among all items, so results under the two protocols are not comparable.
  • L2 on GMF. The weights hh can grow while the embeddings shrink, so an L2 penalty on the embeddings alone does not limit the model; Rendle et al. (2020, Section 3.3.3) make this point.
  • Serving cost. A model that needs a forward pass per item does not scale to large catalogs without a candidate generation stage.
  • ReLU at zero. A finite-difference gradient check fails near a unit that is exactly at 0. Check at random points, as the tests do.

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.

neural_collaborative_filtering.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/neural-collaborative-filtering/. The authors are listed in prov/9XDZVT.jsonl.

"""NeuMF, the neural collaborative filtering model of He et al. (WWW 2017), by hand.

The score of (u, i) is

    g   = pG_u * qG_i                          (GMF part, elementwise product)
    z_0 = [pM_u ; qM_i]                        (MLP part, concatenation)
    z_l = ReLU(W_l z_(l-1) + b_l)              for l = 1, ..., L
    s   = h . [g ; z_L],     y_hat = sigma(s)

and the loss of one example (u, i, y), with y in {0, 1}, is the log loss
-y ln y_hat - (1 - y) ln(1 - y_hat). The backward pass is written out by hand
and checked against finite differences in the tests. Training is plain SGD
with q negatives per positive, drawn uniformly from the unused items of the
user in each epoch. The paper trains with Adam and pre-trains the two parts;
this module does neither, to stay short.

Parameters are a dict of 2-D lists (vectors are 1 x d rows).
"""

import math
import random

Matrix = list[list[float]]
Params = dict[str, Matrix]


def sigmoid(z: float) -> float:
    if z >= 0:
        return 1.0 / (1.0 + math.exp(-z))
    e = math.exp(z)
    return e / (1.0 + e)


def softplus(z: float) -> float:
    """ln(1 + e^z) without overflow."""
    return z + math.log1p(math.exp(-z)) if z > 0 else math.log1p(math.exp(z))


def init(m: int, n: int, k: int, hidden: list[int], seed: int = 1, scale: float = 0.1) -> Params:
    """Gaussian start. hidden lists the widths of the ReLU layers. Cost O((m + n) k + sum of layer sizes)."""
    rng = random.Random(seed)

    def mat(r: int, c: int) -> Matrix:
        return [[rng.gauss(0.0, scale) for _ in range(c)] for _ in range(r)]

    p = {"PG": mat(m, k), "QG": mat(n, k), "PM": mat(m, k), "QM": mat(n, k)}  # @line L1
    width = 2 * k
    for l, w in enumerate(hidden):
        p[f"W{l}"] = mat(w, width)
        p[f"b{l}"] = mat(1, w)
        width = w
    p["h"] = mat(1, k + width)
    return p


def layers(p: Params) -> int:
    return sum(1 for name in p if name.startswith("W"))


def forward(p: Params, u: int, i: int) -> tuple[float, dict]:
    """The logit s and a cache for the backward pass. Cost O(k + sum of W_l sizes)."""
    g = [a * b for a, b in zip(p["PG"][u], p["QG"][i])]  # @line L8
    z = p["PM"][u] + p["QM"][i]  # @line L9
    zs, pre = [z], []
    for l in range(layers(p)):  # @line L10
        w, b = p[f"W{l}"], p[f"b{l}"][0]
        a = [sum(wr[c] * z[c] for c in range(len(z))) + b[r] for r, wr in enumerate(w)]
        z = [max(0.0, v) for v in a]
        pre.append(a)
        zs.append(z)
    phi = g + z
    s = sum(a * b for a, b in zip(p["h"][0], phi))  # @line L11
    return s, {"u": u, "i": i, "g": g, "zs": zs, "pre": pre, "phi": phi}


def score(p: Params, u: int, i: int) -> float:
    """y_hat = sigma(s)."""
    return sigmoid(forward(p, u, i)[0])


def loss(p: Params, examples: list[tuple[int, int, int]]) -> float:
    """The sum of the log losses of the examples. Cost O(len(examples)) forward passes."""
    total = 0.0
    for u, i, y in examples:
        s = forward(p, u, i)[0]
        total += softplus(-s) if y == 1 else softplus(s)
    return total


def backward(p: Params, cache: dict, ds: float, grads: dict) -> None:
    """Add the gradient of the loss to grads, given ds = dloss/ds. Cost of one forward pass."""
    k = len(p["PG"][0])
    u, i, phi = cache["u"], cache["i"], cache["phi"]
    h = p["h"][0]
    for c in range(len(h)):
        grads["h"][0][c] += ds * phi[c]
    dphi = [ds * v for v in h]
    dg, dz = dphi[:k], dphi[k:]
    for c in range(k):
        grads["PG"][u][c] += dg[c] * p["QG"][i][c]
        grads["QG"][i][c] += dg[c] * p["PG"][u][c]
    for l in range(layers(p) - 1, -1, -1):
        a, zin, w = cache["pre"][l], cache["zs"][l], p[f"W{l}"]
        da = [d if v > 0 else 0.0 for d, v in zip(dz, a)]
        gw, gb = grads[f"W{l}"], grads[f"b{l}"][0]
        for r in range(len(w)):
            gb[r] += da[r]
            for c in range(len(zin)):
                gw[r][c] += da[r] * zin[c]
        dz = [sum(w[r][c] * da[r] for r in range(len(w))) for c in range(len(zin))]
    for c in range(k):
        grads["PM"][u][c] += dz[c]
        grads["QM"][i][c] += dz[k + c]


def zeros_like(p: Params) -> Params:
    return {name: [[0.0] * len(row) for row in mat] for name, mat in p.items()}


def gradient(p: Params, examples: list[tuple[int, int, int]]) -> Params:
    """The gradient of loss(p, examples). d(log loss)/ds = sigma(s) - y."""
    grads = zeros_like(p)
    for u, i, y in examples:
        s, cache = forward(p, u, i)
        backward(p, cache, sigmoid(s) - y, grads)
    return grads


def train(
    pairs: set[tuple[int, int]],
    m: int,
    n: int,
    k: int,
    hidden: list[int],
    epochs: int,
    rate: float,
    negatives: int = 4,
    seed: int = 1,
) -> Params:
    """SGD on the log loss with negative sampling.

    Precondition: every user with a positive pair has an unused item.
    Cost O(epochs |S| (1 + negatives) c), with c the cost of one forward pass.
    """
    rng = random.Random(seed)
    p = init(m, n, k, hidden, seed)
    used: dict[int, set[int]] = {}
    for u, i in pairs:
        used.setdefault(u, set()).add(i)
    free = {u: [j for j in range(n) if j not in s] for u, s in used.items()}
    if any(not f for f in free.values()):
        raise ValueError("a user has used every item")
    for _ in range(epochs):  # @line L2
        data = [(u, i, 1) for u, i in sorted(pairs)]  # @line L3
        for u, _i in sorted(pairs):
            data.extend((u, rng.choice(free[u]), 0) for _ in range(negatives))
        rng.shuffle(data)
        for u, i, y in data:  # @line L4
            s, cache = forward(p, u, i)  # @line L5
            g = zeros_like_used(p, u, i)
            backward(p, cache, sigmoid(s) - y, g)
            step(p, g, u, i, rate)  # @line L6
    return p  # @line L7


def zeros_like_used(p: Params, u: int, i: int) -> dict:
    """A gradient buffer for one example.

    The dense weights get full zero matrices. The embedding tables get only
    the row of u or of i, as a dict {row: zeros}, so the cost does not grow
    with m and n.
    """
    out: dict = {name: [[0.0] * len(row) for row in mat] for name, mat in p.items() if name not in EMB}
    for name, row in (("PG", u), ("PM", u), ("QG", i), ("QM", i)):
        out[name] = {row: [0.0] * len(p[name][0])}
    return out


EMB = ("PG", "QG", "PM", "QM")


def step(p: Params, g: dict, u: int, i: int, rate: float) -> None:
    """p -= rate * g on the dense weights and on the rows of u and i."""
    for name, mat in p.items():
        if name in ("PG", "PM"):
            rows = [u]
        elif name in ("QG", "QM"):
            rows = [i]
        else:
            rows = list(range(len(mat)))
        for r in rows:
            gr = g[name][r]
            pr = mat[r]
            for c in range(len(pr)):
                pr[c] -= rate * gr[c]


def recommend(p: Params, u: int, used: set[int], n: int, top: int) -> list[int]:
    """The top items by score among the unused ones. Cost O(n) forward passes."""
    scored = sorted((-forward(p, u, i)[0], i) for i in range(n) if i not in used)
    return [i for _, i in scored[:top]]
test_neural_collaborative_filtering.py 117 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/neural-collaborative-filtering/. The authors are listed in prov/9XDZVT.jsonl.

import math
import random

import pytest

import neural_collaborative_filtering as ncf

FD_STEP = 1e-6
FD_TOL = 1e-6
AUC_MIN = 0.75


def planted(seed: int) -> tuple[set, set, int, int]:
    """Two groups of 15 users; group 0 uses items 0 to 9 and group 1 items 10 to 19."""
    rng = random.Random(seed)
    m, n = 30, 20
    train, test = set(), set()
    for u in range(m):
        base = 0 if u < 15 else 10
        items = rng.sample(range(base, base + 10), 6)
        test.add((u, items[0]))
        train.update((u, i) for i in items[1:])
    return train, test, m, n


def held_out_auc(p, train, test, m, n) -> float:
    total = 0.0
    for u, t in sorted(test):
        others = [j for j in range(n) if (u, j) not in train and j != t]
        st = ncf.forward(p, u, t)[0]
        total += sum(1.0 if st > ncf.forward(p, u, j)[0] else 0.0 for j in others) / len(others)
    return total / len(test)


def test_every_gradient_matches_finite_differences():
    for seed, hidden in ((1, [5, 3]), (2, [4]), (3, [])):
        p = ncf.init(3, 4, 3, hidden, seed=seed, scale=0.7)
        examples = [(0, 1, 1), (2, 3, 0), (1, 1, 0), (0, 2, 1)]
        grads = ncf.gradient(p, examples)
        for name, mat in p.items():
            for r in range(len(mat)):
                for c in range(len(mat[r])):
                    old = mat[r][c]
                    mat[r][c] = old + FD_STEP
                    up = ncf.loss(p, examples)
                    mat[r][c] = old - FD_STEP
                    down = ncf.loss(p, examples)
                    mat[r][c] = old
                    fd = (up - down) / (2 * FD_STEP)
                    assert abs(fd - grads[name][r][c]) <= FD_TOL * max(1.0, abs(fd)), (name, r, c)


def test_sparse_step_equals_dense_step():
    p = ncf.init(4, 5, 2, [3], seed=4, scale=0.5)
    q = {name: [row[:] for row in mat] for name, mat in p.items()}
    s, cache = ncf.forward(p, 2, 3)
    dense = ncf.zeros_like(p)
    ncf.backward(p, cache, ncf.sigmoid(s) - 1, dense)
    sparse = ncf.zeros_like_used(q, 2, 3)
    ncf.backward(q, cache, ncf.sigmoid(s) - 1, sparse)
    for name, mat in p.items():
        for r in range(len(mat)):
            for c in range(len(mat[r])):
                mat[r][c] -= 0.1 * dense[name][r][c]
    ncf.step(q, sparse, 2, 3, 0.1)
    for name in p:
        for a, b in zip(p[name], q[name]):
            for x, y in zip(a, b):
                assert abs(x - y) <= 1e-15


def test_gmf_with_unit_weights_is_the_dot_product():
    p = ncf.init(3, 3, 4, [2], seed=5)
    p["h"] = [[1.0, 1.0, 1.0, 1.0, 0.0, 0.0]]
    for u in range(3):
        for i in range(3):
            dot = sum(a * b for a, b in zip(p["PG"][u], p["QG"][i]))
            assert abs(ncf.forward(p, u, i)[0] - dot) <= 1e-12


def test_page_example():
    p = {
        "PG": [[1.0, 2.0]],
        "QG": [[0.5, -1.0]],
        "PM": [[1.0, 0.0]],
        "QM": [[0.0, 1.0]],
        "W0": [[1.0, -1.0, 1.0, 0.0], [0.0, 1.0, 1.0, 1.0]],
        "b0": [[0.0, -0.5]],
        "h": [[1.0, 0.5, 2.0, -1.0]],
    }
    s, cache = ncf.forward(p, 0, 0)
    assert cache["g"] == [0.5, -2.0]
    assert cache["pre"][0] == [1.0, 0.5]
    assert abs(s - 1.0) <= 1e-12
    assert abs(ncf.score(p, 0, 0) - 1 / (1 + math.exp(-1.0))) <= 1e-12
    grads = ncf.gradient(p, [(0, 0, 1)])
    d = 1 / (1 + math.exp(-1.0)) - 1
    assert abs(grads["h"][0][2] - d * 1.0) <= 1e-12
    assert abs(grads["W0"][1][3] - d * (-1.0) * 1.0) <= 1e-12


def test_training_learns_the_planted_groups():
    train, test, m, n = planted(5)
    before = ncf.init(m, n, 4, [4], seed=3)
    p = ncf.train(train, m, n, 4, [4], 15, 0.1, negatives=4, seed=3)
    assert held_out_auc(before, train, test, m, n) < 0.7
    assert held_out_auc(p, train, test, m, n) > AUC_MIN
    pairs = [(u, i, 1) for u, i in sorted(train)]
    assert ncf.loss(p, pairs) < ncf.loss(before, pairs)


def test_user_with_all_items_is_rejected():
    with pytest.raises(ValueError):
        ncf.train({(0, 0), (0, 1)}, 1, 2, 2, [2], 1, 0.1)

History

He et al. presented NCF at WWW 2017, and it became a common baseline for neural recommenders. In 2019, Ferrari Dacrema, Cremonesi, Jannach and coauthors studied the reproducibility of neural recommendation papers, including NCF, and compared them with simple, well-tuned baselines. Rendle, Krichene, Zhang and Anderson revisited the NCF experiments at RecSys 2020 and found that a tuned dot product beat the learned similarity in their experiments, that an MLP has difficulty learning a dot product, and that MLP scores are costly to serve.

References

  1. Xiangnan He, Lizi Liao, Hanwang Zhang, Liqiang Nie, Xia Hu and Tat-Seng Chua, Neural collaborative filtering, Proceedings of the 26th International Conference on World Wide Web (WWW 2017), 173-182, Section 3.1 (the general framework and the log loss with negative sampling, Equation 7), Section 3.2 (GMF, Equations 8 and 9), Section 3.3 (MLP, Equation 10), Section 3.4 (NeuMF, Equation 12, and pre-training in 3.4.1), Section 4 (MovieLens and Pinterest, leave-one-out with HR@10 and NDCG@10)
  2. Steffen Rendle, Walid Krichene, Li Zhang and John Anderson, Neural collaborative filtering vs. matrix factorization revisited, Proceedings of the 14th ACM Conference on Recommender Systems (RecSys 2020), 240-248, Section 3 (the NCF experiments rerun with a tuned dot product, Figure 2), Section 3.4 (test-set selection of the NCF numbers), Section 4 (learning a dot product with an MLP is hard, Figure 3), Section 5 (the cost of serving MLP scores)
  3. Steffen Rendle, Walid Krichene, Li Zhang and John Anderson, Neural collaborative filtering vs. matrix factorization revisited, arXiv version, Sections 3.2 and 3.3 and Appendix A (the setup of the dot product baseline and the embedding sizes 16 to 192)

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