#347Pairwise Ranking Loss (BPR / RankNet)Medium

Pairwise Ranking Loss (BPR / RankNet)

Background

Pairwise ranking loss treats ranking as a series of pairwise preference choices: positive item ii should outrank negative item jj. The Bradley-Terry / RankNet form uses a logistic on the score difference; BPR (Bayesian Personalised Ranking) is the same loss applied to implicit-feedback recsys.

Problem statement

Implement pairwise_ranking_loss(scores_pos, scores_neg) returning the mean BPR/RankNet loss:

L  =  1Nilnσ ⁣(si+si)\mathcal{L} \;=\; -\frac{1}{N}\sum_i \ln \sigma\!\bigl(s^+_i - s^-_i\bigr)

where si+,sis^+_i, s^-_i are the model scores for the positive and negative items in pair ii.

Input

  • scores_pos - 1-D array of positive scores, length NN.
  • scores_neg - 1-D array of negative scores, length NN.

Output

  • float >= 0, the mean loss.

Examples

Input: scores_pos=[2.0], scores_neg=[1.0]
Output: -ln(sigma(1)) ~= 0.3133

Constraints

  • Use a numerically stable softplus: lnσ(x)=softplus(x)-\ln \sigma(x) = \mathrm{softplus}(-x). The naive form overflows for very negative xx.
  • Lengths must match; ValueError otherwise.

Notes

  • Pairwise vs pointwise. Pointwise (BCE on individual items) optimises calibration; pairwise optimises ordering. Production rankers often use pointwise + pairwise auxiliary.
Python
Loading...

▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.

  • reference single pair pos-neg=1
  • example two pairs
  • sample asymmetric triple