Algorithmadvanced
Bayesian personalized ranking
Also called BPR.
Learns from implicit feedback by maximizing the log-sigmoid of the score margin between an observed item and a sampled unobserved one.
- Solves
- Recommendation problem
- Time
- O(T r + (m + n) r) expected
- Space
- O((m + n) r) extra
- Where
- T = the number of sampled triples; m = the number of users; n = the number of items; r = the number of factors
- Model
- Word RAM
- Properties
- randomizednot exactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Steffen Rendle, Christoph Freudenthaler, Zeno Gantner, Lars Schmidt Thieme, 2009
Bayesian personalized ranking (BPR) trains a recommender on implicit feedback by comparing pairs of items. For a user , an item that used and an item that did not use, it asks that the score of be above the score of , and it maximizes the sum of over such triples, minus a penalty. Rendle, Freudenthaler, Gantner and Schmidt-Thieme (2009) derived this criterion, BPR-Opt, as a maximum posterior estimate, and they fit it with LearnBPR, stochastic gradient steps on triples drawn at random with replacement. The criterion works with any differentiable scoring model; this page uses matrix factorization, .
In plain words
When a user clicked one item and ignored another, we do not know that the user dislikes the ignored item. We only guess that the user likes the clicked one more. BPR learns from exactly this kind of guess: it takes one clicked item and one ignored item, and if the model scores them in the wrong order, or in the right order by only a small margin, it moves the scores apart.
Picking the pairs at random, and not user by user, keeps the same pair from being pushed again and again in a row. The result is a model tuned for the order of the items, which is what a top-10 list needs.
The problem
The input is a set of positive pairs of users and items, , a number of factors , a step size and penalties . The training triples are
Each triple says that prefers to ; the pairs with both items used, or both unused, are not compared. With , BPR-Opt (Section 4.1) is the sum of over minus a penalty. The paper writes the penalty once, as with all parameters, which makes BPR-Opt the log posterior of the parameters when each triple is an independent event with probability and the prior on is a zero mean Gaussian. The updates of LearnBPR penalize instead the three vectors of each triple, and this page and its proof use that form:
where . The output is a score for every user and item; the recommendation for is the unused items in order of score.
The algorithm
LEARN-BPR(S, r, α, λ_W, λ_H+, λ_H-, T)- 1
w_u, h_i ← small random vectors in R^r for all users and items - 2
repeat T times - 3
draw (u, i) uniformly from S - 4
draw j uniformly from all items; if j ∈ I_u^+ then go back to L3 - 5
e ← σ(-x_uij), with x_uij = w_uᵀ(h_i - h_j) - 6
w_u ← w_u + α (e (h_i - h_j) - λ_W w_u) h_i ← h_i + α (e w_u - λ_H+ h_i)h_j ← h_j + α (-e w_u - λ_H- h_j) ▷ all three use the old values- 7
return W, H
Lines L3 and L4 draw a triple uniformly from by rejection. Line L5 uses . Line L6 is the gradient step of Section 4.3.1 of the paper, where , and . Each step changes only three vectors.
Example
Take , , a used item , an unused item , step size and no penalty.
- Scores: and , so . The model has the pair in the wrong order.
- Line L5: . The loss of the triple is .
- Line L6: , so moves by to ; moves by to ; and moves by the opposite amount to .
- After the step, and the loss is about . The pair is still in the wrong order, but by a much smaller margin.
On a planted data set of 30 users in two groups, where each group uses only its own 10 of the 20 items, the test file trains with and 40,000 steps. The AUC on one held-out item per user goes from 0.49 for the random start to about 0.84; the best possible is about 0.86, since the model cannot know which unused items of its own group the user will pick.
Correctness
The proof in proofs/correctness.md shows three facts. Line L6 is a step against the exact gradient of the loss plus the penalty of the three vectors. The rejection draw of lines L3 and L4 is uniform on , so the expected step is the gradient of the mean loss over ; a draw of from the unused items of would weight the users differently. And for every user, the training AUC is at least times the mean of over its triples, because for every real . This is the precise sense in which BPR-Opt is a smooth version of the AUC (Section 4.1.1).
The criterion is not convex in and , and the page does not claim that LearnBPR converges or finds the best factors. That BPR gives better rankings than other methods is a measured result, not a proved one.
Proof: The BPR step follows an unbiased estimate of the gradient of the mean triple loss, and the criterion bounds the AUC from belowfull
The notation is that of the page. is the set of positive pairs, , and . The model is and . The loss of one triple is
and the code minimizes , the mean over . The sum of over minus the penalty of each triple, which is the version of BPR-Opt that the updates of LearnBPR follow, equals , so maximizing it and minimizing are the same problem. What can be proved is that each step of the algorithm is a correct stochastic gradient step for , and what says about the AUC. Whether the learned ranking is good on real data is measured, not proved.
Lemma 1 (the gradient). Let and . Then
and does not depend on any other parameter.
Proof. . By the chain rule, . Since , the partial derivatives of are for , for and for , as in Section 4.3.1 of Rendle et al. The penalty has gradient . Only , and appear in .
The update printed in Figure 4 of the paper reads . Lemma 1 shows that an ascent step on has in that place, and . Line L6 of the page uses the sign of Lemma 1.
Lemma 2 (the sampler is uniform on ). Lines L3 and L4 draw uniformly from and uniformly from the items, and draw again until . The accepted triple is uniform on .
Proof. One attempt produces a fixed triple with probability , the same for every triple of , and produces a triple outside otherwise. The attempts are independent, so the first accepted triple is distributed as one attempt conditioned on acceptance, which gives each triple of the probability .
Drawing uniformly from the unused items of the drawn user instead would give the triple the probability , which favors users with many positive items; the expectation in Theorem 3 would then be a weighted mean, not .
Theorem 3 (unbiased step). Let be the vector that lines L5 and L6 subtract from the parameters, divided by the step size, with zeros for all parameters other than , and . Then , where the expectation is over the triple drawn in this step, with the parameters fixed.
Proof. By Lemma 1, as a vector over all parameters. By Lemma 2 the triple is uniform on , so , by the linearity of the gradient.
Proposition 4 (the criterion bounds the AUC). For a user with and its complement both nonempty, let be the triples of with first entry and
Then .
Proof. It is enough to show for every real and to average. If , the left side is 1 and , so the right side is below 1. If , the left side is 0, and gives , so the right side is at most 0.
So a larger mean of forces a larger lower bound on the training AUC. This makes precise the remark of Section 4.1.1 of the paper that BPR-Opt is a smooth version of the AUC, with in place of the step function . The bound is about the triples used in training; the AUC on held-out pairs is a measurement.
Cost. Lines L3 and L4 take expected attempts when the users use at most a constant fraction of the items, since an attempt succeeds with probability , the mean fraction of unused items weighted by the number of positives. Lemma 1 costs , and so does line L6, so one step costs expected time.
What is not claimed. is not convex in , since is a product of parameters. Theorem 3 is the property that the standard analysis of stochastic gradient descent assumes, but this page does not prove that LearnBPR converges, or that it reaches a global minimum.
Complexity
- One step. Lines L5 and L6 cost . Lines L3 and L4 need tries on average, which is when each user uses at most a constant fraction of the items.
- Total. to start and expected for steps. The paper chooses the number of steps linear in .
- Space. for the factors and for the data.
- Evaluation. The AUC of one user costs by sorting the scores, or by direct comparison of pairs.
There are triples, so a full gradient over is too costly on real data. This is the reason for sampling.
Properties
- Pairwise. The loss depends only on differences of scores, so adding a constant to all scores of a user changes nothing.
- Online. Each step uses one triple, and steps can run as new data arrives.
- Model-agnostic. Any differentiable score can be used; the paper also applies it to an adaptive item-kNN model (Section 4.3.2).
- Stochastic. The result depends on the random start and the random triples.
Variants and improvements
- Item biases. Add a bias to . User biases cancel in , so they are useless here.
- Weighted least squares. Implicit ALS fits the same factor model to all cells with a pointwise weighted loss. Section 5.1 of the paper calls it WR-MF and argues that its pointwise loss is not tuned to the ranking.
- Other models. Factorization machines are often trained with the BPR loss when there are side features. GRU4Rec uses a BPR loss on the scores of a recurrent network, with the other items of the mini-batch as the unused items.
- Other samplers. Drawing by popularity, or picking a with a high score, gives more informative triples than uniform draws, at the cost of changing the objective that the steps follow in expectation.
- Hinge loss. Replacing by gives a pairwise hinge loss, as in ranking SVMs.
When to use it
Use BPR when the data is clicks, plays or purchases, when the goal is a ranked list, and when the data is too large for a full gradient. On a Rossmann purchase set (10,000 users, 4,000 items) and a Netflix subset turned into implicit data (10,000 users, 5,000 items), the paper measured AUC with one held-out item per user and found that the BPR versions of matrix factorization and kNN ranked better than WR-MF, SVD-MF, cosine kNN and the most popular items for all tested numbers of factors (Figure 6). These are measurements on two data sets with the settings and the tuning of the paper, not properties of the method.
Pitfalls
- The sign of the penalty. Figure 4 of the paper prints the update as . For a gradient ascent on BPR-Opt the penalty term must be , as in line L6. With the plus sign the vectors grow.
- Sampling user by user. Going through all for one before moving on makes many steps in a row on the same vectors; the paper reports much slower convergence for user-wise traversal (Figure 5).
- Overflow. Computing directly overflows for large negative . Use a stable form, as the code does.
- Reading the AUC. A good AUC can come with a poor top of the list, since the AUC weighs all positions the same. Report a top-heavy measure such as precision at k or NDCG as well.
- Unused is not disliked. At test time, a held-out used item is compared with items that the user may like but has not seen. The measured AUC is a lower estimate of the true one.
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/bayesian-personalized-ranking/. The authors are listed in prov/JYHKHX.jsonl.
"""Bayesian personalized ranking with a matrix factorization model (BPR-MF).
Rendle, Freudenthaler, Gantner and Schmidt-Thieme (UAI 2009). The data is a
set of positive (user, item) pairs. A training triple (u, i, j) has i a
positive item of u and j an item that u has not used. The model scores
x_ui = w_u . h_i and x_uij = x_ui - x_uj. BPR-Opt is
sum over triples of ln sigma(x_uij) - (regularization),
and LearnBPR does stochastic gradient ascent on it with triples drawn
uniformly with replacement. This module minimizes the negative of the
per-triple term,
loss(u, i, j) = -ln sigma(x_uij)
+ (lam_u |w_u|^2 + lam_i |h_i|^2 + lam_j |h_j|^2) / 2,
so a step moves against the gradient. The factor 1/2 on the penalty only
rescales the constants.
"""
import math
import random
Matrix = list[list[float]]
def sigmoid(z: float) -> float:
"""The logistic function, computed without overflow."""
if z >= 0:
return 1.0 / (1.0 + math.exp(-z))
e = math.exp(z)
return e / (1.0 + e)
def log_sigmoid(z: float) -> float:
"""ln sigma(z) = -ln(1 + e^(-z)), computed without overflow."""
if z >= 0:
return -math.log1p(math.exp(-z))
return z - math.log1p(math.exp(z))
def dot(a: list[float], b: list[float]) -> float:
return sum(x * y for x, y in zip(a, b))
def triple_loss(w: Matrix, h: Matrix, u: int, i: int, j: int, regs: tuple[float, float, float]) -> float:
"""loss(u, i, j) as in the module docstring. Cost O(r)."""
lu, li, lj = regs
x = dot(w[u], h[i]) - dot(w[u], h[j])
pen = lu * dot(w[u], w[u]) + li * dot(h[i], h[i]) + lj * dot(h[j], h[j])
return -log_sigmoid(x) + 0.5 * pen
def triple_grad(
w: Matrix, h: Matrix, u: int, i: int, j: int, regs: tuple[float, float, float]
) -> tuple[list[float], list[float], list[float]]:
"""Gradients of loss(u, i, j) with respect to w_u, h_i and h_j.
Precondition: i != j. With e = sigma(-x_uij), d(-ln sigma(x))/dx = -e,
and dx/dw_u = h_i - h_j, dx/dh_i = w_u, dx/dh_j = -w_u. Cost O(r).
"""
lu, li, lj = regs
wu, hi, hj = w[u], h[i], h[j]
x = dot(wu, hi) - dot(wu, hj)
e = sigmoid(-x)
gw = [-e * (a - b) + lu * c for a, b, c in zip(hi, hj, wu)]
gi = [-e * a + li * b for a, b in zip(wu, hi)]
gj = [e * a + lj * b for a, b in zip(wu, hj)]
return gw, gi, gj
def by_user(pairs: set[tuple[int, int]], m: int) -> list[set[int]]:
"""The set I_u^+ of positive items of each user."""
pos: list[set[int]] = [set() for _ in range(m)]
for u, i in pairs:
pos[u].add(i)
return pos
def learn_bpr(
pairs: set[tuple[int, int]],
m: int,
n: int,
r: int,
steps: int,
rate: float,
regs: tuple[float, float, float],
seed: int = 1,
) -> tuple[Matrix, Matrix]:
"""LearnBPR with bootstrap sampling of triples.
A draw takes a positive pair (u, i) uniformly and an item j uniformly,
and starts again when u has used j. The accepted triple is uniform on
D_S. Precondition: every user with a positive pair has at least one item
it has not used. Cost O(r) per step, so O(steps r) in total, plus
O((m + n) r) to start, if the expected number of draws per step is O(1),
which holds when the users use a small part of the catalog.
"""
rng = random.Random(seed)
w = [[rng.gauss(0.0, 0.1) for _ in range(r)] for _ in range(m)] # @line L1
h = [[rng.gauss(0.0, 0.1) for _ in range(r)] for _ in range(n)]
pos = by_user(pairs, m)
plist = sorted(pairs)
for u in range(m):
if pos[u] and len(pos[u]) == n:
raise ValueError("a user has used every item, so no triple exists")
for _ in range(steps): # @line L2
while True:
u, i = plist[rng.randrange(len(plist))] # @line L3
j = rng.randrange(n) # @line L4
if j not in pos[u]:
break
gw, gi, gj = triple_grad(w, h, u, i, j, regs) # @line L5
for f in range(r): # @line L6
w[u][f] -= rate * gw[f]
h[i][f] -= rate * gi[f]
h[j][f] -= rate * gj[f]
return w, h # @line L7
def auc(
w: Matrix, h: Matrix, train: set[tuple[int, int]], test: set[tuple[int, int]], m: int, n: int
) -> float:
"""The mean over users of the fraction of correctly ordered pairs (Rendle et al., Equation 2).
For user u, the pairs are (i, j) with i a test item of u and j an item in
neither the training nor the test set of u. Ties count one half.
Users with no test item are skipped. Cost O(m n^2 r) at most.
"""
tr, te = by_user(train, m), by_user(test, m)
total, users = 0.0, 0
for u in range(m):
if not te[u]:
continue
others = [j for j in range(n) if j not in tr[u] and j not in te[u]]
if not others:
continue
good = 0.0
for i in te[u]:
xi = dot(w[u], h[i])
for j in others:
xj = dot(w[u], h[j])
good += 1.0 if xi > xj else 0.5 if xi == xj else 0.0
total += good / (len(te[u]) * len(others))
users += 1
return total / users if users else 0.5
def rank(w: Matrix, h: Matrix, u: int, used: set[int], k: int) -> list[int]:
"""The k unused items with the highest score for user u. Cost O(n r + n log n)."""
scored = sorted((-dot(w[u], h[i]), i) for i in range(len(h)) if i not in used)
return [i for _, i in scored[:k]]
test_bayesian_personalized_ranking.py 117 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bayesian-personalized-ranking/. The authors are listed in prov/JYHKHX.jsonl.
import math
import random
import pytest
import bayesian_personalized_ranking as bpr
FD_STEP = 1e-6
FD_TOL = 1e-7
AUC_MIN = 0.8
def planted(seed: int) -> tuple[set, set, int, int]:
"""Two groups of 15 users. Group 0 uses items 0 to 9, group 1 items 10 to 19.
Each user has 6 items of its own group; one of them is held out for test.
The planted order: for every user, the items of its group come before
the items of the other group.
"""
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]))
for i in items[1:]:
train.add((u, i))
return train, test, m, n
def test_gradient_matches_finite_differences():
rng = random.Random(3)
for _ in range(10):
r = rng.randint(1, 4)
w = [[rng.gauss(0, 1) for _ in range(r)] for _ in range(3)]
h = [[rng.gauss(0, 1) for _ in range(r)] for _ in range(4)]
regs = (rng.uniform(0, 0.5), rng.uniform(0, 0.5), rng.uniform(0, 0.5))
u, i, j = 1, 0, 3
gw, gi, gj = bpr.triple_grad(w, h, u, i, j, regs)
for mat, row, g in ((w, u, gw), (h, i, gi), (h, j, gj)):
for f in range(r):
old = mat[row][f]
mat[row][f] = old + FD_STEP
up = bpr.triple_loss(w, h, u, i, j, regs)
mat[row][f] = old - FD_STEP
down = bpr.triple_loss(w, h, u, i, j, regs)
mat[row][f] = old
assert abs((up - down) / (2 * FD_STEP) - g[f]) <= FD_TOL
def test_page_example_step():
w = [[0.1, 0.2]]
h = [[0.3, -0.1], [0.2, 0.4]]
zero = (0.0, 0.0, 0.0)
assert abs(bpr.triple_loss(w, h, 0, 0, 1, zero) - 0.7391593390256102) <= 1e-12
gw, gi, gj = bpr.triple_grad(w, h, 0, 0, 1, zero)
w[0] = [a - 0.5 * g for a, g in zip(w[0], gw)]
h[0] = [a - 0.5 * g for a, g in zip(h[0], gi)]
h[1] = [a - 0.5 * g for a, g in zip(h[1], gj)]
x = bpr.dot(w[0], h[0]) - bpr.dot(w[0], h[1])
assert abs(x - (-0.008237299183673295)) <= 1e-12
assert abs(bpr.triple_loss(w, h, 0, 0, 1, zero) - 0.6972743117650329) <= 1e-12
def test_log_sigmoid_is_stable_and_correct():
for z in (-800.0, -30.0, -1.0, 0.0, 1.0, 30.0, 800.0):
got = bpr.log_sigmoid(z)
assert math.isfinite(got)
if abs(z) < 30:
assert abs(got - math.log(1 / (1 + math.exp(-z)))) <= 1e-12
assert abs(bpr.sigmoid(0.0) - 0.5) <= 1e-15
def test_learned_auc_on_planted_order():
train, test, m, n = planted(5)
w, h = bpr.learn_bpr(train, m, n, 4, 40000, 0.05, (0.01, 0.01, 0.01), seed=7)
assert bpr.auc(w, h, train, test, m, n) > AUC_MIN
def test_untrained_model_is_near_random():
train, test, m, n = planted(5)
w, h = bpr.learn_bpr(train, m, n, 4, 0, 0.05, (0.01, 0.01, 0.01), seed=7)
assert abs(bpr.auc(w, h, train, test, m, n) - 0.5) < 0.2
def test_auc_by_brute_force_count():
rng = random.Random(9)
m, n, r = 4, 6, 2
w = [[rng.gauss(0, 1) for _ in range(r)] for _ in range(m)]
h = [[rng.gauss(0, 1) for _ in range(r)] for _ in range(n)]
train = {(0, 0), (0, 1), (1, 2), (2, 3), (3, 4)}
test = {(0, 2), (1, 5), (2, 0), (3, 1)}
# Brute force: the position of the test item in the sorted list of candidates.
per_user = []
for u, t in sorted(test):
cands = [j for j in range(n) if (u, j) not in train and j != t]
score = sum(bpr.dot(w[u], h[t]) > bpr.dot(w[u], h[j]) for j in cands)
per_user.append(score / len(cands))
want = sum(per_user) / len(per_user)
assert abs(bpr.auc(w, h, train, test, m, n) - want) <= 1e-12
def test_ranking_leaves_out_used_items():
train, _, m, n = planted(1)
w, h = bpr.learn_bpr(train, m, n, 3, 2000, 0.05, (0.01, 0.01, 0.01))
used = bpr.by_user(train, m)[0]
top = bpr.rank(w, h, 0, used, 5)
assert len(top) == 5 and not set(top) & used
def test_user_with_all_items_is_rejected():
with pytest.raises(ValueError):
bpr.learn_bpr({(0, 0), (0, 1)}, 1, 2, 2, 10, 0.1, (0.0, 0.0, 0.0))
History
Rendle, Freudenthaler, Gantner and Schmidt-Thieme presented BPR at UAI 2009. The paper compared it with the weighted least squares methods of Hu, Koren and Volinsky and of Pan et al., both from ICDM 2008, and with maximum margin matrix factorization. The BPR loss became a standard loss for implicit data and was later used with factorization machines, with sequence models such as GRU4Rec, and with neural scoring models.
References
- Steffen Rendle, Christoph Freudenthaler, Zeno Gantner and Lars Schmidt-Thieme, BPR, Bayesian personalized ranking from implicit feedback, Proceedings of the 25th Conference on Uncertainty in Artificial Intelligence (UAI 2009), 452-461, Section 3 (the set D_S), Section 4.1 (BPR-Opt) and 4.1.1 (analogy to AUC, Equation 1), Section 4.2 and Figure 4 (LearnBPR), Section 4.3.1 (the gradients for matrix factorization), Section 5.1 (relation to WR-MF), Section 6 (AUC on Rossmann and Netflix data, Figure 6)
- Yifan Hu, Yehuda Koren and Chris Volinsky, Collaborative filtering for implicit feedback datasets, ICDM 2008, 263-272, Section 4 (the weighted least squares model that BPR is compared with)
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.
| 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 JYHKHX Edit this page History Report an error Markdown