195. 计算隐式反馈的 BPR ranking loss 并防止溢出
在隐式反馈(点击、播放)场景下,你很难知道用户不喜欢什么,只能知道他们接触了什么。Bayesian Personalised Ranking (BPR) 通过训练 embeddings,使得用户对已交互 item 的评分高于未交互 item。
编写 bpr_loss(U, V, triples)。U 的 shape 为 (n_users, k),V 的 shape 为 (n_items, k),triples 是一个 (u, i, j) 列表,表示用户 u 交互了 item i 但没有交互 item j。对于每个 triple,x = U[u] @ V[i] - U[u] @ V[j]。loss 是所有 triples 的 -log(sigmoid(x)) = log(1 + exp(-x)) 的均值。
使其具备数值稳定性:x 可能在两个方向上都非常大,且结果必须保持有限(当 x = -1000 时,该项应为 1000)。
def bpr_loss(U, V, triples)示例 1
输入: U = [[1, 0]], V = [[2, 0], [0, 1]], triples = [(0, 0, 1)]
输出: x = 2 and loss log(1 + e^-2) = 0.126928
示例 2
输入: U = [[10.0]], V = [[-50.0], [50.0]], triples = [(0, 0, 1)]
输出: 1000.0
示例 3
输入: U = [[10.0]], V = [[50.0], [-50.0]], triples = [(0, 0, 1)]
输出: 0.0
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
提示 1
For each triple you want the score of the item the user touched to be higher than the other item, and the loss is the softplus of the negative score gap.
提示 2
Gather the user, positive, and negative rows with integer arrays, compute x = U[u] dot (V[i] - V[j]) for every triple, then average log(1 + exp(-x)).
提示 3
Use np.logaddexp(0, -x) for log(1 + exp(-x)) so huge positive or negative x never overflows; the row wise dot is (U[u] * (V[i] - V[j])).sum(axis=1).
理解思路
通过点击和播放,你只知道用户接触了什么,而不知道他们不喜欢什么。BPR 只要求正确的排序:对于该用户,被接触过的 item i 的评分应该高于未被接触过的 item j。分值差距 x = U[u] . V[i] - U[u] . V[j] 被带入 logistic loss,当 x 为较大的正数时,loss 很小。
U = [[1, 1]], V = [[1, 0], [3, 0]], triple (0, 0, 1)。item 0 的分值是 1,item 1 的分值是 3,所以 x = -2,loss 为 log(1 + e^2) = 2.1269,因为顺序错误,所以惩罚很大。
loss = mean over triples of log(1 + exp(-x))。为了稳定性,永远不要计算一个很大的正数的 exp:使用恒等式 log(1 + exp(z)) = max(z, 0) + log(1 + exp(-|z|)),其中 z = -x。当 x = -1000 时,这会得到精确的 1000。该方法用于训练信息流、音乐和购物场景下的隐式反馈推荐系统。