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.
- Solves
- Recommendation problem
- 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
- Model
- Word RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 of positive pairs of users and items, an embedding size , the widths of the hidden layers, and a number of negatives per positive. NeuMF (Section 3.4, Equation 12) computes
with separate embeddings for the GMF part and for the MLP part. The training set has label for each pair of , and label for items drawn uniformly from the items the user has not used. The loss is the log loss of Equation 7,
The output is a score for each user and item, and the recommendation is the unused items in order of score.
The algorithm
NCF-TRAIN(S, k, widths, q, E, η)- 1
draw all embeddings and weights from a Gaussian with a small spread - 2
repeat E times - 3
D ← {(u, i, 1) : (u, i) ∈ S} ∪ {(u, j, 0) : q random unused j for each (u, i) ∈ S} - 4
for each (u, i, y) in D, in random order do - 5
s ← SCORE(u, i) - 6
step every parameter used in L5 against the gradient of -y ln σ(s) - (1 - y) ln σ(-s) - 7
return the parameters SCORE(u, i)- 8
g ← p_u^G ⊙ q_i^G ▷ GMF part - 9
z ← [p_u^M ; q_i^M] ▷ MLP part - 10
for each hidden layer l do z ← ReLU(W_l z + b_l) - 11
return 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 , the top layer passes down, and each ReLU layer passes 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 on each part (Section 3.4.1). The code uses plain stochastic gradient steps and no pre-training.
Example
Take and one hidden layer of width 2. Let , , , ,
- Line L8: .
- Line L9: .
- Line L10: , and both units are active, so .
- Line L11: , so .
For a positive example, . The gradient for the third entry of is that times , and the gradient for in row 2, column 4 is that times times , about . A step against these gradients raises . The test file checks these values.
With the MLP part is switched off and the score is , 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 , , 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 with , the forward pass computes
and the loss is . The claims are about exact arithmetic and about points where no entry of any is 0; at such a point every function in the chain is differentiable. At an entry the code uses the derivative 0 for ReLU, which is one element of its subdifferential.
Lemma 1 (the output). .
Proof. , so . The derivative of is and that of is . So .
Write .
Lemma 2 (the top layer and the GMF part). and . With split like , , and
Proof. is bilinear, so its partial derivatives are and ; multiply by (chain rule). Entry of is , which depends only on entry of each vector, with partial derivatives and .
Lemma 3 (one ReLU layer). Let be known. Then, with the diagonal matrix with entries where and where ,
Proof. acts entry by entry with derivative 1 or 0 away from 0, which gives the first formula. Entry of is , so , , and ; no other entry of depends on or . The chain rule gives the three formulas.
Theorem 4 (the backward pass is the gradient). The function backward adds to its buffers exactly for every parameter : the entries of , , , of the rows , and zero for every other row of the embedding tables.
Proof. backward receives (Lemma 1) and computes the derivatives of Lemma 2. It sets and applies Lemma 3 for , which is induction on the layers from the top: each step uses , correct by the previous step, and produces . At the end , and since is a concatenation, its first half is and its second half is . The other rows of the tables do not appear in the forward pass of , so their derivative is 0. For a set of examples the loss is a sum, and gradient adds the per-example gradients.
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 and , then , the score of matrix factorization. If only , then , the GMF model of He et al.
Proof. , and with the second term vanishes; with the first term is .
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.
Complexity
- One example. The forward and backward passes cost , where is the number of weights in the hidden layers.
- One epoch. examples, so . The paper uses .
- Training. for epochs.
- Space. for the four embedding tables and for the weights; a step touches only the four rows of and .
- Serving. Ranking all items for one user costs forward passes, . 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 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, ; with 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 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 ( from 16 to 192), and beat NeuMF except at one point, HR on MovieLens with , 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 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.
# 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
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 9XDZVT Edit this page History Report an error Markdown