18Ranking metrics and position bias (NumPy)
18 Ranking metrics and position bias (NumPy)
An Airbnb MLE loop from April 2026 (reported that August) had ML design with embeddings and two-stage retrieval and ranking, and the interviewer pushed hard on position bias (2 reports). A prep site lists a Netflix data science question on planning a ranking A/B test (nfx-058, guide only). These are the numbers you'd use to judge a ranker.
Set a 50-minute timer. Read one level at a time, and run only that level's tests until they pass:
pytest problems/18_ranking_metrics -k level1. Earlier levels must keep passing.
Level 1. Write in solution.py:
dcg_at_k(rels, k): discounted cumulative gain of a ranked list of graded relevances, with the exponential gain(2^rel - 1)and the discountlog2(position + 1), positions counted from 1.ndcg_at_k(rels, k): DCG divided by the DCG of the best possible ordering of the same items. A list with no relevant items scores 0.- The best ordering sorts every item in
rels, not only the topk, then takes its topk. Akbigger than the list uses the whole list. Both functions return a float.
Level 2. ips_relevance(clicks, positions, propensity): from a click log where each impression
was shown at some position, estimate each item's click rate as if every impression had been at the
top. propensity[p] is the chance a user even looks at position p (positions from 0). clicks and
positions are arrays per impression. Return the inverse-propensity-weighted mean of clicks: the sum of click / propensity[position] over
every impression, divided by the number of impressions (not by the sum of the weights). One click at
a low position can push the estimate above 1. Be ready
to say why raw click-through rate punishes items that were shown low.
Level 3. Where the propensities come from. A small slice of traffic shuffled the top n results,
so every position got the same mix of items. propensities_from_shuffle(clicks, positions, n) returns
an array of n numbers: each position's click rate (clicks over impressions at that position) divided
by the click rate at position 0. Every position from 0 to n - 1 has impressions. Position 0 always
comes out 1.0, even when thin data gives a lower position a higher rate.
Level 4. Thin data. Add a parameter, ips_relevance(clicks, positions, propensity, tau=0.0), that
divides each click by max(propensity, tau) instead of its propensity, so no weight is bigger than
1 / tau. With the default, nothing changes. At tau = 1, it's the raw click rate.
Follow-ups: the variance of IPS when propensities are small, how you'd pick tau, and offline NDCG
against online metrics.