AI Wiki中文/EN

Ranking objectives: a good score is not yet a good order

推荐排序目标

Train one scorer with pointwise, pairwise and listwise losses, then examine score shifts and NDCG.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The same ordering can have very different squared error

Scores [0.4,0.3,−0.2] and [10.4,10.3,9.8] rank three items identically. Against fixed relevance labels [2,1,0], however, their squared errors are very different. A score-fitting objective asks something beyond “put the better item first.” Before choosing a loss, decide what the labels mean and which errors matter.

Pointwise objectives examine individual items, pairwise objectives examine relative preferences, and listwise objectives examine a group of items for the same query or user context. Burges’s RankNet overview derives a pairwise logistic loss from score differences. PDF 2–3 BPR derives a related log-sigmoid criterion for implicit recommendation, with a specific assumption about observed versus unobserved items. PDF 3–4

This article trains the same linear scorer under three objectives. The comparisons use authored graded labels, so the pairwise experiment is not silently presented as BPR’s exact implicit-data sampling protocol.

Three training objectives fit different priorities; a common score shift preserves ordering but changes squared error.
Three training objectives fit different priorities; a common score shift preserves ordering but changes squared error.

Three ways to tell a scorer it is wrong

For query/context q and candidate i, let x_qi contain F features. Use a shared linear scorer and regularize its weights:

sqi=w⊤xqi,L(w)=Ldata(w)+λ2∥w∥22.s_{qi}=w^\top x_{qi},\qquad L(w)=L_{\rm data}(w)+\frac\lambda2\|w\|_2^2.

The example uses relevance labels 0, 1 and 2. They are grades, not click probabilities. A pointwise squared objective over Q contexts and N candidates per context is:

Lpoint=12QN∑q,i(sqi−yqi)2.L_{\rm point}=\frac{1}{2QN}\sum_{q,i}(s_{qi}-y_{qi})^2.

It cares about the absolute numerical scale of scores. In a rating task that may be useful. If the aim is top-of-list ordering, a large absolute error on a low-ranked item can consume effort without correcting the decision that matters.

Let D contain triples (q,i,j) with a strict labeled preference y_qi>y_qj. A pairwise logistic objective is:

Lpair=1∣D∣∑(q,i,j)∈Dlog⁡(1+exp⁡[−(sqi−sqj)]).L_{\rm pair}=\frac1{|D|}\sum_{(q,i,j)\in D}\log\big(1+\exp[-(s_{qi}-s_{qj})]\big).

This is the strict-preference RankNet data loss with sigmoid scale one. Tied-label pairs are omitted here; RankNet can also model a tie with target probability one half. BPR’s implicit training triples instead pair an observed item with an unobserved one for the same user. That is an assumed preference relation, not a verified statement that all unobserved items are disliked. Two observed items do not automatically have an ordering under that construction. RankNet, PDF 2–3 BPR, PDF 3–4

Writing delta=s_i−s_j, a single pair contributes opposite score gradients:

∂ℓ∂si=−σ(−δ),∂ℓ∂sj=σ(−δ),σ(a)=11+e−a.\frac{\partial\ell}{\partial s_i}=-\sigma(-\delta),\qquad\frac{\partial\ell}{\partial s_j}=\sigma(-\delta),\qquad\sigma(a)=\frac1{1+e^{-a}}.

The preferred item is pushed up and the other down. At equal scores, the loss is log 2 and the gradients are −0.5 and +0.5. Stable logaddexp avoids overflow when the current ordering is badly wrong. Pair sampling determines how often users, items and grades influence the update; changing that sampling changes the effective objective unless compensated.

Our listwise teaching choice normalizes graded gains into a target distribution and compares it with a score softmax:

gqi=2yqi−1,tqi=gqi∑jgqj,pqi=esqi∑jesqj,Llist=−1Q∑q,itqilog⁡pqi.g_{qi}=2^{y_{qi}}-1,\quad t_{qi}=\frac{g_{qi}}{\sum_jg_{qj}},\quad p_{qi}=\frac{e^{s_{qi}}}{\sum_je^{s_{qj}}},\quad L_{\rm list}=-\frac1Q\sum_{q,i}t_{qi}\log p_{qi}.

At least one positive gain per context is required. A zero-gain row is rejected, not divided by zero. This disclosed gain-target cross-entropy is a concrete listwise objective; it is not claimed to reproduce the complete ListNet algorithm or directly optimize NDCG. Its score gradient is (p−t)/Q. The list denominator couples all candidates, unlike separately fitted pointwise examples.

Evaluation can use normalized discounted cumulative gain at k:

NDCG@⁡k=∑r=1k(2yπr−1)/log⁡2(r+1)max⁡π∑r=1k(2yπr−1)/log⁡2(r+1).\operatorname{NDCG@}k=\frac{\sum_{r=1}^{k}(2^{y_{\pi_r}}-1)/\log_2(r+1)}{\max_\pi\sum_{r=1}^{k}(2^{y_{\pi_r}}-1)/\log_2(r+1)}.

Only available list positions are summed when k exceeds the list length. If every gain is zero, this program reports None. A surrogate training loss and a ranking metric answer different questions; a lower surrogate need not improve every top-k decision.

Adding a common constant c to a context’s scores preserves pair differences and its softmax:

(si+c)−(sj+c)=si−sj,softmax⁡(s+c1)=softmax⁡(s).(s_i+c)-(s_j+c)=s_i-s_j,\qquad\operatorname{softmax}(s+c\mathbf1)=\operatorname{softmax}(s).

Thus pairwise and this listwise data loss are shift-invariant. The pointwise squared loss against fixed labels is not. The statement concerns scores and data terms: changing model parameters to create a shift may also change regularization.

Use one scorer and change only its feedback

Run the original program with Python 3.12 and NumPy 1.26.4. Seed 23 creates 3 contexts, 5 items per context and 3 features per item. A planted linear ranking assigns grade 2 to the first item, grade 1 to the next two and 0 to the remaining two. There are 24 strict preference pairs. All reported NDCG values are on these training lists.

"""Original pointwise, pairwise and listwise objectives on a common linear scorer."""
import json
import numpy as np


def validate(features,labels):
    x=np.asarray(features,float);y=np.asarray(labels,float)
    if x.ndim!=3 or min(x.shape)==0 or y.shape!=x.shape[:2] or not np.isfinite(x).all() or not np.isfinite(y).all() or (y<0).any():raise ValueError('query/item/feature tensor and nonnegative labels required')
    return x,y


def sigmoid(x):return np.exp(-np.logaddexp(0,-np.asarray(x,float)))


def loss_gradient(features,labels,weights,kind='pairwise',regularization=.01):
    x,y=validate(features,labels);w=np.asarray(weights,float)
    if w.shape!=(x.shape[2],) or not np.isfinite(w).all() or not np.isfinite(regularization) or regularization<0:raise ValueError('compatible finite weights and ridge required')
    scores=x@w;g=np.zeros_like(scores)
    if kind=='pointwise':
        error=scores-y;loss=.5*float(np.mean(error*error));g=error/error.size
    elif kind=='pairwise':
        pairs=[(q,i,j) for q in range(len(y)) for i in range(y.shape[1]) for j in range(y.shape[1]) if y[q,i]>y[q,j]]
        if not pairs:raise ValueError('at least one strict preference pair required')
        loss=0.
        for q,i,j in pairs:
            delta=scores[q,i]-scores[q,j];loss+=float(np.logaddexp(0,-delta))/len(pairs)
            derivative=-float(sigmoid(-delta))/len(pairs);g[q,i]+=derivative;g[q,j]-=derivative
    elif kind=='listwise':
        gains=np.exp2(y)-1
        if not np.isfinite(gains).all() or (gains.sum(axis=1)==0).any():raise ValueError('finite positive total gain per query required')
        target=gains/gains.sum(axis=1,keepdims=True);shift=scores-scores.max(axis=1,keepdims=True);logp=shift-np.log(np.exp(shift).sum(axis=1,keepdims=True))
        loss=-float(np.sum(target*logp))/len(y);g=(np.exp(logp)-target)/len(y)
    else:raise ValueError('unknown ranking objective')
    return loss+.5*regularization*float(w@w),np.einsum('qif,qi->f',x,g)+regularization*w


def fit(features,labels,kind='pairwise',steps=400,rate=.2,regularization=.01):
    x,y=validate(features,labels)
    if not isinstance(steps,int) or steps<0 or not np.isfinite(rate) or rate<=0:raise ValueError('valid optimizer controls required')
    w=np.zeros(x.shape[2]);history=[]
    for step in range(steps+1):
        loss,g=loss_gradient(x,y,w,kind,regularization);history.append(loss)
        if step<steps:w-=rate*g
    return w,history


def ndcg(labels,scores,k=3):
    y=np.asarray(labels,float);s=np.asarray(scores,float)
    if y.ndim!=1 or s.shape!=y.shape or not np.isfinite(y).all() or not np.isfinite(s).all() or (y<0).any() or not isinstance(k,int) or k<1:raise ValueError('valid label/score vectors and positive k required')
    def dcg(order):return sum(float(np.expm1(np.log(2)*y[i]))/np.log2(rank+2) for rank,i in enumerate(order[:k]))
    ideal=dcg(sorted(range(len(y)),key=lambda i:(-y[i],i)))
    return dcg(sorted(range(len(s)),key=lambda i:(-s[i],i)))/ideal if ideal else None


def demo():
    rng=np.random.default_rng(23);x=rng.normal(size=(3,5,3));latent=x@np.array([1.,-.5,.3]);y=np.zeros((3,5))
    for q in range(3):
        order=np.argsort(-latent[q]);y[q,order[0]]=2;y[q,order[1:3]]=1
    rows=[]
    for kind in ['pointwise','pairwise','listwise']:
        w,h=fit(x,y,kind);scores=x@w
        rows.append(dict(kind=kind,loss=[h[0],h[-1]],weights=w.tolist(),ndcg=[ndcg(y[q],scores[q]) for q in range(3)]))
    y1=np.array([2.,1.,0.]);s1=np.array([.4,.3,-.2]);offset=10.
    pair=lambda s:float(np.mean([np.logaddexp(0,-(s[i]-s[j])) for i in range(3) for j in range(3) if y1[i]>y1[j]]))
    target=(2**y1-1)/(2**y1-1).sum()
    listloss=lambda s:float(-target@(s-np.logaddexp.reduce(s)))
    return dict(rows=rows,labels=y.tolist(),strict_pairs=sum(y[q,i]>y[q,j] for q in range(3) for i in range(5) for j in range(5)).item(),
                offset_example=dict(pointwise=[float(np.mean((s1-y1)**2)/2),float(np.mean((s1+offset-y1)**2)/2)],pairwise=[pair(s1),pair(s1+offset)],listwise=[listloss(s1),listloss(s1+offset)]),
                hand=dict(tied_pair_loss=float(np.logaddexp(0,0)),ndcg_swapped=ndcg([2,1,0],[1,2,0],k=2)))


if __name__=='__main__':print(json.dumps(demo(),allow_nan=False))

Each model starts from zero weights, uses lambda 0.01, learning rate 0.2 and 400 full-batch steps. Pointwise loss falls from 0.6 to 0.444370, pairwise loss from 0.693147 to 0.130132, and listwise loss from 1.609438 to 1.034285. Those absolute numbers have different scales and should not be compared as if they were the same metric.

Training NDCG@3 is approximately [0.847267,0.726229,1] for pointwise fitting, and [1,1,1] for each of the other objectives. This is a constructed illustration of different priorities, not a claim that pairwise or listwise learning always generalizes better.

In the score-shift example, mean half-squared error rises from 0.515 to 42.181667. Pairwise loss stays about 0.518654 and listwise loss about 0.922576. A separate hand case swaps grades 2 and 1 in the first two positions, giving NDCG@2 of 0.796708. Tests independently finite-difference all three weight gradients and check an extreme reversed pair with score difference −2000.

Dense linear scoring takes O(Q N F). Pointwise and listwise objectives add O(Q N) work. This simple pair implementation constructs all ordered candidate pairs, taking O(Q N²) time to discover strict pairs and O(|D|) memory to retain them. The chain-rule reduction to weight gradients costs O(Q N F). For large candidate lists, choose a documented pair-sampling scheme instead of pretending all pairs are free. Exact metric sorting here costs O(Q N log N).

The negative item may simply have had no exposure

Implicit labels depend on which items the user was shown. Treating every noninteraction as a lower preference encodes an assumption about that missingness. BPR formalizes a useful training relation; it does not eliminate exposure bias. PDF 3 Reweighting, counterfactual estimation or exploration require additional data and assumptions beyond this example.

Pairwise improvement can also spend effort on low-ranked pairs that barely affect NDCG@k. The three objectives here do not incorporate cost, diversity or eligibility. Use a fixed candidate universe for comparisons, tune on a separate validation split, and evaluate later unseen decisions. Sampling a much smaller evaluation list changes the ranking task; state the sampling protocol rather than comparing that score with full-catalog evaluation.

What does the loss ignore?

  1. What happens to ordering when every score receives +10? Answer: Nothing. The relative comparisons are unchanged, although pointwise squared error against fixed labels generally changes.
  2. What is the strict-preference pair loss and score gradient at a tie? Answer: Loss log 2; gradients −0.5 for the preferred item and +0.5 for the other, before any averaging or regularization.
  3. Why reject a zero-gain list for this listwise target? Answer: Its gain normalization denominator is zero. It does not define the target distribution used by this objective.
  4. Does BPR observe that every unclicked item is disliked? Answer: No. It assumes an observed item should outrank an unobserved one for training. Lack of exposure or a missing action can explain the absence of a click.

Separate the preference relation, loss and metric

The BPR source supplies the implicit preference construction and Bayesian log-sigmoid criterion. Burges supplies RankNet’s score-difference loss and gradient; the existing source object is preserved, with this additional reading recorded separately. The graded fixture, gain-target listwise loss and three-way comparison are original. No production ranking service, sampled-negative benchmark or LambdaMART implementation is reproduced. Recommendation diversity next asks what a relevance-only order leaves out.

Make a prediction, then check

Adding the same constant to every score preserves which quantities here?

Choose one answer

Learning objectives

  • Derive score gradients and distinguish observed preferences, surrogate losses and evaluation metrics.
  • Run the original computation and explain a counterexample without claiming a public benchmark result.

Prerequisites & connections

Explore related knowledge →

References

  1. BPR: Bayesian Personalized Ranking from Implicit Feedback
    Steffen Rendle; Christoph Freudenthaler; Zeno Gantner; Lars Schmidt-Thieme · 2009
  2. From RankNet to LambdaRank to LambdaMART: An Overview
    Christopher J. C. Burges · 2010

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-23 · Single AI author. Scoped reading: Read PDF 1 identity, page 3 training-set discussion and page 4 criterion; viewed page 4. Observed-versus-unobserved preference assumption and log-sigmoid. No LearnBPR or benchmark reproduction. Source material and further reading. See individual article citations for supported claims. 7 paired equations and four explained exercises. Checked point/pair/list gradients by finite differences, score-shift invariance, stable extreme logistic loss and hand NDCG. Three authored training lists; gain-target CE is an explicit teaching choice.

  • Checked point/pair/list gradients by finite differences, score-shift invariance, stable extreme logistic loss and hand NDCG. Three authored training lists; gain-target CE is an explicit teaching choice.
  • Four computed SVG variants per topic;10 numeric/geometry tests and30 responsive cases passed. Ten selected final captures directly viewed. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.