Compute the BPR ranking loss for implicit feedback without overflow
With implicit feedback (clicks, plays) you rarely know what a user dislikes, only what they touched. Bayesian Personalised Ranking (BPR) trains embeddings so a user scores an item they interacted with above one they did not.
Write bpr_loss(U, V, triples). U has shape (n_users, k), V has shape (n_items, k), and triples is a list of (u, i, j) where user u interacted with item i but not item j. For each triple, x = U[u] @ V[i] - U[u] @ V[j]. The loss is the mean over triples of -log(sigmoid(x)) = log(1 + exp(-x)).
Make it numerically stable: x can be very large in either direction, and the result must stay finite (for x = -1000 the term is 1000).
def bpr_loss(U, V, triples)Example
U = [[1, 0]], V = [[2, 0], [0, 1]], triples = [(0, 0, 1)] gives x = 2 and loss log(1 + e^-2) = 0.126928.
Understand the idea
With clicks and plays you know what a user touched, not what they disliked. BPR only asks for the right order: the touched item i should score higher than an untouched item j for that user. The score gap x = U[u] . V[i] - U[u] . V[j] goes into a logistic loss, which is small when x is large and positive. Worked example: U = [[1, 1]], V = [[1, 0], [3, 0]], triple (0, 0, 1). Score of item 0 is 1, item 1 is 3, so x = -2, and the loss is log(1 + e^2) = 2.1269, a big penalty because the order is wrong. Rule: loss = mean over triples of log(1 + exp(-x)). For stability, never compute exp of a large positive number: use the identity log(1 + exp(z)) = max(z, 0) + log(1 + exp(-|z|)), with z = -x. For x = -1000 this gives exactly 1000. Used to train implicit-feedback recommenders for feeds, music and shopping.