Sign in

BPR

Bayesian Personalized Ranking

A pairwise ranking loss for implicit feedback: it pushes the score of an item a user interacted with above the score of one they did not.

Overview

Click and purchase logs tell you what a user chose, not what they disliked. Bayesian Personalized Ranking makes a modest assumption: an item the user interacted with should rank above an item they did not. Training runs on triples of a user, a positive item and a sampled negative item. The loss looks only at the difference between the two scores. If the positive item scores well above the negative, the loss is near zero. If the order is wrong, the loss grows roughly in proportion to the gap. Absolute score values do not matter, only the order.

A short history

Steffen Rendle, Christoph Freudenthaler, Zeno Gantner and Lars Schmidt-Thieme introduced BPR at the UAI conference in 2009. Recommender data is mostly implicit: clicks and purchases, with no explicit dislikes. Earlier methods treated every missing interaction as a negative rating. BPR instead optimises the order directly, asking only that an item the user chose scores above one they did not, and it became a standard baseline for implicit feedback.

How it works

  1. For each user in the batch, take the score of an item they interacted with, s+s^{+}, and the score of a sampled item they did not, s−s^{-}.
  2. Compute the difference d=s+−s−d = s^{+} - s^{-}.
  3. The loss for the triple is −ln⁡σ(d)-\ln\sigma(d), computed as ln⁡(1+e−d)\ln(1 + e^{-d}) so it cannot overflow.
  4. Reduce over the batch with reduction.
  5. In backward, the gradient for s+s^{+} is −σ(−d)-\sigma(-d) and the gradient for s−s^{-} is its negative, both divided by the batch size for the mean.

Watch out for

  • The negative is only an item the user has not interacted with. Some of those are items the user would like, so some training pairs are wrong.
  • Uniformly sampled negatives quickly become too easy. Their gradient σ(−d)\sigma(-d) shrinks toward zero and training stalls unless harder negatives are sampled.
  • The loss depends only on score differences, so the scores are not probabilities and cannot be compared across users.
  • The template is the loss alone. The original method also adds an L2 penalty on the embeddings and needs a negative sampler, both of which you supply.

Use cases

When to use it

Recommenders trained on implicit feedback such as clicks, plays or purchases, where the goal is a good ordering of items per user and there are no explicit ratings.

In industry

E-commerce
Shops train matrix factorisation models with BPR on purchase and view logs to rank products for each customer.
Media streaming
Music and video services with play histories and no ratings use pairwise ranking losses like BPR to order a catalogue per listener.
Marketplaces and listings
Job and property sites learn from which listings a user opened, ranking those above listings the user was shown and ignored.

Choosing it: what must hold

  • Implicit feedback: records of what users interacted with, without explicit negative ratings.
  • A sampler that draws, for each observed item, an item the user has not interacted with.
  • A goal defined by ranking quality, such as AUC or recall at k, not by predicting a rating value.

When to choose something else

IfUse instead
You have explicit ratings and want to predict their valueMean squared error on the ratings
The catalogue is very large and you train a two-tower retrieval modelSampled softmax or InfoNCE with in-batch negatives
You need a calibrated probability of a clickBinary cross-entropy

Math foundations

  1. The score gap

    duij=sui−sujd_{uij} = s_{ui} - s_{uj}

    For user uu, the score of the interacted item ii minus the score of the sampled item jj. A positive gap means the pair is ranked correctly.

  2. The model of a preference

    P(i>uj)=σ(duij)P(i >_u j) = \sigma(d_{uij})

    The probability that user uu prefers ii to jj is taken to be the sigmoid of the gap. A gap of zero means a coin flip.

  3. The loss

    L=−1N∑(u,i,j)ln⁡σ(duij)=1N∑(u,i,j)ln⁡ ⁣(1+e−duij)\mathcal{L} = -\frac{1}{N}\sum_{(u,i,j)} \ln \sigma(d_{uij}) = \frac{1}{N}\sum_{(u,i,j)} \ln\!\big(1 + e^{-d_{uij}}\big)

    The negative log-likelihood of the observed preferences. It is binary cross-entropy on the gap with the label always 1.

  4. Gradients for the two scores

    ∂ℓ∂sui=−σ(−duij),∂ℓ∂suj=+σ(−duij)\frac{\partial \ell}{\partial s_{ui}} = -\sigma(-d_{uij}), \qquad \frac{\partial \ell}{\partial s_{uj}} = +\sigma(-d_{uij})

    Equal and opposite: raise the positive score, lower the negative one. The size is the probability the model currently gives to the wrong order.

Symbols

u,i,ju, i, j
a user, an item the user interacted with, and a sampled item the user did not
sui,sujs_{ui}, s_{uj}
model scores for the positive and negative item; pos_score and neg_score
duijd_{uij}
the score gap, positive minus negative
σ\sigma
the logistic sigmoid
ℓ\ell
the loss for one triple
L\mathcal{L}
the mean loss over the batch
NN
the number of triples in the batch
i>uji >_u j
user u prefers item i to item j

Worked by hand

One triple with positive score 2 and negative score 0.5. Use e−1.5=0.2231e^{-1.5} = 0.2231.

d=2−0.5=1.5d = 2 - 0.5 = 1.5
ℓ=ln⁡(1+0.2231)=0.2014\ell = \ln(1 + 0.2231) = 0.2014
σ(−1.5)=0.22311.2231=0.1824\sigma(-1.5) = \frac{0.2231}{1.2231} = 0.1824
∂ℓ∂s+=−0.1824,∂ℓ∂s−=+0.1824\frac{\partial \ell}{\partial s^{+}} = -0.1824, \qquad \frac{\partial \ell}{\partial s^{-}} = +0.1824

The pair is ranked correctly, so the loss is a modest 0.2014. The model still gives 18 percent to the wrong order, and that is the size of the push on each score.

Visual example

Loading the example.

Try this

  • Move across the curve: the height is what the model is charged.
  • Move each control and watch which part of the curve it changes.

Code sample

import numpy as np
from impl import BPRLoss
from config import BPRLossConfig

loss = BPRLoss(BPRLossConfig())
rng = np.random.default_rng(0)
user, pos_item, neg_item = rng.normal(size=(3, 4, 8))   # 4 triples of 8-dim embeddings
pos_score = (user * pos_item).sum(axis=1)                # (4,)
neg_score = (user * neg_item).sum(axis=1)                # (4,)
print(loss.forward(pos_score, neg_score))
g_pos, g_neg = loss.backward(pos_score, neg_score)       # chain these into the embeddings:
grad_user = g_pos[:, None] * pos_item + g_neg[:, None] * neg_item
Read the implementation (55 lines)
"""BPR loss for implicit-feedback ranking: -log(sigmoid(pos_score - neg_score)).

NumPy only. `forward` returns the loss, `backward` its gradients with respect to the positive and the negative
scores.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import BPRLossConfig
except ImportError:  # run from the template's own folder
    from config import BPRLossConfig

def _reduce(per_row: np.ndarray, reduction: str):
    """Reduce one loss value per row: "mean" and "sum" give a float, "none" returns the (N,) array."""
    if reduction == "mean":
        return float(per_row.mean())
    return float(per_row.sum()) if reduction == "sum" else per_row


def _scores(pos_score, neg_score) -> tuple[np.ndarray, np.ndarray]:
    """Both score arrays as floats of one shape. Raises ValueError when the shapes differ."""
    pos, neg = np.asarray(pos_score, dtype=float), np.asarray(neg_score, dtype=float)
    if pos.shape != neg.shape:
        raise ValueError(f"pos_score and neg_score must have the same shape, got {pos.shape} and {neg.shape}")
    return pos, neg


class BPRLoss:
    """-log(sigmoid(pos_score - neg_score)) for (user, positive item, negative item) triples."""

    def __init__(self, config: BPRLossConfig | None = None) -> None:
        self.config = config or BPRLossConfig()

    def forward(self, pos_score: np.ndarray, neg_score: np.ndarray):
        """pos_score: (N,) model scores of the interacted items. neg_score: (N,) scores of the sampled
        non-interacted items for the same users. Returns a float, or (N,) for "none"."""
        pos, neg = _scores(pos_score, neg_score)
        # -log(sigmoid(d)) = log(1 + exp(-d)); logaddexp cannot overflow
        return _reduce(np.logaddexp(0.0, -(pos - neg)), self.config.reduction)

    def backward(self, pos_score: np.ndarray, neg_score: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
        """Gradients of the reduced loss with respect to pos_score and neg_score, each of shape (N,).

        d loss / d pos = -sigmoid(neg - pos) and d loss / d neg is its negative (both divided by N for "mean").
        For "none" the per-row derivatives are returned unscaled.
        """
        pos, neg = _scores(pos_score, neg_score)
        g_pos = -np.exp(-np.logaddexp(0.0, pos - neg))  # -sigmoid(-(pos - neg))
        if self.config.reduction == "mean":
            g_pos = g_pos / max(pos.size, 1)
        return g_pos, -g_pos

    __call__ = forward
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
6, run with python3 -m unittest -v

Practice

Build BPRLoss(BPRLossConfig(reduction="none")) and call forward with pos_score fixed at 0 and neg_score at -4, -2, 0, 2, 4. Describe how the loss grows. Then call backward and confirm the two returned gradients are equal and opposite.

Check on learning

  1. Adding 10 to every score for one user leaves the loss unchanged. What does that tell you about what the model can and cannot learn from this loss?
    A way to think about it

    Only differences enter the loss. Ask whether a per-user offset or a notion of absolute relevance can be recovered from differences alone.

  2. After a few epochs most sampled negatives have a gap above 5. What is the gradient from those triples, and what would you change?
    A way to think about it

    Evaluate σ(−5)\sigma(-5). Nearly all triples contribute nothing. Consider sampling negatives that the model currently scores highly.

  3. A user has not clicked on an item simply because they never saw it. How does that affect the assumption behind the loss?
    A way to think about it

    The method treats not interacted as less preferred. Think about which items are most often unseen yet relevant, and what pushing them down does to the recommendations.

  4. Why train on pairs rather than predicting a click probability for each item separately?
    A way to think about it

    The task is ordering. A pointwise loss must also label every non-interaction as a definite negative, which is a stronger claim than ranking it below a known positive.