Algorithm Search⌘K

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.

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
Properties
randomizednot exactonlineiterative
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 uu, an item ii that uu used and an item jj that uu did not use, it asks that the score of ii be above the score of jj, and it maximizes the sum of ln⁡σ(xui−xuj)\ln \sigma(x_{ui} - x_{uj}) 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, xui=wu⊤hix_{ui} = w_u^\top h_i.

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 SS of positive pairs of mm users and nn items, Iu+={i:(u,i)∈S}I_u^+ = \{i : (u, i) \in S\}, a number of factors rr, a step size α\alpha and penalties λW,λH+,λH−≥0\lambda_W, \lambda_{H^+}, \lambda_{H^-} \ge 0. The training triples are

DS={(u,i,j):i∈Iu+,  j∈I∖Iu+}.D_S = \{(u, i, j) : i \in I_u^+, \; j \in I \setminus I_u^+\}.

Each triple says that uu prefers ii to jj; the pairs with both items used, or both unused, are not compared. With xuij=xui−xujx_{uij} = x_{ui} - x_{uj}, BPR-Opt (Section 4.1) is the sum of ln⁡σ(xuij)\ln \sigma(x_{uij}) over DSD_S minus a penalty. The paper writes the penalty once, as λΘ∥Θ∥2\lambda_\Theta \lVert \Theta \rVert^2 with Θ\Theta all parameters, which makes BPR-Opt the log posterior of the parameters when each triple is an independent event with probability σ(xuij)\sigma(x_{uij}) and the prior on Θ\Theta 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:

BPR-Opt=∑(u,i,j)∈DS[ln⁡σ(xuij)−12(λW∥wu∥2+λH+∥hi∥2+λH−∥hj∥2)],\text{BPR-Opt} = \sum_{(u, i, j) \in D_S} \Bigl[ \ln \sigma(x_{uij}) - \tfrac12 \bigl(\lambda_W \lVert w_u \rVert^2 + \lambda_{H^+} \lVert h_i \rVert^2 + \lambda_{H^-} \lVert h_j \rVert^2\bigr) \Bigr],

where σ(z)=1/(1+e−z)\sigma(z) = 1 / (1 + e^{-z}). The output is a score for every user and item; the recommendation for uu is the unused items in order of score.

The algorithm

  1. LEARN-BPR(S, r, α, λ_W, λ_H+, λ_H-, T)
  2. 1w_u, h_i ← small random vectors in R^r for all users and items
  3. 2repeat T times
  4. 3draw (u, i) uniformly from S
  5. 4draw j uniformly from all items; if j ∈ I_u^+ then go back to L3
  6. 5e ← σ(-x_uij), with x_uij = w_uᵀ(h_i - h_j)
  7. 6w_u ← w_u + α (e (h_i - h_j) - λ_W w_u)
  8. h_i ← h_i + α (e w_u - λ_H+ h_i)
  9. h_j ← h_j + α (-e w_u - λ_H- h_j) ▷ all three use the old values
  10. 7return W, H

Lines L3 and L4 draw a triple uniformly from DSD_S by rejection. Line L5 uses ddzln⁡σ(z)=σ(−z)\frac{d}{dz} \ln \sigma(z) = \sigma(-z). Line L6 is the gradient step of Section 4.3.1 of the paper, where ∂xuij/∂wu=hi−hj\partial x_{uij} / \partial w_u = h_i - h_j, ∂xuij/∂hi=wu\partial x_{uij} / \partial h_i = w_u and ∂xuij/∂hj=−wu\partial x_{uij} / \partial h_j = -w_u. Each step changes only three vectors.

Example

Take r=2r = 2, wu=(0.1,0.2)w_u = (0.1, 0.2), a used item hi=(0.3,−0.1)h_i = (0.3, -0.1), an unused item hj=(0.2,0.4)h_j = (0.2, 0.4), step size α=0.5\alpha = 0.5 and no penalty.

  • Scores: xui=0.03−0.02=0.01x_{ui} = 0.03 - 0.02 = 0.01 and xuj=0.02+0.08=0.10x_{uj} = 0.02 + 0.08 = 0.10, so xuij=−0.09x_{uij} = -0.09. The model has the pair in the wrong order.
  • Line L5: e=σ(0.09)≈0.52248e = \sigma(0.09) \approx 0.52248. The loss of the triple is −ln⁡σ(−0.09)≈0.73916-\ln \sigma(-0.09) \approx 0.73916.
  • Line L6: hi−hj=(0.1,−0.5)h_i - h_j = (0.1, -0.5), so wuw_u moves by 0.5⋅0.52248⋅(0.1,−0.5)0.5 \cdot 0.52248 \cdot (0.1, -0.5) to (0.12612,0.06938)(0.12612, 0.06938); hih_i moves by 0.5⋅0.52248⋅wu0.5 \cdot 0.52248 \cdot w_u to (0.32612,−0.04775)(0.32612, -0.04775); and hjh_j moves by the opposite amount to (0.17388,0.34775)(0.17388, 0.34775).
  • After the step, xuij≈−0.00824x_{uij} \approx -0.00824 and the loss is about 0.697270.69727. 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 r=4r = 4 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 −ln⁡σ(xuij)-\ln \sigma(x_{uij}) plus the penalty of the three vectors. The rejection draw of lines L3 and L4 is uniform on DSD_S, so the expected step is the gradient of the mean loss over DSD_S; a draw of jj from the unused items of uu would weight the users differently. And for every user, the training AUC is at least 1+1ln⁡21 + \frac{1}{\ln 2} times the mean of ln⁡σ(xuij)\ln \sigma(x_{uij}) over its triples, because δ(x>0)≥1+log⁡2σ(x)\delta(x > 0) \ge 1 + \log_2 \sigma(x) for every real xx. 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 WW and HH, 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. SS is the set of positive pairs, Iu+={i:(u,i)∈S}I_u^+ = \{i : (u, i) \in S\}, and DS={(u,i,j):i∈Iu+,j∉Iu+}D_S = \{(u, i, j) : i \in I_u^+, j \notin I_u^+\}. The model is xui=wu⊤hix_{ui} = w_u^\top h_i and xuij=xui−xujx_{uij} = x_{ui} - x_{uj}. The loss of one triple is

ℓ(u,i,j)=−ln⁡σ(xuij)+12(λW∥wu∥2+λH+∥hi∥2+λH−∥hj∥2),\ell(u, i, j) = -\ln \sigma(x_{uij}) + \tfrac12 \bigl(\lambda_W \lVert w_u \rVert^2 + \lambda_{H^+} \lVert h_i \rVert^2 + \lambda_{H^-} \lVert h_j \rVert^2\bigr),

and the code minimizes L=1∣DS∣∑(u,i,j)∈DSℓ(u,i,j)L = \frac{1}{|D_S|} \sum_{(u,i,j) \in D_S} \ell(u, i, j), the mean over DSD_S. The sum of ln⁡σ(xuij)\ln \sigma(x_{uij}) over DSD_S minus the penalty of each triple, which is the version of BPR-Opt that the updates of LearnBPR follow, equals −∣DS∣L-|D_S| L, so maximizing it and minimizing LL are the same problem. What can be proved is that each step of the algorithm is a correct stochastic gradient step for LL, and what LL says about the AUC. Whether the learned ranking is good on real data is measured, not proved.

Lemma 1 (the gradient). Let e=σ(−xuij)e = \sigma(-x_{uij}) and i≠ji \ne j. Then

∂ℓ∂wu=−e (hi−hj)+λWwu,∂ℓ∂hi=−e wu+λH+hi,∂ℓ∂hj=e wu+λH−hj,\frac{\partial \ell}{\partial w_u} = -e\,(h_i - h_j) + \lambda_W w_u, \qquad \frac{\partial \ell}{\partial h_i} = -e\, w_u + \lambda_{H^+} h_i, \qquad \frac{\partial \ell}{\partial h_j} = e\, w_u + \lambda_{H^-} h_j,

and ℓ\ell does not depend on any other parameter.

Proof. ddzln⁡σ(z)=σ′(z)σ(z)=σ(z)(1−σ(z))σ(z)=1−σ(z)=σ(−z)\frac{d}{dz} \ln \sigma(z) = \frac{\sigma'(z)}{\sigma(z)} = \frac{\sigma(z)(1 - \sigma(z))}{\sigma(z)} = 1 - \sigma(z) = \sigma(-z). By the chain rule, ∂(−ln⁡σ(xuij))/∂θ=−σ(−xuij) ∂xuij/∂θ\partial(-\ln \sigma(x_{uij}))/\partial \theta = -\sigma(-x_{uij})\, \partial x_{uij} / \partial \theta. Since xuij=wu⊤hi−wu⊤hjx_{uij} = w_u^\top h_i - w_u^\top h_j, the partial derivatives of xuijx_{uij} are hi−hjh_i - h_j for wuw_u, wuw_u for hih_i and −wu-w_u for hjh_j, as in Section 4.3.1 of Rendle et al. The penalty 12λ∥v∥2\frac12 \lambda \lVert v \rVert^2 has gradient λv\lambda v. Only wuw_u, hih_i and hjh_j appear in ℓ(u,i,j)\ell(u, i, j). □\square

The update printed in Figure 4 of the paper reads Θ←Θ+α(e−x1+e−x∂x∂Θ+λΘ)\Theta \leftarrow \Theta + \alpha \bigl(\frac{e^{-x}}{1 + e^{-x}} \frac{\partial x}{\partial \Theta} + \lambda \Theta\bigr). Lemma 1 shows that an ascent step on ln⁡σ(x)−12λ∥Θ∥2\ln \sigma(x) - \frac12 \lambda \lVert \Theta \rVert^2 has −λΘ-\lambda \Theta in that place, and e−x1+e−x=σ(−x)=e\frac{e^{-x}}{1 + e^{-x}} = \sigma(-x) = e. Line L6 of the page uses the sign of Lemma 1.

Lemma 2 (the sampler is uniform on DSD_S). Lines L3 and L4 draw (u,i)(u, i) uniformly from SS and jj uniformly from the nn items, and draw again until j∉Iu+j \notin I_u^+. The accepted triple is uniform on DSD_S.

Proof. One attempt produces a fixed triple (u,i,j)∈DS(u, i, j) \in D_S with probability 1∣S∣⋅1n\frac{1}{|S|} \cdot \frac{1}{n}, the same for every triple of DSD_S, and produces a triple outside DSD_S otherwise. The attempts are independent, so the first accepted triple is distributed as one attempt conditioned on acceptance, which gives each triple of DSD_S the probability 1/(∣S∣n)∣DS∣/(∣S∣n)=1∣DS∣\frac{1 / (|S| n)}{|D_S| / (|S| n)} = \frac{1}{|D_S|}. □\square

Drawing jj uniformly from the unused items of the drawn user instead would give the triple the probability 1∣S∣(n−∣Iu+∣)\frac{1}{|S| (n - |I_u^+|)}, which favors users with many positive items; the expectation in Theorem 3 would then be a weighted mean, not LL.

Theorem 3 (unbiased step). Let gg be the vector that lines L5 and L6 subtract from the parameters, divided by the step size, with zeros for all parameters other than wuw_u, hih_i and hjh_j. Then E[g]=∇L\mathbb{E}[g] = \nabla L, where the expectation is over the triple drawn in this step, with the parameters fixed.

Proof. By Lemma 1, g=∇ℓ(u,i,j)g = \nabla \ell(u, i, j) as a vector over all parameters. By Lemma 2 the triple is uniform on DSD_S, so E[g]=1∣DS∣∑DS∇ℓ(u,i,j)=∇L\mathbb{E}[g] = \frac{1}{|D_S|} \sum_{D_S} \nabla \ell(u, i, j) = \nabla L, by the linearity of the gradient. □\square

Proposition 4 (the criterion bounds the AUC). For a user uu with Iu+I_u^+ and its complement both nonempty, let DuD_u be the triples of DSD_S with first entry uu and

AUC(u)=1∣Du∣∑(u,i,j)∈Duδ(xuij>0).\mathrm{AUC}(u) = \frac{1}{|D_u|} \sum_{(u,i,j) \in D_u} \delta(x_{uij} > 0).

Then AUC(u)≥1+1ln⁡2⋅1∣Du∣∑(u,i,j)∈Duln⁡σ(xuij)\mathrm{AUC}(u) \ge 1 + \frac{1}{\ln 2} \cdot \frac{1}{|D_u|} \sum_{(u, i, j) \in D_u} \ln \sigma(x_{uij}).

Proof. It is enough to show δ(x>0)≥1+log⁡2σ(x)\delta(x > 0) \ge 1 + \log_2 \sigma(x) for every real xx and to average. If x>0x > 0, the left side is 1 and log⁡2σ(x)<0\log_2 \sigma(x) < 0, so the right side is below 1. If x≤0x \le 0, the left side is 0, and σ(x)≤12\sigma(x) \le \frac12 gives log⁡2σ(x)≤−1\log_2 \sigma(x) \le -1, so the right side is at most 0. □\square

So a larger mean of ln⁡σ(xuij)\ln \sigma(x_{uij}) 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 ln⁡σ\ln \sigma in place of the step function δ(x>0)\delta(x > 0). The bound is about the triples used in training; the AUC on held-out pairs is a measurement.

Cost. Lines L3 and L4 take O(1)O(1) expected attempts when the users use at most a constant fraction of the items, since an attempt succeeds with probability ∣DS∣/(∣S∣n)|D_S| / (|S| n), the mean fraction of unused items weighted by the number of positives. Lemma 1 costs O(r)O(r), and so does line L6, so one step costs O(r)O(r) expected time.

What is not claimed. LL is not convex in (W,H)(W, H), since xuijx_{uij} 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. ■\blacksquare

Complexity

  • One step. Lines L5 and L6 cost O(r)O(r). Lines L3 and L4 need ∣S∣ n/∣DS∣|S| \, n / |D_S| tries on average, which is O(1)O(1) when each user uses at most a constant fraction of the items.
  • Total. O((m+n)r)O((m + n) r) to start and O(Tr)O(T r) expected for TT steps. The paper chooses the number of steps linear in ∣S∣|S|.
  • Space. O((m+n)r)O((m + n) r) for the factors and O(∣S∣)O(|S|) for the data.
  • Evaluation. The AUC of one user costs O(nlog⁡n)O(n \log n) by sorting the scores, or O(n2)O(n^2) by direct comparison of pairs.

There are O(∣S∣ n)O(|S| \, n) triples, so a full gradient over DSD_S 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 xuix_{ui} 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 bib_i to xuix_{ui}. User biases cancel in xuijx_{uij}, 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 jj by popularity, or picking a jj 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 −ln⁡σ(x)-\ln \sigma(x) by max⁡(0,1−x)\max(0, 1 - x) 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 Θ←Θ+α(e−x1+e−x∂x∂Θ+λΘΘ)\Theta \leftarrow \Theta + \alpha (\frac{e^{-x}}{1 + e^{-x}} \frac{\partial x}{\partial \Theta} + \lambda_\Theta \Theta). For a gradient ascent on BPR-Opt the penalty term must be −λΘΘ-\lambda_\Theta \Theta, as in line L6. With the plus sign the vectors grow.
  • Sampling user by user. Going through all jj for one (u,i)(u, i) 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 ln⁡(1+e−x)\ln(1 + e^{-x}) directly overflows for large negative xx. 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.

bayesian_personalized_ranking.pyI0RawGitHub
# 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

  1. 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)
  2. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.expected
  • 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
  • at least three sources
  • a scene preset for the example