Take one SGD step of Bayesian personalized ranking
Why it matters BPR-style pairwise updates train implicit-feedback recommenders where only clicks or purchases are observed.
BPR trains embeddings so a user scores an item they interacted with (i) above one they did not (j). Each training step uses one (u, i, j) triple.
Write bpr_step(U, V, u, i, j, lr, reg). U is (n_users, d), V is (n_items, d); work on float copies. With x = U[u] . (V[i] - V[j]) and g = sigmoid(-x) (computed stably), do gradient ASCENT on log sigmoid(x) - reg/2 * (|U[u]|^2 + |V[i]|^2 + |V[j]|^2), using the OLD vectors for every gradient:
- U[u] += lr * (g * (V[i] - V[j]) - reg * U[u])
- V[i] += lr * (g * U[u] - reg * V[i])
- V[j] += lr * (-g * U[u] - reg * V[j])
Return (U, V).
def bpr_step(U, V, u, i, j, lr, reg)Example
bpr_step([[1, 0]], [[0, 0], [0, 0]], 0, 0, 1, 0.1, 0.0) gives (array([[1., 0.]]), array([[0.05, 0.], [-0.05, 0.]])).
Understand the idea
With implicit feedback (clicks, purchases) we never see dislikes, only things the user did and did not touch. BPR turns this into ranking: for a user, a clicked item i should score higher than a random unclicked item j. Each step looks at one such triple and nudges the embeddings to widen the gap.
Example: user vector [1, 0], both items at [0, 0], so the gap x = 0 and sigmoid(-0) = 0.5. With lr 0.1: item i moves by 0.1 * 0.5 * [1, 0] = [0.05, 0], item j moves the other way to [-0.05, 0], and the user vector does not move because V[i] - V[j] was zero.
Rules: x = u . (v_i - v_j); g = sigmoid(-x); u += lr (g (v_i - v_j) - reg u); v_i += lr (g u - reg v_i); v_j += lr (-g u - reg v_j).
When the gap is already large, g is near 0 and the step is tiny, so training focuses on hard pairs.
Shapes and data flow
U: (n_users, d), V: (n_items, d); U[u], V[i], V[j]: (d,) -> x scalar