Matching is different from ranking

Ranking vs matching

  • In classic recsys / ads ranking, items are non-rival
    • Same reel recommended to a million users costs nothing
    • Greedy argmax per request is approximately the global optimum
    • Closest exception is ads budget: the budget is rival, and the pacing multiplier is its λ. Same math shows up below
  • In matching (jobs, dating), the resource is attention and capacity, which is rival
    • If the model surfaces candidate X to 500 recruiters, X can respond to maybe 10
    • Greedy per request is provably sub-optimal. Optimal rankings must account for both sides’ preferences and capacity constraints
maximize Σ_{r,c} match_prob(r, c) · x_{r,c}
subject to Σ_c x_{r,c} ≤ K_r (recruiter review capacity)
Σ_r x_{r,c} ≤ K_c (candidate attention capacity)
where
x_{r,c} = show candidate c to recruiter r (1) or not (0). The LP relaxes it to a fraction between 0 and 1
(LP = Linear Programming)
K_r = how many candidates recruiter r can review;
K_c = how many messages candidate c can handle
  • It is an asymmetric marketplace
    • Recruiter reviews ~100 candidates in a session; candidate applies to ~20 jobs
    • Volumes, rate limits and session structure differ on both sides
    • Dating / matrimony are relatively symmetric
  • Running example: candidate recs to a recruiter
    • I will use it as reference for this post
  • Measuring congestion
    • Load: InMails per candidate per week (p95, share going to the top 1% of candidates)
    • Overlap: how many recruiters were shown the same candidate in a week
    • Damage: reply rate vs inbox load. If reply rate falls as pending messages rise, the candidate is congested
    • Flip side: matching candidates who got zero InMails (starvation)

Two probabilities and their labels

  • p_send(r,c) = P(recruiter messages candidate | shown). Is the candidate suitable?
  • p_reply(r,c) = P(candidate accepts | messaged). Will they respond? This is where “candidate has 30 pending InMails” lives
  • p_match = p_send × p_reply

Two interlocking funnels, joining at the mutual event:

Outbound (recruiter acts first): shown → profile view → InMail sent → InMail accepted ◀
Inbound (candidate acts first): shown → view JD → apply ────────────→ recruiter replies ◀
│
Joint: interview → offer → hire
We are focus on outbound here. So first mutual event is "In mail accepted"
p_sendp_reply
PositiveInMail sent (or saved to pipeline)InMail accepted
Negativeshown and seen, no actiondeclined, or no reply after N days
Training rowsrecruiter impressionssent InMails only
Label latencyminutesdays
Densitydensesparse

Which label to train on: the earliest event that needs both sides to act. LinkedIn Recruiter uses InMail Accept as the signal of two-way interest (LinkedIn Eng, 2019). One-sided clicks say nothing about mutual fit.

Four things that make the labels hard:

  1. Delayed terminal label
    • Hire lands weeks later. Train on the mutual proxy, validate on hire
    • If a change improves reply rate but not hire rate, you’ve started optimizing politeness instead of matching
  2. Right censoring: no outcome yet ≠ negative
    • Wait a window before calling a negative; use fast explicit signals early
    • LinkedIn’s applicant model: ~30% of positives known within a day, negatives conclusive after 14 days, earlier negatives inferred if the recruiter replies to later applicants (LinkedIn Eng, 2020)
  3. Ambiguous negatives (positive-unlabelled data)
    • No reply could mean bad fit, recruiter on leave, or req already filled
    • Drop rows from inactive recruiters and closed reqs before training
  4. Selection bias and self-fulfilling labels
    • p_reply only sees candidates recruiters chose to message, but it scores everyone shown. Same as CVR in ads: trained on clicks, served on impressions
    • Fix: ESMM-style training over the full impression space.
      • Supervise
        • p_send
        • p_send·p_reply
      • p_reply is learned implicitly
    • Position bias compounds into allocation: whoever ranks high collects labels and stays high. Position feature + small exploration

One model or two?

  • (a) Two separate models
  • (b) Shared trunk, two heads (standard MTML)
  • (c) Shared trunk with expert gating (MMoE / PLE), when the heads start fighting
    • MMoE: several shared expert networks; each head has its own gate that picks a mix of experts
    • PLE: MMoE plus experts private to each head, so one head’s gradients can’t overwrite the other’s
Shared trunk + 2 headsSeparate models
Sparse p_replyDense p_send labels shape the representation the sparse head usesp_reply trains on little data
Selection biasESMM trick needs both heads in one graphHandled separately per model
Conflicting featuresNegative transfer: inbox load raises p_send (desirable profile) and lowers p_reply (saturated). One head usually losesEach model uses the feature its own way
Label cadenceWaits for the slowest label, or trains on censored p_reply labelsp_send retrains hourly, p_reply daily
OwnershipOne change retrains both heads; loss weight between heads is one more knobIndependent launches, calibration and debugging
ServingOne feature fetch, one callTwo calls, duplicate infra
  • Default: shared trunk + two heads
  • Add gating (MMoE/PLE) or keep conflicting features head-specific when per-head metrics show a seesaw
    • seesaw – improving one head’s metric makes the other’s worse
  • Split p_reply into its own model when label cadence becomes the bottleneck
  • Either way, calibrate each head on its own before combining

Combining into one score

Combiners that ignore capacity

  • Naive product of two marginals: p(r→c) × p(c→r)
    • p(r->c) = recruiter likes candidate
    • p(c->r) candidate like recruiter
    • Assumes independence. A genuinely good fit pushes both up together, so it understates true matches and overstates one-sided ones
      • Understatement for true match
        • score – 0.9 * 0.9 = 0.81 ( which is less than 0.9)
      • Overstatement if one side is enthusiastic
        • score = 0.8 * 0.1 = 0.08
        • True mutual match is near 0
  • Chain rule: p_send × p_reply
    • p_reply is conditional on the message, clean way to write would be p(reply | message)
    • P-send = p(r->c)
    • This is P(mutual match), not a heuristic. Model the second head conditionally and the product is correct
  • Harmonic mean (RECON, dating)
    • Harmonic mean of the two one-sided compatibility scores, 2 / (1/s₁ + 1/s₂)
    • It has no probability meaning
    • Punishes imbalance harder than the product: (0.9, 0.1) → 0.18 but (0.3, 0.3) → 0.30, where the product ties both at 0.09
    • Other choices in the literature: arithmetic, geometric, weighted mean (survey)
  • Weighted geometric: p_send^α · p_reply^β
    • taking log -> α·log p_send + β·log p_reply
    • Candidate-scarce market: candidate attention is the bottleneck, so β > α. Protecting candidates from noise keeps the market liquid
    • It flips by segment: senior backend engineers are candidate-scarce, entry-level generalist roles are job-scarce, in the same product at the same time
  • Calibration compounds when you multiply
    • 20% overestimate on both heads → 1.2 × 1.2 = 1.44, a 44% overestimate on the product
    • A constant miscalibration doesn’t reorder; one that varies by segment does, and any threshold or λ comparison breaks
    • Calibrate each head per segment; monitor the product’s calibration separately
  • All of these say this pair is likely to match. None says whether the candidate’s attention is better spent elsewhere. That is the job of λ

Adding capacity: the λ term

Refine the candidate constraint. What fills an inbox is messages, not impressions:

Σ_r x_{r,c} · p_send(r,c) ≤ K_c

Relax it with λ_c ≥ 0 (and recruiter capacity with μ_r). The coefficient on each x_{r,c} becomes:

p_send·p_reply − λ_c·p_send − μ_r

Inside one recruiter’s request μ_r is the same for every candidate, so it only sets how many to show. Rank by:

score(r,c) = p_send(r,c) · ( p_reply(r,c) − λ_c )
  • λ_c = shadow price of one more message in candidate c’s inbox
  • Uncongested candidate: λ_c = 0, the score falls back to the plain product
  • Congested candidate (30 pending): λ_c > 0, so they surface only where p_reply is high enough to be worth the slot
  • Feature or λ? Both, for different jobs
    • Inbox load as a feature keeps p_reply honest about the candidate’s current state
    • λ enforces a policy (≤ K_c messages a week) and prices the opportunity cost to other recruiters. A feature alone just predicts lower and lower while recruiters keep messaging
    • Feature-only control can oscillate: congested → down-ranked → inbox clears → up-ranked → congested. Let the model estimate affinity; let λ do traffic control

Where λ comes from

A ladder, simplest first:

  1. Hand-tuned global weight
    • One λ (or α, β) picked by A/B. Simple; blind to which candidate is congested
  2. Forecast + rule-based penalty
    • LinkedIn’s LiJAR for job recs: forecast how many applications a job will get by expiry, then promote under-supplied and penalize over-supplied jobs (KDD’17). λ in spirit, rules in practice
  3. Offline dual solve, online serve
    • Solve the dual on a sample of traffic daily or hourly, store λ per entity, rank with the primal-from-dual formula at serve time
    • Origin: click shaping via Lagrangian duality. At LinkedIn scale: DuaLip, whose use cases include job-recommendation matching under job-apply budgets
  4. Online dual ascent (a controller)
    • Every window: λ_c ← max(0, λ_c + η·(messages_c − K_c))
    • Self-correcting, no solver. η too large → oscillation, too small → lag. Same loop as ad budget pacing
  5. Predicted λ
    • λ_c = f(features of c and its segment). Helps cold-start candidates and smooths millions of noisy λs
    • One practical recipe: regress on the λs from the offline solve

Tuning the knobs

  • What is left to tune once λ_c is computed
    • K_c: a product decision. How many InMails a week is too many?
    • α, β per segment; the controller step η
  • A/B grid
    • A few arms, one primary metric plus guardrails. Slow, coarse
  • Offline replay (counterfactual / IPS) to prune the grid
    • Misses market effects. Replay can’t see two recruiters competing for one candidate
  • Online Bayesian optimization
    • LinkedIn feed: maximize the primary metric subject to secondary metrics not dropping past a threshold; posterior updated hourly, parameters assigned per member by hashing (Agarwal et al., KDD’18)
    • Their feed score already carries a job-apply term: S = p_VA + x_EFS·p_EFS + x_JA·p_JA
  • Experiment design
    • Arms compete for the same candidates’ inboxes, so candidate-level randomization leaks
    • Randomize by market cluster (geo × job family) or by recruiter, or use switchbacks
  • Metrics to watch
    • Mutual accepts per recruiter session (primary)
    • Hires (lagging check on the proxy)
    • p95 InMails per candidate per week (congestion)
    • Share of candidates and jobs with zero engagement (starvation)

Summary

One thing worth internalizing again – why don’t we build model to predict p(match) directly ?

Pros of keeping it separate

  • Allows traffic control with λ_c
  • denser label
    • Separate model training cadense
    • Not much of a benefit if using ESMM on shared arch
  • Easy to debug / explain
    • Why the pair did not get the match
  • Build new products and monetization opportunities
    • “likely to respond” badge for recruiter

Pros of combing

  • Calibration error does not multiply
  • ESMM is giving you p_match anyways

[Paper] RankNet to LambdaRank to LambdaMART

Microsoft had published a paper on RankNet in 2005, which also won ICML’s test of time award in 2015. Subsequent improvement to that algorithm were lambdaRank and lambdaMART. The later had also won 2010 – learning to rank challenge. Current paper[1] summaries all three algorithms and incremental improvement they are mapping. It is written by Chris Burges who was involved in these development since RankNet.

Quick Gist

  • RankNet was trained using Neural Net.
  • RankNet was trained to minimize pair-wise differences.
  • LambdaNet was designed to maximise NDCG.
    • Which is more relevant to IR compared to pair-wise differences.
  • LambdaMART started using tree based boosting algorithms (MART, XgBoost etc)

RankNet

  • For a given query (q), we have two items (i and j)
    • I am writing down item but it would be any document (web page for example)
    • We will have features for
      • query
      • item
      • query item pairs
  • For both (q, i) and (q, j) we pass them through NeuralNet and get scores -> si and sj
    • We will also pass pairs which has same supervised label
  • We need to decided a loss function based on si and sj, gradient of which we will back propagate.
  • Computed probability formula y_hat
  • Supervised probability label y = (P_ij_bar) = (1 + S_ij) / 2
    • S_ij = { 0, 1, -1}
      • 1 if ( i is more relevant then j)
      • 0 if (i is less relevant then j)
      • 1/2 if both have same relevant scores
    • y will be in {0, 1/2, 1}
  • sigma determines shape of sigmoid
    • We would go to difference of (si – sj) on x-axis and read corresponding value from y axis.
    • sigma determines steepness around 0
    • This technique is known as temperature scaling. In tower network people use is when passing cosine similarity value to sigmoid.
    • Technique is useful when input has limited range
      • Cosine similarity has range (-1, 1)
      • s_i – s_j would also have smaller range
  • Cost function is cross entropy
  • One observation here is that when si = sj
    • cost = log 2 > 0
    • Document with different label but same score are still pushed aways from each other.

Speeding up RankNet Training by factoring

Defining lambda_ij

Defining lambda_i

  • What speedup did we achieve
    • Earlier for a given query we were computing lambda_ij for each pair and updating weights
    • Now we are computing lambda_i for each document and then update weight for given query
      • You can correlate this to going from SGD to mini-batch
      • We can do SGD at query, pair level or query level. We choose later.
  • Intuition of lambda_i
    • Direction(+Ve/-Ve) and magnitude where we want document to move
      • Move up/down in the ranking

LambdaRank

Figure below and caption explains why reducing pairwise difference does not necessarily results in increase of IR metrics. And LambdaRank is a way to optimize for IR metrics faster.

LamdaRank modified lamda_ij equation empirically as follows and it seemed to work well. We could do this because we don’t need to know actual cost function as long as we compute lamda_ij and then lamda_i

This becomes maximisation problem so we move in direction of gradient.

LambdaMART

  • MART – Multiple Additive Regression. Trees. For more info read the post on gradient boosting
  • To work with MART we need to specify two things
    • Gradient of loss function, which will be used to fit the trees
    • For the region in tree compute leaf value, that is done using line search/newton’s method
  • We had empirically defined lambda as gradient in lambdaRank, we use same lambda as gradient here as well.
  • For above lambda gradient, paper defines empirical cost function and then derives value at leaf nodes using newton’s method.
  • Key difference to observe between lambdaRank and lambdaMART
    • Lambda rank updates all weights (of classifier) after each query is examined
    • Leaf value at lambdaMART is computed for all query, item pairs that falls into that leaf
      • This allows lambdaMART to update splits and leaf values such that it may decrease utility for some queries but overall utility increases.
  • Training flow
    • 1) Score every item in the query with the current model and sort, which gives each item its current position.
    • 2) For each pair with different grades, compute the RankNet gradient × |ΔNDCG|.
    • 3) Sum those per item, so each item row gets one lambda (and one Hessian). The next tree fits those.
      • The pair gets same push in opposite direction
      • Example: the relevant item scores 1.2 and the irrelevant one 2.0. The RankNet gradient is 0.69 and |ΔNDCG| is 0.036, so λ_ij = 0.69 × 0.036 = 0.025. The relevant item gets +0.025 (push up) and the irrelevant one −0.025 (push down)

Reference

[0] : https://www.microsoft.com/en-us/research/blog/ranknet-a-ranking-retrospective/

[1] : https://www.microsoft.com/en-us/research/uploads/prod/2016/02/MSR-TR-2010-82.pdf

On Interleaving

This post summarises some concepts around interleaving. Take away for me in the topic is realisation that in some cases interleaving can be conclusive while a/b test is not. (examples of search improvement on small % of queries) and the intuition that why it converges faster. Also there is a broader topic – design of experiments. It is generally used in search systems and recommender systems. Both can come under umbrella of retrieval systems.

What is interleaving ?

  • It is a method to evaluate ranking system.
  • If we want to measure effectiveness of two ranker, we prepare a merged list and observe customer’s interaction on that.

Why do we need interleaving ?

  • It allows us to experiment faster.
    • It converges faster than a/b tests
  • For search systems many times a/b test might not converge at all
    • Say an improvement is affecting small % of search queries
  • Search system has low convergence say 4 %. How to measure algorithm that improves 0.5 % on top of that.
    • Lots of impressions are needed for convergence in a/b test.

Illustrative Examples

  • Shoe
    • Suppose for a given shoe design we have two compelling soles, we want to measure which one has better resistance to wear/tear
    • We have 100 people to test on
    • option 1 – classic a/b test
      • 50 people get each type of shoes
      • Two variability
        • How active the person under tests it
        • Quality of sole
    • option 2 – interleaved test
      • Different sole in left and right pair of shoe
      • Just one variability
        • Quality of sole
  • Soda [0]
    • We want to test what is more popular among population – Pepsi or Coke ?
    • option 1 – classic a/b test
      • Split population into two groups
        • One group receives Pepsi
        • Another one receives Coke
      • Measure soda consumption between two
      • Variability
        • Wide variation in soda consumption habit
        • Heavy soda consumer would be small % of population but large % of contributor
    • option 2 – interleaving
      • Allow people to choose either Pepsi or Coke.
      • Don’t mark a label, but can be visually distinguishable

For some tests interleaving is not possible.

  • In the shoe examples instead of sole, if we have two different design of shoe
  • In search systems, if you are changing some UI elements

Two tests Netflix did while introducing new interleaving system

  1. Compare sensitivity against traditional a/b tests [0]
    1. Before the test it was known that algorithm B is better than A
    2. They measure no of impressions it took to converge

2. Correlation of interleaving result with a/b tests [0]

On Metrics

  • Search systems have business metric like conversion & revenue
  • Netflix has business metrics like retention and streaming hours

Reference

[0] Netflix blog

[Paper] Semantic Product Search

  • Paper is related to search systems for e-commerce.
  • Shortcoming of BM-25
    • lack of understanding of hypernyms, synonyms, antonyms
      • hypernym – general/broad word
      • Color is hypernym for red
      • Examples
        • Red dress and burgundy dress
        • sneakers and running shoes
    • Morphological variants (woman vs women)
      • Stemming and lemmatization is typical solution
      • Requires numerous hand-crafted rules
        • Converts reading glasses to reading glass
    • Sensitivity to spelling error
      • Typically solved by spell correction algorithms

Architecture

  • Sharing embedding layer in siamese network work well, capturing local word level matching even before training this network.
  • Average pooling
    • Comparing to LSTM performance of average pooling reduced by just 0.5 %
    • Evaluation metric were MAP and Recall@100
    • It helped computationally
    • Unlike web search query and items titles have smaller length
    • Query also does not have stop words
  • Batch Normalisation
    • Length of items are generally longer than query
    • They had observed difference in magnitude after avg pooling of query and item
    • I have seen people using FC layer instead to have separate parameters

Loss Function

  • They first tried with 2 part hinge loss
  • Analysing the overlap items they found that they were clicked but not purchased.
    • They note that from matching standpoint these products are okay to show to customer
  • So they introduced third term and decided it’s threshold to be 0
  • EmpIrical values used episolon (+) = 0.9, episilon (-) = 0.2
  • My view on this
    • For the products that has clicks but not orders, new loss tries to keep it below 0.55
    • 2 part hinge loss was for purchased vs random items
    • Some of those random items had got clicks
    • For positive items when we get similarity above 0.9 it should contribute 0 to loss
    • For negative items if we get similarity below 0.2 it should contribute 0 to loss
    • For neutral items if we get similarity below 0.55 it should contribute 0 to loss
  • y_hat is cosine similarity
    • Based on which loss is calculated
    • Instead of passing cosine similarity to sigmoid they are passing it through hinge function.

Tokenization Methods

  • Word unigram
  • word n-gram
    • To preserve information about word ordering
    • They preferred word n-gram over LSTM or CNN
  • Character trigram
    • Robust typos (iphone & iphonr)
    • Compound words (amazontv & firetvstick)
    • Item parts and sizes
      • Tires have different sizes
      • TVs have different model
  • Handling unseen words
    • Common NLP techniques
      • Mask the input
      • use same embedding for all unseen words
    • What they choose
      • Keep more embedding space for unseen words
      • Hash them to get the bucket
    • Enough space is allocated for frequent words and they are not hashed
      • 10k or 100k of n-grams are kept
  • Combining tokenization
    • One approach
      • Separate embedding for unigram, biagram and character trigrams
      • Compute. weighted sum of cosine similarity individually
    • Their approach
      • Consider them as bag or words

Data

  • Time range
    • Training data – 11 month
    • Eval data – 1 month
  • Trick of aggregating count as weight
    • Weight while computing the loss, simple multiplication ( I had done that in synonyms as well )
    • 54 billion query product training pairs
    • Reduced to 650 million
  • Ratio
    • 1 purchased
    • 6 impressed
    • 7 random
    • They plan for both matching and ranking
    • Matching -> Differentiate between (purchased + impressed) from random
    • Ranking -> Differentiate between purchased and impressed
  • Query Preprocessing
    • Changes queries to list of token IDs
    • array length = 99 % tile of query token length
    • Smaller tokens are padded to right
  • Item preprocessing
    • One approach
      • Embed every attribute independently and concat
    • Their approach
      • Ordered Bag of words for title and attributes
      • Issue was variability in attributes and lack of structured data across items

Model Evaluations

Evaluation Metrics

  • Matching
    • Recall@100 and MAP
      • Used for tuning model hyper parameter as well
    • 20k queries and sub-corpus for those queries
      • Around 1M items
      • Ordered + Impressed + Random
  • Ranking
    • NDCG and MRR
    • Purchased + Impressed

Evaluation Results

  • Table 1
    • L2 variant of hinge loss outperforms L1
      • They hypothesise that L2 is more robust to outliers
    • 3 part hinge loss outperforms 2 part in matching but not in ranking
      • Introduction of 3rd part forced purchased and random to be more separated
  • Table 2
    • LSTM, GRU vs avg Pooling for aggregation
      • Comparison is made for various losses
      • Average pooling is performing similar or slightly better
        • Definitely reduces computation time
      • Since query and product title are relatively short this works well
      • Recurrent methods are expressive but introduces specialisation between query and title
        • Some may argue it is a good thing
        • They argue that it might not capture local word level mapping
  • Table 3
    • Compares different tokenization methods
    • Vocab sizes in embedding space
      • 125k – unigram
      • 25k – bigram
      • 64k – character trigram
      • 500k – Out of vocabulary (OOV) bins
    • Advantage of adding bigrams
      • Example – Chocolate milk vs milk chocolate
    • Advantage of character trigrams
      • Robustness to spelling error
    • OOV adds additional parameters
      • case 1 : 500k unigrams
      • case 2 : 125k unigrams and 375k OOV
      • case 2 performs better
  • Table 4
    • Batch vs layer vs no normalisation
    • query sorted data vs shuffled data
    • Optimum combination was using batch normalisation with shuffled data
    • Query sorted data did not have much effect on layer normalisation but was on batch normalisation
      • Batch estimates for mean and variant would be biased for batch normalisation
  • Table 5

Online evaluations

  • Three categories
    • toys and games, kitchen and pets
  • Conversion rate, revenue and other KPI increased with statistical significance
  • Challenges
    • Precision was decreased
    • To mitigate they added guardrails using some heuristic and ranking models to filter non relevant items
    • Not that recall@100 was metric for matching task and not precision.

Training Acceleration

  • Increasing query product pairs from 200 million to 1.2 billion had improved matching metric by 10 %
  • Data parallel training
    • Idea
      • Split data
      • Same model on multiple GPUs
      • Take the average of gradient in the end
    • Cons for this architecture
      • Limits embedding metric
        • It has to fit on single GPU
      • Data parallel approach has high communication overhead
        • We need to weight till forward pass from each GPU is available
  • Model parallel training
    • Pros in this architecture
      • Simplicity of average pooling
      • Siamese has some parallelism by default
    • How they implemented
      • Embedding metric is split across GPUs, across embedding dimension
        • Hence we need to concat to get final embedding vector for each token
          • Concatenation requires O(2k) communication of floating point numbers
        • Partial token embeddings are averaged at each GPUs
      • Full dataset is sent to all GPUs
  • In the result section they have told that embedding dimension was 256
  • Explaining above image
    • For low embedding dimension time-to-train increases with number of GPUs but for high embedding dimension time-to-train decreases with number of GPUs
    • Dotted line
      • Following two should have same training time
        • 2048 embedding with 1 GPU
        • 1024 embedding with 2 GPU
      • Doted line is for the ration of embedding_size/GPU
      • With ideal scaling it would be horizontal

Exampels

IR metrics

Information retrieval (IR) deals with fetching relevant documents given search query. Purpose of this blog is to list evaluation metric that can be used to measure performance of this system.

Metrics for unranked retrieval

For all these definition is same as that for classification. However they have some distinct characteristics for IR system.

Precision and Recall

  • Example of a system where precision is important
    • Web search
  • Example of a system where recall is important
    • Individual searching their hard disk

Accuracy

  • For IR system data is genrally very skewed. 99 % of the document are in non relvant category. Hence accuracy does not make sense.
  • However accuracy @ 1 is used in know item search query in email ( that would be ranked retrieval though )

F Measure

  • We can have F1 score, F2 score etc depending upon how much weight we want to precision and recall in harmonic mean.
  • As ß > 1, we start giving more weight to recall.

Metrics for ranked retrieval

Precision recall curves

  • Historically during classification we plot ROC by changing the threshold of binary classification. In case of IR we plot it by changing no of documents retrieved.

11 point interpolated average precision

  • For the recall values of (0,0.1,0.2,…,0.9,1.0) find out the precision and average it.

Mean Reciprocal Rank (MRR)

Measures how high the first relevant result appears

Mean Reciprocal Rank answers one question: how far down the list did the user have to look before hitting something relevant?

For a single query, the reciprocal rank is 1 / (position of the first relevant result). MRR is just the average of that across all queries.

  • We have multiple queries in test set for offline eval
  • The average will get us a single number to work with

MRR = (1 / |Q|) ∑i=1|Q| (1 / ranki)

Example — three queries, relevant doc marked with ✓:

QueryRanked resultsFirst hit atRR
q1d1, d2, d3✓30.333
q2d7✓, d4, d911.000
q3d5, d2✓, d820.500
  • MRR = (0.333 + 1.000 + 0.500) / 3 = 1.833 / 3 ≈ 0.611
  • Mean is across queries

If a query has no relevant result in the top-k, its RR is 0 (not undefined) — otherwise you’d be silently dropping your worst queries.

Two things worth keeping in mind about its shape: it only looks at the first relevant item, so a list with one hit at position 2 scores identically whether the other nine results are all relevant or all garbage. And the drop-off is steep — 1 → 0.5 → 0.33 — so it’s dominated by whether you nailed position 1 or 2. That makes it a good fit for known-item lookup and QA, and a poor fit when recall across a set matters.

Mean average precision (MAP)

  • Measures how early all relevant results appear across a ranked list
  • For a given query we calculate average precision. We take a mean of that for several queries.
    • there is no @k. It keep going down util all related items are taken
  • Example:
    • There are 10 documents, document 1,2,5 are revalant.
    • System 1 retrieves : 1,5,4,6,7,2
      • Average precision = (1/1 + 2/2 + 3/6)/3 = 8/9 = 0.83
    • System 2 retrieves : 1,2,5,3,4
      • Average precision = (1/1 + 2/2 + 3/3)/3 = 1
    • System 3 retrieves : 6,7,1,2,3,4,5
      • Average precision = (1/3 + 2/4 + 3/7)/3 = 0.42
  • MAP values typically varies a lot for different query in the same system. Say between 0.1 to 0.7
  • For different systems and same query MAP values does not vary that much. Hence for testing which system is better using MAP, large no of queries are needed.

Precision at k

  • MAP measure precision at various recall levels (until all the documents are retrieved). For application like web search what matters is result on first page or first three pages.
  • Disadvantages
    • Least stable and does not average well
    • Reason : total no of relevant document for a query has a strong influence on this metric.
  • R-precision
    • Different queries can have different number of relevant items ( call it R )
    • We set different k = R for each query
    • R is different for each query

R precision

  • Same as precision at k where k = no of relevant documents in a given query
  • It adjusts for the relevant document for a query (disadvantage of precision at k)
  • Empirically R-precision and MAP turn out be highly correlated.

NDCG

  • Normalized Discounted Cumulative Gain
  • Like precision at k it is evaluated at some values of k
  • It constitutes of cumulative gain at each position which is discount by position and is normalized
    • It is not max or sum normalized
    • It is normlized by ideal ndcg, which is calculated by sorting document based on relevance score. [3]
  • NDCG ranges between 0 to 1. For perfect ranking ideal value of NDCG is 1.
  • Example
    • positions : 1 2 3 4 5
    • eval score : 2 1 2 0 1
NDCG(q, k) = DCG(k)/Ideal DCG(k)

DCG(k) = sum (Gain(i) * Discount factor(i)) for i in (1,k)

Discount factor is generally taken as 1/log(1 + pos)

Gain is generally takes as (2^r - 1) where r is relevance score given by humans say 0 - not relevant ,1-near relevant , or 2-relevant.

Normalized Discounted Cumulative Gain (NDCG) becomes comparable across queries by dividing a query’s actual Discounted Cumulative Gain (DCG) by its Ideal DCG (IDCG), which scales every query’s maximum possible score to a uniform baseline of 1.0. [1, 2] 

Why Raw DCG Fails Across Queries

  • Varying relevance: Different queries have different numbers of relevant items or varying maximum possible scores.
  • Absolute scale distortion: A broad query with many highly relevant documents naturally produces a much higher raw DCG than a niche query with few results.
  • Incomparable totals: Comparing raw DCG across two different queries is like comparing percentages to raw point totals. 

When to use which examples

When to Use MRR

Use MRR when one good answer is enough or you only care about the top hit:

  • Chatbots and FAQ search: Users want a single quick answer.
  • Autocomplete and known-item lookup: You want the exact target item right at the top.
  • Factoid Q&A: A single factual passage satisfies the query.
  • Early-hit RAG checks: You want to know how fast the first useful chunk shows up.

When to Use MAP

Use MAP when multiple relevant items matter and you want them clustered near the top:

  • Multi-chunk RAG retrieval: The answer needs several supporting passages before context limits or rerankers cut the list.
  • E-commerce and product search: Users browse multiple matching products on the first page.
  • Code search and bug localization: Multiple files or functions may be relevant to a fix.
  • Document and corpus search: You want high precision across every relevant item retrieved.

Key Limitations

  • MRR ignores everything after the first relevant result.
  • MAP still treats relevance as binary, so it cannot tell a “somewhat relevant” item from an “ideal” one. Switch to NDCG when relevance is graded (such as a 0–3 scale).

References

[0] Christopher D. Manning, Prabhakar Raghavan and Hinrich Schütze, Introduction to Information Retrieval, Cambridge University Press. 2008.

[1] https://towardsdatascience.com/breaking-down-mean-average-precision-map-ae462f623a52

[2] https://blog.thedigitalgroup.com/measuring-search-relevance-using-ndcg

[3] https://www.geeksforgeeks.org/normalized-discounted-cumulative-gain-multilabel-ranking-metrics-ml/