Recommendation, Ranking, and Personalization Questions
Systems that select and order items for users. Covers candidate generation and ranking (two-stage retrieval, embedding-based retrieval with two-tower models and approximate nearest-neighbour candidate lookup, multi-stage scoring and cross-encoder re-ranking), collaborative and content-based filtering, matrix factorization (alternating least squares, Bayesian personalized ranking), sequence-aware and graph-based recommenders, cold start, learning-to-rank and negative sampling, turning noisy implicit feedback into labels, position, exposure and popularity bias and feedback loops, diversity, fairness-aware exposure and multi-objective re-ranking, counterfactual (off-policy) evaluation of recommenders (inverse propensity scoring, doubly robust estimators), and exploration with multi-armed and contextual bandits (epsilon-greedy, upper-confidence-bound and Thompson sampling, LinUCB, regret, non-stationarity, constraints, rollout, and when a bandit beats a fixed split or full reinforcement learning). Includes end-to-end recommender and personalized feed design. Focuses on the modeling and evaluation patterns specific to recommendation and ranking at scale. General A/B test design, generic ranking-metric definitions and ML serving infrastructure are covered elsewhere.
How do you choose the embedding dimension for users and items? Discuss the trade-offs and the empirical process and diagnostics you would use.
Sample Answer
The idea in plain words
An embedding is a vector of d numbers that represents a user or an item, and the model scores a pair by their dot product. The dimension d is the model's capacity: with d numbers per row the model can represent at most d independent taste directions (the score matrix it produces has rank at most d; rank is the number of independent directions in a matrix). Too small and it cannot separate genuinely different tastes. Too large and it memorises noise unless regularisation (a penalty on vector size) is strong, while memory and scoring cost grow in proportion to d. So you pick the smallest d on the plateau of the validation curve, checked against the metric you ship and the cost you can pay.
A hand-sized example with d=2: a user vector (1.0,0.5) and two item vectors (2.0,−1.0) and (0.5,1.0) give scores 1.0⋅2.0+0.5⋅(−1.0)=1.50 and 1.0⋅0.5+0.5⋅1.0=1.00 (the program prints both), so this user is shown item A first. With d=1 every user and item would be one number, so the model has a single taste axis: a user with a positive number likes the items high on the axis and a user with a negative number likes the low ones. It cannot hold two independent tastes at once, for example a user who likes both action films and cooking shows. With d=2 each user can sit anywhere on two axes.
What changes with d
- Quality: validation error falls while d is below the number of real taste directions, then flattens (with good regularisation) or rises (without it).
- Memory: the tables hold (users + items) x d floats.
- Scoring cost: one dot product costs d multiply-adds, and an approximate nearest-neighbour index (ANN: a structure that finds close vectors without comparing against all of them) gets slower and larger with d.
- Rows with few interactions get noisy vectors at any d, so a single large d is wasted on the tail.
Empirical process
- Start from a log-spaced grid (1, 2, 4, 8, 16, 32...). Each grid point is a full training run, so powers of two cover the range cheaply.
- Re-tune the regularisation strength for every d. Comparing dimensions at one fixed penalty confuses capacity with regularisation.
- Score on a held-out split by time, using the ranking metric you ship (recall@k or NDCG, not only error on ratings).
- Take the smallest d within noise of the best (for example within one standard error across seeds: the spread of the metric over repeated runs with different random seeds, divided by the square root of the number of runs).
- Then check the diagnostics below and the cost.
The program fits matrix factorisation by alternating least squares (fix the item vectors and solve a small ridge regression for each user, that is, least squares with a penalty on the squared size of the solution, then swap) on a synthetic rating matrix whose real structure has rank 8 plus noise with standard deviation 0.5, so 0.50 is the lowest validation error any model could reach. It compares a weak penalty (0.1) with a stronger one (5) and prints the memory arithmetic for 50 million users and 5 million items.
import numpy as np
# A score is a dot product. Tiny example with d = 2: one user vector, two item vectors.
user = np.array([1.0, 0.5])
for name, v in {"item A": np.array([2.0, -1.0]), "item B": np.array([0.5, 1.0])}.items():
print(f"{name}: {user[0]} x {v[0]} + {user[1]} x {v[1]} = {user @ v:.2f}")
print()
def make(seed, n_users=300, n_items=200, true_rank=8, noise=0.5, dens=0.15):
rng = np.random.default_rng(seed)
P = rng.normal(size=(n_users, true_rank))
Q = rng.normal(size=(n_items, true_rank))
R = P @ Q.T / np.sqrt(true_rank) + noise * rng.normal(size=(n_users, n_items))
u = rng.random((n_users, n_items))
return R, u < dens, (u >= dens) & (u < dens + 0.05) # ratings, train mask, validation mask
def als(R, train, d, lam, iters=12, seed=0):
"""Alternating least squares: solve a ridge problem for each user, then for each item."""
rng = np.random.default_rng(seed)
n_u, n_i = R.shape
P = 0.1 * rng.normal(size=(n_u, d))
Q = 0.1 * rng.normal(size=(n_i, d))
for _ in range(iters):
for u in range(n_u):
j = train[u]
P[u] = np.linalg.solve(Q[j].T @ Q[j] + lam * np.eye(d), Q[j].T @ R[u, j])
for i in range(n_i):
j = train[:, i]
Q[i] = np.linalg.solve(P[j].T @ P[j] + lam * np.eye(d), P[j].T @ R[j, i])
return P, Q
def rmse(R, mask, P, Q):
return float(np.sqrt(np.mean((R[mask] - (P @ Q.T)[mask]) ** 2)))
dims = (1, 2, 4, 8, 16, 32)
print("mean over 3 seeds; ratings = rank-8 signal + noise with std 0.5, so 0.50 is the best possible validation RMSE")
print(" d train(lam=0.1) val(lam=0.1) train(lam=5) val(lam=5)")
for d in dims:
row = []
for lam in (0.1, 5.0):
tr, va = [], []
for seed in range(3):
R, train, val = make(seed)
P, Q = als(R, train, d, lam)
tr.append(rmse(R, train, P, Q)); va.append(rmse(R, val, P, Q))
row += [np.mean(tr), np.mean(va)]
print(f"{d:2d} {row[0]:13.3f} {row[1]:12.3f} {row[2]:12.3f} {row[3]:10.3f}")
print("\nembedding table memory in float32 (GB), 50M users + 5M items")
for d in (32, 64, 128, 256):
print(f"d={d:3d}: {(50e6 + 5e6) * d * 4 / 1e9:6.1f} GB")
print("\nvalidation RMSE at d=8, penalty 5, as more of the rating matrix is observed (mean over 3 seeds)")
for dens in (0.15, 0.30, 0.60):
va = []
for seed in range(3):
R, train, val = make(seed, dens=dens)
P, Q = als(R, train, 8, 5.0)
va.append(rmse(R, val, P, Q))
print(f"observed share {dens:.2f} ({int(300 * 200 * dens):>5,} ratings): validation RMSE {np.mean(va):.3f}")
It prints:
item A: 1.0 x 2.0 + 0.5 x -1.0 = 1.50
item B: 1.0 x 0.5 + 0.5 x 1.0 = 1.00
mean over 3 seeds; ratings = rank-8 signal + noise with std 0.5, so 0.50 is the best possible validation RMSE
d train(lam=0.1) val(lam=0.1) train(lam=5) val(lam=5)
1 1.003 1.081 1.013 1.061
2 0.905 1.062 0.922 1.015
4 0.712 0.984 0.765 0.924
8 0.412 0.912 0.546 0.747
16 0.189 1.617 0.510 0.786
32 0.020 1.319 0.497 0.797
embedding table memory in float32 (GB), 50M users + 5M items
d= 32: 7.0 GB
d= 64: 14.1 GB
d=128: 28.2 GB
d=256: 56.3 GB
validation RMSE at d=8, penalty 5, as more of the rating matrix is observed (mean over 3 seeds)
observed share 0.15 (9,000 ratings): validation RMSE 0.747
observed share 0.30 (18,000 ratings): validation RMSE 0.596
observed share 0.60 (36,000 ratings): validation RMSE 0.533
Reading it: with the weak penalty, training error keeps falling (0.020 at d=32) while validation error explodes (1.617 at d=16, 1.319 at d=32). With the stronger penalty the curve bottoms at d=8 (0.747), the true rank, and the larger sizes stay close (0.786 at 16, 0.797 at 32) instead of blowing up. Two things in the table need explaining. First, the weak-penalty validation error is not monotone (1.617 at d=16, then 1.319 at d=32). The training set has only 9,000 observed ratings, while the model has (300+200)d numbers to fit: 8,000 at d=16, close to the number of ratings, so it can nearly memorise them and the unpenalised solution is at its wildest, and 16,000 at d=32, where there is more freedom than data and the fit settles into a different, less extreme solution. A peak near the point where parameters match observations is a known pattern in nearly unregularised models, and its exact height depends on the seeds and on the 12 update rounds, so read it as "large d with a weak penalty is far worse than d=8", not as a rule that 32 beats 16. Second, the best validation error (0.747) is well above the 0.50 floor because the floor assumes every vector is known exactly, while here each user has only about 30 observed ratings (15% of 200 items) to fix 8 numbers. The last block of the output shows the gap closing as more ratings are observed: 0.747 with 9,000 ratings, 0.596 with 18,000, 0.533 with 36,000.
The clean notch at 8 comes from the synthetic generator; real data has no exact rank, so expect a plateau and choose its left edge. The table also shows that the cost side is linear: 7.0 GB at d=32 becomes 14.1 GB at 64.
Diagnostics beyond the headline metric
- Train versus validation gap by d: a widening gap at a fixed penalty means the model is memorising.
- The metric split by head and tail users and items (head: the popular ones with many interactions; tail: the rare ones with few): a larger d can help popular rows and hurt rare ones.
- Singular values of the learned item matrix (a decomposition of the matrix into directions, each with a size; the squared size is its "energy", its share of the matrix's total variation): if the trailing dimensions carry almost no energy, they are unused.
- Recall of the ANN index against exact search at the chosen d, measured rather than assumed.
- Latency and memory at the target scale, from the arithmetic above.
Decision
For a first production model, pick the left edge of the plateau (8 in this toy, where the notch is exact) and then round up to the next size your serving stack handles efficiently, since vector libraries and hardware often work best on multiples of 8 or 16. Real catalogues have no exact rank, so their plateau tends to begin much higher, at a few dozen, and 64 is a typical landing point; the memory table above prices that choice: 14.1 GB at 64 against 7.0 GB at 32. Move to a larger d only if a tail-segment metric or a new feature input (content features, many interaction types) shows a measured gain that pays for the extra memory. If the tables dominate memory, reduce the dimension of the tail rows or hash them (map many rare ids onto a smaller shared table of rows), rather than shrinking every row.
Common mistakes
- Picking d by training loss.
- Sweeping d with a fixed penalty and concluding that bigger always overfits.
- Reporting error on ratings when the product ranks items.
Running the code
No installation beyond Python 3.12 with numpy. The listing is a complete program with fixed seeds; run it with python and it prints the output shown.
How are negatives chosen when training a large recommendation model from implicit feedback? Compare the main strategies by the bias they introduce, efficiency and implementation cost.
Sample Answer
The idea in plain words
With implicit feedback (clicks, plays, purchases rather than star ratings) you only observe positives: the user did interact with this item. There is no "the user disliked this" row. To train a model that scores items, you must manufacture negatives by picking items the user did NOT interact with and treating them as "less preferred". An unobserved item is not a confirmed dislike: the user may never have seen it, or may have liked it. How you pick negatives therefore decides what the model learns, and every strategy trades three things: bias (what wrong lesson it teaches), efficiency (compute per training step) and implementation cost.
A few terms the rest relies on. The catalogue is the full set of items that can be recommended. A logit is the model's raw score for an item (any real number). Softmax turns a list of logits into probabilities that sum to 1: each item's probability is ezj divided by the sum of ez over all items, so training pushes the clicked item's probability up and every other item's down. Scoring every item in that sum (the "full softmax") costs work proportional to the catalogue size per example. A sampled softmax sums over only k sampled negatives plus the positive instead, which cuts the work to k+1 scores per example. A mini-batch is the group of training examples processed in one step. Zipf-like popularity means a few items get most interactions and a long tail gets very few. Popularity bias is a model's tendency to over-recommend items that are already popular.
The main strategies
| Strategy | How negatives are drawn | Bias it introduces | Efficiency | Implementation cost |
|---|---|---|---|---|
| Uniform random | Any item not interacted with, equal chance | Mostly easy negatives, so the model learns coarse separation. Popular items almost never appear as negatives, so popularity is rewarded and popularity bias is amplified | Cheap | Lowest |
| Popularity-proportional (or popularity raised to a power below 1) | Drawn in proportion to interaction counts, or counts to an exponent such as 0.75 | Popular items are pushed down more, which can under-recommend them. A flatter exponent softens that | Cheap | Low (a precomputed table) |
| In-batch negatives | Other users' positives in the same mini-batch act as negatives | Equivalent to popularity-proportional sampling, so popular items are over-penalized unless corrected | Almost free: the scores already exist | Low, plus the correction below |
| Hard negatives (model-mined) | Items the current model scores high that the user did not interact with | More false negatives (unseen but liked), and risk of training collapse (the model gets stuck on a poor solution, for example mapping many items to nearly the same vector) if used alone | Needs an approximate nearest-neighbour index (a structure that finds high-scoring items quickly without scoring all of them) refreshed during training | Highest |
| Exposure-based negatives (also called impression-based) | Items that were SHOWN (impression) but not clicked | Fewer false negatives, but only items the old system showed, which carries its selection bias | Cheap given impression logs | Needs reliable impression logging |
Popularity correction for in-batch sampling (logQ)
If item j shows up as a negative with probability qj, a sampled softmax over-counts popular items. The reason is that the softmax denominator is meant to be a sum over the whole catalogue, ∑jezj. A sample can estimate that sum without bias only if each drawn item is divided by its probability of being drawn: E[ezj/qj]=∑jqj⋅ezj/qj=∑jezj. Writing ezj/qj as ezj−logqj gives exactly the correction below. The same correction is normally applied to every logit in the sampled softmax, including the positive item's own, because in-batch positives are drawn from the same popularity distribution. The standard correction subtracts the log sampling probability from each logit:
z~j=zj−logqjwhere zj is the model's score for item j. Intuition: a popular item is drawn all the time, so each draw should count less; a rare item is drawn almost never, so when it does appear it must stand in for all the draws of it that did not happen. The program below checks this on 2,000 items. With 1,000 draws per batch the most popular item is expected about 122 times and the rarest about 0.06 times. Dividing each draw by its probability recovers the true denominator, and ignoring the unevenness overshoots it several-fold.
import numpy as np
rng = np.random.default_rng(0)
N, B = 2000, 1000
pop = 1.0 / np.arange(1, N + 1); q = pop / pop.sum() # Zipf-like: item 0 is drawn most often
z = 0.5 * np.log(q * N) + rng.normal(0, 0.5, N) # model scores (logits), a bit higher for popular items
D = np.exp(z).sum() # the full-softmax denominator: score every item once
print("expected draws of each item in a batch of 1000:", {i: round(float(B * q[i]), 2) for i in (0, 9, 99, 1999)})
naive, fixed = [], []
for _ in range(300):
j = rng.choice(N, size=B, p=q)
naive.append(N * np.exp(z[j]).mean()) # treat the draws as if they were uniform
fixed.append(np.exp(z[j] - np.log(q[j])).mean()) # each draw counts 1/q: the logQ correction
print(f"true denominator {D:.1f}")
print(f"uncorrected estimate: mean {np.mean(naive):.1f}, relative error {np.mean(naive) / D - 1:+.1%}")
print(f"logQ-corrected estimate: mean {np.mean(fixed):.1f}, relative error {np.mean(fixed) / D - 1:+.1%}")
# one draw of the rarest item in a batch of 1000, versus a batch of 4
print("weight 1/q of item 1999:", round(float(1 / q[1999])), "(one draw of it stands in for the roughly 16,000 draws it would take to meet it once on average)")
sm = lambda v: np.exp(v - v.max()) / np.exp(v - v.max()).sum()
batch = np.array([0, 1, 2, 1999])
print("share of the corrected softmax held by the rare item in a batch of 4:", round(float(sm(z[batch] - np.log(q[batch]))[3]), 3))
big = np.concatenate([rng.choice(N, size=999, p=q), [1999]])
print("same rare item in a batch of 1000 draws:", round(float(sm(z[big] - np.log(q[big]))[-1]), 4))
Output:
expected draws of each item in a batch of 1000: {0: 122.27, 9: 12.23, 99: 1.22, 1999: 0.06}
true denominator 1534.9
uncorrected estimate: mean 10576.3, relative error +589.1%
logQ-corrected estimate: mean 1526.1, relative error -0.6%
weight 1/q of item 1999: 16357 (one draw of it stands in for the roughly 16,000 draws it would take to meet it once on average)
share of the corrected softmax held by the rare item in a batch of 4: 0.918
same rare item in a batch of 1000 draws: 0.0046
Reading it: the true denominator is 1534.9. The uncorrected estimate averages 10576.3 (589 percent too high), because popular items are drawn so often; the corrected estimate averages 1526.1, within 1 percent. The last two lines show the price: a single rare item carries weight 1/q=16357, so in a tiny batch of 4 it takes 92 percent of the corrected softmax, but in a batch of 1000 draws the same item holds under 0.5 percent. Large batches therefore tame the correction, and a real implementation also watches for single items that dominate the softmax.
Worked example 1: what each distribution samples and how often it picks something the user would have liked
A simulation: 2,000 items with Zipf-like popularity, 300 users, 10 negatives each. Whether a user would like an item rises with popularity plus individual taste; exposure is limited, so some liked items were never seen and are not recorded as positives. A false negative is a sampled negative that the user would actually have liked. The "hard" row takes each user's 10 highest-scoring non-positives under a noisy copy of the true preference (a stand-in for a trained model). Below it, the logQ correction on four logits.
import numpy as np
rng = np.random.default_rng(0)
N_ITEMS, N_USERS = 2000, 300
pop = 1.0 / np.arange(1, N_ITEMS + 1) # Zipf popularity, item 0 is the most popular
pop /= pop.sum()
fn = {"uniform": 0.0, "popularity^0.75": 0.0, "popularity^1.0 (in-batch)": 0.0, "hard (top model scores)": 0.0}
hit_rate = {k: 0.0 for k in fn}
head_mass = {}
for name, a in [("uniform", 0.0), ("popularity^0.75", 0.75), ("popularity^1.0 (in-batch)", 1.0)]:
q = pop ** a
q /= q.sum()
head_mass[name] = q[:20].sum() # probability a negative is one of the 20 most popular items
K = 10
for u in range(N_USERS):
affinity = rng.normal(size=N_ITEMS) + 1.0 * np.log(pop * N_ITEMS) # liking rises with popularity (a real effect)
likes = rng.random(N_ITEMS) < 1 / (1 + np.exp(-2 * (affinity - 1.5))) # items the user would actually like
seen = rng.random(N_ITEMS) < np.minimum(1.0, pop * N_ITEMS * 0.25) # items exposed to the user
observed_pos = likes & seen # only exposed + liked items appear as positives
cand = np.where(~observed_pos)[0] # sampled negatives must not be observed positives
for name, a in [("uniform", 0.0), ("popularity^0.75", 0.75), ("popularity^1.0 (in-batch)", 1.0)]:
q = pop[cand] ** a
q /= q.sum()
neg = rng.choice(cand, size=K, p=q)
fn[name] += likes[neg].mean() # false negative: the user would have liked it
model_score = affinity + rng.normal(0, 1.0, N_ITEMS)
top = cand[np.argsort(-model_score[cand])[:K]]
fn["hard (top model scores)"] += likes[top].mean()
print(f"{'strategy':28s} {'P(negative in top-20 popular)':>30s} {'false-negative rate':>20s}")
for name in fn:
hm = f"{head_mass[name]:.3f}" if name in head_mass else "n/a"
print(f"{name:28s} {hm:>30s} {fn[name] / N_USERS:20.3f}")
# logQ correction: subtract log(sampling probability) from every logit in the sampled softmax
logits = np.array([2.0, 1.5, 1.2, 1.0]) # [positive, popular negative, popular negative, rare negative]
q = np.array([0.01, 0.05, 0.04, 0.0005]) # probability each item is drawn as an in-batch negative
sm = lambda z: np.exp(z - z.max()) / np.exp(z - z.max()).sum()
for label, z in [("no correction", logits), ("logQ correction", logits - np.log(q))]:
p = sm(z)
print(f"{label:16s} softmax {np.round(p, 3)} positive-loss {-np.log(p[0]):.3f}")
Output:
strategy P(negative in top-20 popular) false-negative rate
uniform 0.010 0.036
popularity^0.75 0.218 0.049
popularity^1.0 (in-batch) 0.440 0.058
hard (top model scores) n/a 0.387
no correction softmax [0.413 0.25 0.185 0.152] positive-loss 0.885
logQ correction softmax [0.116 0.014 0.013 0.856] positive-loss 2.151
Reading it:
- Uniform sampling puts 1.0% of its negatives on the 20 most popular items; popularity to the power 0.75 puts 21.8%; full popularity proportionality (the in-batch case) puts 44.0%. This is the popularity pressure each strategy applies.
- False-negative rates are 3.6%, 4.9% and 5.8% for uniform, power-0.75 and in-batch. Model-mined hard negatives reach 38.7%: the items a good model likes most among the unobserved are very often items the user would have liked. This is why hard negatives are mixed with easier ones and down-weighted rather than used alone.
- With the logQ correction, the popular negatives (sampling probabilities 0.05 and 0.04) lose probability mass in the softmax (0.250 and 0.185 become 0.014 and 0.013), and the rare negative (0.0005) goes from 0.152 to 0.856. The positive-item loss rises from 0.885 to 2.151, which is expected and not a sign of damage. The correction adds −logq to every logit: about 4.6 to the positive (q=0.01), 3.0 and 3.2 to the two popular negatives, and 7.6 to the rare one, whose logit therefore jumps from 1.0 to 8.6 and overtakes the positive's 6.6. That one rare negative is what raises the loss. The loss values are not comparable between the two settings, and the training signal changes: the popular negatives are pushed down much less (their probability falls from 0.250 and 0.185 to about 0.01), so the model no longer learns "popular means bad".
- How to read the 85.6 percent on the rare negative: it comes from this toy having only three negatives. Its sampling probability of 0.0005 means its weight is 2,000, so one draw of it must stand for a large part of the catalogue. In a real batch of hundreds or thousands of draws, a healthy corrected softmax spreads the mass over many items and no single rare item holds most of it; a rare item taking most of the mass is a warning sign of too small a batch, a very noisy q estimate, or an uncapped correction.
One application: popularity and exposure bias in negatives for a restaurant ranker
This section applies the strategies above to one concrete product; skip it if the general case is all you need.
A ranker trained on click and order logs has two traps. First, restaurants the app showed prominently dominate the positives, and sampling negatives by popularity then teaches the model that popular restaurants are bad. Use a power below 1 or logQ correction, and mix uniform. Second, a negative must be one the user could actually have ordered: sample from restaurants that deliver to that user's address and are open at that time, otherwise the negatives are trivially easy (a restaurant in another city) and the model learns nothing about preference. Impression-based negatives (shown, not clicked, not ordered) are the cleanest, and orders should count above clicks as positives.
Recommendation
For a large model trained from implicit feedback: use in-batch negatives with logQ correction as the default (cheap and corrected), add a small share of uniform negatives for items the batch never contains, and add a limited share of hard negatives later in training once the model has learned coarse structure, at a lower loss weight. Switch to exposure-based negatives if impression logs are reliable. What would flip this: if popularity bias in the results is the main complaint, move toward a flatter exponent and stronger correction; if training is unstable after hard negatives are added, lower their share.
Common mistakes
- Treating every unobserved item as a confirmed negative, then mining the hardest ones.
- Using in-batch negatives without correction on a catalogue with a strong head.
- Sampling negatives from the whole catalogue rather than the items the user was eligible to see.
How would you model recommendations that respect both global patterns and local preferences across regions? Cover features and model structure, and how you would diagnose a recommender that underperforms in a newly launched market.
Sample Answer
Direct answer
Model the score as a global part shared by every region plus a regional deviation that is shrunk toward zero. Mature regions with lots of data can move far from the global behaviour; a new region with little data stays close to it until its own evidence accumulates. Statisticians call this partial pooling: not one model for everyone (full pooling) and not one model per region (no pooling), but regions that borrow from the shared model in proportion to how little data they have. In practice that is a shared model with region-aware features and a small set of region-specific parameters (a region embedding, a region bias, or region-crossed features: each feature copied once per region, with the copy active only for that region's rows) under a stronger regularization penalty. When a newly launched market underperforms, diagnose in a fixed order: is the evaluation itself valid for that market, does the catalog and training data cover what the market asks for, which features shifted, and only then is the model structure at fault.
Model structure
- Global component. Item, user and context features, plus embeddings trained on all regions together. This carries what is universal: relevance of a match between a user's recent behaviour and an item.
- Local component. Features that are region-specific by nature: language and script match, local popularity and trending items, currency-normalized price, local holidays and time of day, local catalog availability and delivery constraints. Add the region id itself as a feature or embedding so the model can adjust the weighting.
- Hierarchical shrinkage (regional weights are pulled back toward the shared ones, like a rubber band whose stiffness you set). Let wr be the weights for region r, with wr=wg+δr where wg are the global weights and δr is the regional deviation. Train with a penalty on the deviation:
Here Dr is the training data from region r, ℓ is the logistic loss (the penalty for assigning a low probability to what actually happened), and λδ controls how strongly regions are pulled toward the global model. A larger λδ suits regions with little data. In a neural ranker the same idea appears as a shared trunk with small region-specific layers, or a mixture of experts gated by region (several small sub-networks plus a gate that decides, here from the region, how much each one contributes).
With numbers: take three features, global weights wg=(0.8,−0.4,0.2) and a new-market deviation δ=(0.3,0.1,−0.2), so the new market's weights are wg+δ=(1.1,−0.3,0.0). For an example x=(1,2,1) the click probability is 0.550 under the global weights and 0.622 with the regional deviation (computed in the program after the output). The penalty makes δ expensive, so with little data it stays near zero and the regional weights stay near wg.
Worked experiment
Stand-in: synthetic click data with 30 features per example. Each region's true weights are the global weights plus a small regional difference. Two mature regions have 2,000 training rows each. The new market has 50, 500 or 5,000 rows, and the test set is 3,000 new-market rows. The region-crossed design copies each feature once per region; its columns are multiplied by scale. Why a smaller scale means a stronger pull toward the global weights: a column x⋅s with fitted coefficient c adds s⋅c to that region's weight, so a deviation δ needs c=δ/s, and the optimizer's L2 penalty is charged on c, that is on δ2/s2. At scale 0.3 a given deviation costs 1/0.32≈11 times as much as at scale 1.0. In the notation of the formula above, scikit-learn's LogisticRegression(C=1.0) charges 21 per squared coefficient (it minimises 21∥w∥2+C⋅ the summed logistic loss), so λg≈0.5 on the global block and λδ=0.5/scale2, which is about 5.6 at scale 0.3 and 0.5 at scale 1.0. Metric: area under the ROC curve (AUC: the probability that a random clicked example is scored above a random unclicked one), mean over 6 seeds. The last line is a coverage check from an assumed catalog setup stated in the comments; the 40% there is an input to the simulation, so the printed 0.404 only shows the check's arithmetic working, not evidence about any real market (in production the same two lines run on real request logs and real training item ids, and the answer is a measurement).
import os
os.environ["OMP_NUM_THREADS"] = "1" # keep the linear algebra single-threaded
os.environ["OPENBLAS_NUM_THREADS"] = "1"
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
F = 30 # item-user match features
REGIONS = 3 # region 0 and 1 are mature markets, region 2 is the new market
def make(rng, n, region, w_global, w_local, n_items=200):
X = rng.normal(size=(n, F))
item = rng.integers(0, n_items, size=n)
logit = X @ (w_global + w_local[region]) - 0.5
y = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
return X, y, item
def design(X, region, scale):
# columns: global block, then one block per region scaled by `scale` (smaller scale = stronger shrinkage)
cols = [X] + [X * (region == r)[:, None] * scale for r in range(REGIONS)]
return np.hstack(cols)
def trial(seed, n_new):
rng = np.random.default_rng(seed)
w_global = rng.normal(scale=0.5, size=F)
w_local = rng.normal(scale=0.3, size=(REGIONS, F))
sets = []
for r, n in ((0, 2000), (1, 2000), (2, n_new)):
X, y, item = make(rng, n, r, w_global, w_local)
sets.append((X, y, np.full(n, r), item))
Xtr = np.vstack([s[0] for s in sets]); ytr = np.concatenate([s[1] for s in sets])
rtr = np.concatenate([s[2] for s in sets])
Xte, yte, ite = make(rng, 3000, 2, w_global, w_local)
rte = np.full(3000, 2)
out = {}
# global only: ignore region
m = LogisticRegression(C=1.0, max_iter=500).fit(Xtr, ytr)
out["global only"] = roc_auc_score(yte, m.decision_function(Xte))
# new-market data only
m = LogisticRegression(C=1.0, max_iter=500).fit(Xtr[rtr == 2], ytr[rtr == 2])
out["new market only"] = roc_auc_score(yte, m.decision_function(Xte))
# global + region deviations, deviations shrunk (scale 0.3 means a stronger pull toward the global weights)
for scale in (0.3, 1.0):
m = LogisticRegression(C=1.0, max_iter=500).fit(design(Xtr, rtr, scale), ytr)
out[f"global + region (scale {scale})"] = roc_auc_score(yte, m.decision_function(design(Xte, rte, scale)))
return out
print("AUC on new-market test set, mean over 6 seeds")
for n_new in (50, 500, 5000):
res = [trial(s, n_new) for s in range(6)]
print(f"new-market training rows: {n_new}")
for k in res[0]:
print(f" {k:32s} {np.mean([r[k] for r in res]):.3f}")
shrunk_wins = sum(r["global + region (scale 0.3)"] > r["global only"] for r in res)
local_wins = sum(r["new market only"] > r["global only"] for r in res)
print(f" seeds where shrunk beats global only: {shrunk_wins} of {len(res)}; where new market only beats global only: {local_wins} of {len(res)}")
# Diagnosis check for an under-performing new market (assumed setup: 2000-item catalog;
# mature markets logged exposure for items 0..1199; 40% of new-market requests go to local items 1200..1999)
rng = np.random.default_rng(1)
local = rng.random(5000) < 0.4
requested = np.where(local, rng.integers(1200, 2000, size=5000), rng.integers(0, 1200, size=5000))
print("share of new-market requests for items with no training history:", round(float(np.mean(requested >= 1200)), 3))
Output:
AUC on new-market test set, mean over 6 seeds
new-market training rows: 50
global only 0.811
new market only 0.742
global + region (scale 0.3) 0.833
global + region (scale 1.0) 0.777
seeds where shrunk beats global only: 5 of 6; where new market only beats global only: 1 of 6
new-market training rows: 500
global only 0.824
new market only 0.896
global + region (scale 0.3) 0.897
global + region (scale 1.0) 0.896
seeds where shrunk beats global only: 6 of 6; where new market only beats global only: 6 of 6
new-market training rows: 5000
global only 0.888
new market only 0.909
global + region (scale 0.3) 0.909
global + region (scale 1.0) 0.909
seeds where shrunk beats global only: 6 of 6; where new market only beats global only: 6 of 6
share of new-market requests for items with no training history: 0.404
Reading it:
- With 50 new-market rows, the global-only model averages 0.811 and the model trained on those rows alone averages 0.742. Their order is not stable: 50 rows are too few to learn 30 local weights reliably, and the local-only model beats global-only in 1 of the 6 seeds. The shrunk hierarchical model averages 0.833 and beats global-only in 5 of 6 seeds. The weak-shrinkage hierarchical model (
scale1.0) averages 0.777, between the two averages, because it is free to overfit the 50 rows. - With 500 rows the local data are enough: the hierarchical and local-only models both reach about 0.896 to 0.897 while global-only stays at 0.824.
- With 5,000 rows all local-aware options are equal at 0.909 and the global-only model is at 0.888 (it also sees these rows). The shrinkage matters in the window where the new market has some data but not enough.
The pattern is the standard one for partial pooling; the exact AUC values belong to this synthetic setup.
Two further numbers back up the reading, from a small extra program (below): with only 50 new-market rows, the fitted size of the new market's deviation ∥δ∥ (the root of the sum of squared entries) averages 0.693 at scale 0.3 and 2.084 at scale 1.0, against a true size of 1.516 in these synthetic markets. Strong shrinkage under-fits the deviation (to less than half its true size) and weak shrinkage over-fits it (to about one and a third times its true size); at 50 rows the under-fit costs less AUC than the over-fit, which is the same story as the AUC table.
import numpy as np
from sklearn.linear_model import LogisticRegression
# 1. w_r = w_g + delta_r on three features, with real numbers.
w_g = np.array([0.8, -0.4, 0.2])
delta_new = np.array([0.3, 0.1, -0.2])
w_new = w_g + delta_new
x = np.array([1.0, 2.0, 1.0])
sigmoid = lambda z: 1 / (1 + np.exp(-z))
print("new-market weights w_g + delta =", w_new)
print(f"click probability with the global weights only: {sigmoid(x @ w_g):.3f}; with the regional deviation: {sigmoid(x @ w_new):.3f}")
# 2. Why a smaller `scale` means a stronger pull toward the global weights.
# A scaled column x*s with fitted coefficient c contributes delta = s*c to the weight, and the penalty is on c = delta/s.
for s in (1.0, 0.3):
print(f"scale {s}: a deviation of delta = 0.3 needs coefficient c = {0.3 / s:.2f} and pays penalty weight on c^2 = {(0.3 / s) ** 2:.2f} (vs {0.3 ** 2:.2f} at scale 1.0)")
# 3. Measured: size of the fitted regional deviation of the new market with 50 rows, mean over 6 seeds.
F, R = 30, 3
def fit_delta(seed, scale):
rng = np.random.default_rng(seed)
wg = rng.normal(scale=0.5, size=F); wl = rng.normal(scale=0.3, size=(R, F))
Xs, ys, rs = [], [], []
for r, n in ((0, 2000), (1, 2000), (2, 50)):
X = rng.normal(size=(n, F)); y = (rng.random(n) < sigmoid(X @ (wg + wl[r]) - 0.5)).astype(int)
Xs.append(X); ys.append(y); rs.append(np.full(n, r))
X = np.vstack(Xs); y = np.concatenate(ys); reg = np.concatenate(rs)
D = np.hstack([X] + [X * (reg == r)[:, None] * scale for r in range(R)])
m = LogisticRegression(C=1.0, max_iter=500).fit(D, y)
c = m.coef_[0][F * (1 + 2): F * (1 + 3)] # coefficients of the new-market block
return np.linalg.norm(scale * c), np.linalg.norm(wl[2])
for scale in (0.3, 1.0):
res = np.array([fit_delta(s, scale) for s in range(6)])
print(f"scale {scale}: fitted |delta| of the new market {res[:, 0].mean():.3f} (true |delta| {res[:, 1].mean():.3f})")
Output:
new-market weights w_g + delta = [ 1.1 -0.3 0. ]
click probability with the global weights only: 0.550; with the regional deviation: 0.622
scale 1.0: a deviation of delta = 0.3 needs coefficient c = 0.30 and pays penalty weight on c^2 = 0.09 (vs 0.09 at scale 1.0)
scale 0.3: a deviation of delta = 0.3 needs coefficient c = 1.00 and pays penalty weight on c^2 = 1.00 (vs 0.09 at scale 1.0)
scale 0.3: fitted |delta| of the new market 0.693 (true |delta| 1.516)
scale 1.0: fitted |delta| of the new market 2.084 (true |delta| 1.516)
Diagnosing an under-performing new market
Check in this order, because each step is cheaper than the next and rules out a cause:
- Is the measurement sound? Is the metric computed on the new market's own logged data, with the same definition and position-bias handling (clicks depend on where an item was shown, so the correction applied in mature markets must be applied here too) as mature markets? Is the sample large enough to have a usable confidence interval? Are the baselines (popularity within the market) included?
- Data coverage. What share of the items users in this market request or click have no training history? In the run, an assumed 40% of local requests targeted items that mature markets never logged, and the printed share of 0.404 is the share of requests the model has never seen an item for. These items fall back to content or popularity, and the model looks weak without being wrong.
- Feature differences. Compare feature distributions between the new market and the training data (missing rates, value ranges, language, units, currencies, time-of-day). A feature that is always null in the new market, or encoded in another unit, silently degrades scores. Check the standardized mean difference per feature (the difference between the two markets' means divided by the pooled standard deviation; values above roughly 0.1 deserve a look) and the share of nulls.
- Label differences. Click behaviour, layout, device mix and the baseline ranker that produced the logged data may differ, so the labels mean something different (position bias differs by interface).
- Localization. Translation or transliteration quality of titles and queries, local catalog completeness and inventory, local pricing and payment options, cultural or seasonal relevance.
- Model structure. Only now ask whether the model needs region-specific capacity. Fit the hierarchical variant and see whether the new market's slice improves while mature markets stay flat.
Report slice metrics (new market against each mature market) on the same dashboard, so launch problems are seen early.
Exploration and data collection
A new market produces data only for what the current model shows. Reserve a small exploration slice and log the propensity (the probability that the item was shown to that user) so that later models can be trained and evaluated without inheriting the launch policy's blind spots. Use content features for items with no history and let the regional deviation grow as data arrives.
Trade-offs and pitfalls
- A fully separate model per region has the cleanest local fit and the worst cold start, and it multiplies the number of models to operate.
- A single global model with no regional features is cheap and fair to small regions in code, but it imposes the dominant market's taste on everyone.
- Shrinkage strength is a hyperparameter; choose it per region size by validating on a held-out slice of that region, not on pooled data where large regions dominate.
- Do not read a lower metric in a new market as a modeling failure before step 1 and step 2 are checked.
Recommendation. Ship the shared model with local features and a regularized regional deviation, instrument coverage and feature-shift checks per region at launch, and relax the shrinkage as the market's data grows.
Running the code
Python 3.12 with numpy and scikit-learn installed, saved as regional_ranking.py; the extra program is regional_check.py (numpy and scikit-learn). Run each with python <file>. The first lines of the program pin the linear-algebra libraries to one thread.
You must pick the best two of ten candidate recommenders using only logged click data collected under selection bias. How do you evaluate them offline, and how do you control variance and multiple comparisons?
Sample Answer
The idea
The log only contains the reward of the item that was shown. Ten candidate recommenders would each have shown different items, so their clicks are mostly unobserved. Averaging the clicks in the log tells you how the old system did, not how a candidate would do. The fix is off-policy evaluation: re-weight each logged row by how much more or less likely the candidate would have been to show that item than the logging system was, using the logged propensity (the probability the logger gave to the item it showed). Rank the ten candidates by these estimates, but treat the ranking as noisy: you are picking the best two of ten noisy numbers, so the winners' scores are inflated and the gaps between near-ties are not resolved by the data. The plan is (1) a low-variance estimator, (2) paired comparisons on shared rows, (3) simultaneous confidence intervals over all ten, (4) selection and reporting on different rows, and (5) a short list confirmed online rather than a hard pick of two.
Step 1: estimate each candidate's value from the log
For logged rows i=1..n with context xi, shown item ai, reward ri (click) and propensity μi, and a candidate policy π that gives each item a probability:
wi=μiπ(ai∣xi)| Estimator | Formula | Property |
|---|---|---|
| IPS (inverse propensity scoring) | n1∑iwiri | Unbiased if propensities are correct and positive wherever π has mass (this is called overlap: the logger must sometimes show what the candidate would show); high variance when weights are large |
| SNIPS (self-normalised IPS) | ∑iwiri/∑iwi | Small bias, usually much lower variance, stays inside the reward range |
| DR (doubly robust) | n1∑i[∑aπ(a∣xi)q^(xi,a)+wi(ri−q^(xi,ai))] | Uses a reward model q^ as a baseline and the weights to correct it; consistent (it converges to the true value as the log grows) if either the propensities or q^ is right; lower variance when q^ is decent |
Here q^(x,a) is a model of the click probability. The reward model should be cross-fitted: trained on one half of the rows and used on the other, so it does not memorise the rows it corrects.
Five rows by hand
Before the simulation, the three estimators on a log small enough to check with a calculator. Five rows; the logger's probabilities (propensities) depend on the time of day; the candidate prefers item C; a hand-set reward model q^ gives the predicted click probability of each item. The program prints the weight wi of each row, the doubly robust pieces, the three estimates, and the effective sample size.
import numpy as np
from scipy.stats import norm
# Five logged rows. Items A, B, C. The logger's probabilities (propensities) depend on the time of day.
ctx = ["morning", "morning", "evening", "evening", "evening"]
shown = ["A", "B", "C", "A", "B"]
click = np.array([1.0, 0.0, 1.0, 0.0, 0.0])
mu = {"morning": {"A": 0.6, "B": 0.3, "C": 0.1}, "evening": {"A": 0.5, "B": 0.4, "C": 0.1}} # logger
pi = {"morning": {"A": 0.2, "B": 0.2, "C": 0.6}, "evening": {"A": 0.1, "B": 0.1, "C": 0.8}} # candidate
qhat = {"morning": {"A": 0.3, "B": 0.2, "C": 0.5}, "evening": {"A": 0.2, "B": 0.1, "C": 0.6}} # reward model
w = np.array([pi[c][a] / mu[c][a] for c, a in zip(ctx, shown)])
base = np.array([sum(pi[c][a] * qhat[c][a] for a in "ABC") for c in ctx]) # sum over actions of pi * qhat
resid = np.array([r - qhat[c][a] for c, a, r in zip(ctx, shown, click)]) # reward minus model on the shown item
print("row ctx shown click weight weight*click model term correction w*(r-qhat)")
for i in range(5):
print(f"{i+1} {ctx[i]:8s} {shown[i]} {int(click[i])} {w[i]:.3f} {w[i]*click[i]:.3f} {base[i]:.3f} {w[i]*resid[i]:+.3f}")
print(f"IPS = mean(w*r) = {np.mean(w * click):.4f}")
print(f"SNIPS = sum(w*r) / sum(w) = {np.sum(w * click) / np.sum(w):.4f}")
print(f"DR = mean(model term + correction) = {np.mean(base + w * resid):.4f}")
print(f"effective sample size (sum w)^2 / sum w^2 = {np.sum(w) ** 2 / np.sum(w ** 2):.2f} of 5 rows")
# Why a simultaneous interval needs a bigger multiplier than 1.96 for ten candidates
rng = np.random.default_rng(0)
m = np.abs(rng.normal(size=(200000, 10))).max(axis=1)
print(f"\ncritical value for one 95% interval: {norm.ppf(0.975):.2f}")
print(f"95th percentile of the largest of 10 independent standardised errors: {np.quantile(m, 0.95):.2f}")
print(f"Bonferroni multiplier for 10 intervals: {norm.ppf(1 - 0.05 / 20):.2f}")
Output:
row ctx shown click weight weight*click model term correction w*(r-qhat)
1 morning A 1 0.333 0.333 0.400 +0.233
2 morning B 0 0.667 0.000 0.400 -0.133
3 evening C 1 8.000 8.000 0.510 +3.200
4 evening A 0 0.200 0.000 0.510 -0.040
5 evening B 0 0.250 0.000 0.510 -0.025
IPS = mean(w*r) = 1.6667
SNIPS = sum(w*r) / sum(w) = 0.8818
DR = mean(model term + correction) = 1.1130
effective sample size (sum w)^2 / sum w^2 = 1.38 of 5 rows
critical value for one 95% interval: 1.96
95th percentile of the largest of 10 independent standardised errors: 2.80
Bonferroni multiplier for 10 intervals: 2.81
Reading it:
- Row 3 is the whole story. The logger showed item C only 10% of the time in the evening, the candidate would show it 80% of the time, so the row gets weight 0.8/0.1=8. That single click contributes 8×1=8 to the sum of wiri, and IPS divides by 5 rows: 8.333/5=1.6667. A click rate above 1 is impossible, which shows how a few heavy rows dominate IPS.
- SNIPS divides by the sum of weights instead: 8.333/9.450=0.8818, a value inside [0, 1] that is still driven by row 3.
- DR starts from the model term of each row, the candidate's expected click under q^ (evening: 0.1×0.2+0.1×0.1+0.8×0.6=0.51) and then adds the correction wi(ri−q^(xi,ai)): how wrong the model was on the item that was actually shown, scaled by the weight. If q^ were perfect the corrections would average to zero; if the weights are right they repair the model's bias. Its estimate here is 1.1130.
- The effective sample size (∑w)2/∑w2 is 1.38 of 5 rows. It is the number of equally weighted rows that would carry the same information, so the ratio to the number of rows says how much of the log this candidate can use: near 1 means evenly spread weights, near 0 means a handful of rows decide the estimate. This candidate cannot be judged from this tiny log.
- The last three lines explain the critical value used below: a single 95% interval uses 1.96, but the 95th percentile of the largest of ten independent standardised errors is 2.80, because the chance that at least one of ten errors is large is much bigger than for one. Bonferroni's multiplier (the 1.96 recipe at an error level of 0.05 / 10) is 2.81, almost the same here. The bootstrap in the next section handles estimates that share rows and so move together, which lowers the value (2.53 in the main run below).
Step 2: what to control, and how
- Variance. Clip the weights at a cap (a bias-for-variance trade), prefer DR or SNIPS to plain IPS, and log the effective sample size (∑w)2/∑w2 per candidate (the number of equally weighted rows that would carry the same information; a ratio to the number of rows near 1 is healthy and near 0 means a few rows decide the estimate). A candidate whose effective sample size is tiny cannot be ranked from this log, however good its point estimate looks.
- Paired comparisons. All ten estimates come from the same rows, so their errors are correlated. The difference between two candidates, computed row by row, is much less noisy than either estimate alone.
- Multiple comparisons. Ten 95% intervals do not give 95% confidence that all ten contain the truth. Use a simultaneous interval, which is built to contain all ten true values together at the stated level. The family-wise error rate (FWER) is the probability that at least one of the ten claims is wrong; controlling it at 5% is the goal. A Gaussian-multiplier bootstrap gets there in four steps: (1) compute each candidate's per-row term and standardise it by its standard deviation; (2) draw one random Normal(0, 1) number per row and form, for each candidate, the weighted sum of its standardised terms divided by n; (3) record the largest absolute value across the ten candidates; (4) repeat a few hundred times and take the 95th percentile of those maxima as c. The interval is estimate ±c× standard error. It is larger than 1.96 because the maximum of ten errors exceeds a single one, as the five-row program's last lines show. Start with this when estimates share rows. Bonferroni (dividing the error rate by ten) needs no bootstrap and is a simpler, more conservative alternative; Holm's step-down procedure (compare the smallest p-value with 0.05/10, the next with 0.05/9, and so on, stopping at the first that fails) controls the same FWER and rejects at least as often as Bonferroni.
- Winner's curse. The maximum of noisy estimates is biased upward, because the chosen candidates are partly chosen for their luck. Fix it by selecting on one set of rows and reporting on another (sample splitting), or by shrinking estimates. The curse is small when the log is large and the candidates are well separated, and it grows with noisy estimates and many near-equal candidates; the last block of the simulation below shows both regimes.
Worked example
A simulated world with 4 context features and 5 items, a logger whose item choice depends on the context (the selection bias), and 10 candidate recommenders whose true values are known only because this is a simulation (so the estimates can be checked). The reward model is a stand-in: logistic regression per item, cross-fitted over 2 folds. Weights are clipped at 20 in all estimators.
import numpy as np
from sklearn.linear_model import LogisticRegression
D, K = 4, 5
W_TRUE = np.random.default_rng(1).normal(size=(D, K))
W_LOG = np.random.default_rng(2).normal(size=(D, K)) * 0.8
def softmax(z):
z = z - z.max(axis=1, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=1, keepdims=True)
def reward_prob(X):
return 1.0 / (1.0 + np.exp(-(X @ W_TRUE - 0.8)))
def make_policies(m, seed=3, q_lo=0.8, q_hi=1.0):
"""m candidate recommenders: logits = sharpness * (true-score mixed with random noise directions)."""
rng = np.random.default_rng(seed)
quality = np.linspace(q_lo, q_hi, m)
noise = rng.normal(size=(m, D, K)) * 0.5
return [(q, nz) for q, nz in zip(quality, noise)]
def policy_probs(pol, X):
q, nz = pol
return softmax(2.0 * q * (X @ W_TRUE) + X @ nz)
def log_data(rng, n):
X = rng.normal(size=(n, D))
mu = softmax(X @ W_LOG)
a = np.array([rng.choice(K, p=p) for p in mu])
r = (rng.random(n) < reward_prob(X)[np.arange(n), a]).astype(float)
return X, a, r, mu[np.arange(n), a]
def estimates(pols, X, a, r, prop, qhat=None, clip=20.0):
"""Return IPS, SNIPS and DR estimates (one per policy). qhat: (n, K) reward-model predictions."""
n = len(a); idx = np.arange(n)
ips, snips, dr = [], [], []
for pol in pols:
pi = policy_probs(pol, X)
w = np.minimum(pi[idx, a] / prop, clip)
ips.append(np.mean(w * r))
snips.append(np.sum(w * r) / np.sum(w))
if qhat is not None:
dr.append(np.mean(np.sum(pi * qhat, axis=1)) + np.mean(w * (r - qhat[idx, a])))
return np.array(ips), np.array(snips), np.array(dr)
def crossfit_qhat(X, a, r, folds=2):
"""Reward model: one logistic regression per action, predicted on the fold it was NOT trained on."""
n = len(a); qhat = np.zeros((n, K)); fold = np.arange(n) % folds
for f in range(folds):
tr, te = fold != f, fold == f
for act in range(K):
m = tr & (a == act)
clf = LogisticRegression(C=1.0).fit(X[m], r[m])
qhat[te, act] = clf.predict_proba(X[te])[:, 1]
return qhat
# ground truth of the 10 candidates (known only because this is a simulation)
pols = make_policies(10)
X_big = np.random.default_rng(999).normal(size=(200000, D))
true_v = np.array([np.mean(np.sum(policy_probs(p, X_big) * reward_prob(X_big), axis=1)) for p in pols])
order = np.argsort(-true_v)
print("true values, best first:", np.round(true_v[order], 4))
print("true top-2 policy ids:", sorted(order[:2].tolist()))
# part 1: how noisy is each estimator for ONE policy, and how biased?
N, REPS = 3000, 60
res = {"IPS": [], "SNIPS": [], "DR": []}
for s in range(REPS):
X, a, r, prop = log_data(np.random.default_rng(1000 + s), N)
ips, sn, dr = estimates(pols, X, a, r, prop, crossfit_qhat(X, a, r))
res["IPS"].append(ips); res["SNIPS"].append(sn); res["DR"].append(dr)
print(f"\nestimator behaviour over {REPS} logged samples of {N} rows, averaged over the 10 policies")
for nm, arr in res.items():
arr = np.array(arr)
print(f"{nm:6s} mean bias {np.mean(arr.mean(axis=0) - true_v):+.4f} mean std {arr.std(axis=0).mean():.4f}")
# part 2: per-row doubly robust terms, simultaneous intervals by a Gaussian-multiplier bootstrap
def dr_rows(pols, X, a, r, prop, qhat, clip=20.0):
"""phi[i, j] = value of policy j implied by row i; the DR estimate is the column mean."""
n = len(a); idx = np.arange(n); cols = []
for pol in pols:
pi = policy_probs(pol, X)
w = np.minimum(pi[idx, a] / prop, clip)
cols.append(np.sum(pi * qhat, axis=1) + w * (r - qhat[idx, a]))
return np.stack(cols, axis=1)
def simultaneous_c(phi, rng, B=400, level=0.95):
n = phi.shape[0]; sd = phi.std(axis=0, ddof=1)
centred = (phi - phi.mean(axis=0)) / sd
xi = rng.normal(size=(B, n))
tmax = np.abs(xi @ centred).max(axis=1) / np.sqrt(n)
return np.quantile(tmax, level)
REPS, N = 40, 10000
cov_naive = cov_sim = hit = 0
curse_same, curse_split, ambiguous, c_list, se_one, se_diff = [], [], [], [], [], []
for s in range(REPS):
rng = np.random.default_rng(5000 + s)
X, a, r, prop = log_data(rng, N)
qh = crossfit_qhat(X, a, r)
phi = dr_rows(pols, X, a, r, prop, qh)
est = phi.mean(axis=0); se = phi.std(axis=0, ddof=1) / np.sqrt(N)
c = simultaneous_c(phi, rng); c_list.append(c)
b1, b2 = order[0], order[1]
se_one.append(se[b1]); se_diff.append((phi[:, b1] - phi[:, b2]).std(ddof=1) / np.sqrt(N))
cov_naive += np.all(np.abs(est - true_v) <= 1.96 * se)
cov_sim += np.all(np.abs(est - true_v) <= c * se)
top2 = np.argsort(-est)[:2]
hit += set(top2) == set(order[:2])
curse_same.append(np.mean(est[top2] - true_v[top2]))
# can the data rule out each policy as a member of the top 2? compare its upper bound with the 2nd best lower bound
second_lcb = np.sort(est - c * se)[-2]
ambiguous.append(int(np.sum(est + c * se >= second_lcb)))
# choose on half A, report on half B
h = N // 2
pick = np.argsort(-phi[:h].mean(axis=0))[:2]
curse_split.append(np.mean(phi[h:, pick].mean(axis=0) - true_v[pick]))
print(f"\nselection and intervals, {REPS} logged samples of {N} rows, 10 policies, DR estimates")
print(f"critical value: simultaneous {np.mean(c_list):.2f} vs 1.96 for one policy")
print(f"all 10 true values inside their intervals: naive 1.96 {cov_naive}/{REPS}, simultaneous {cov_sim}/{REPS}")
print(f"standard error: one policy {np.mean(se_one):.4f}, difference between the true best two (same rows) {np.mean(se_diff):.4f}")
print(f"exact true top-2 recovered by the point estimate: {hit}/{REPS}")
print(f"policies the data cannot yet exclude from the top 2: mean {np.mean(ambiguous):.1f} of 10")
print(f"optimism of the reported value of the chosen pair, same rows: {np.mean(curse_same):+.4f}")
print(f"optimism of the reported value, choose on half A, report on half B: {np.mean(curse_split):+.4f}")
# part 3: a larger pool of near-equal policies
print("\noptimism of the best DR estimate as the pool grows (20 logged samples of 1000 rows each; every policy has the same quality setting)")
for m in (10, 100, 400):
big = make_policies(m, seed=11, q_lo=0.9, q_hi=0.9)
tv = np.array([np.mean(np.sum(policy_probs(p, X_big[:20000]) * reward_prob(X_big[:20000]), axis=1)) for p in big])
c = []
for s in range(20):
X, a, r, prop = log_data(np.random.default_rng(9000 + s), 1000)
est = dr_rows(big, X, a, r, prop, crossfit_qhat(X, a, r)).mean(axis=0)
j = np.argmax(est)
c.append(est[j] - tv[j])
print(f"M={m:4d} spread of true values {tv.max() - tv.min():.3f} mean optimism of the chosen estimate {np.mean(c):+.4f}")
Output:
true values, best first: [0.575 0.5689 0.5647 0.5529 0.5492 0.5478 0.545 0.545 0.5308 0.5213]
true top-2 policy ids: [7, 9]
estimator behaviour over 60 logged samples of 3000 rows, averaged over the 10 policies
IPS mean bias -0.0218 mean std 0.0214
SNIPS mean bias -0.0046 mean std 0.0163
DR mean bias -0.0012 mean std 0.0161
selection and intervals, 40 logged samples of 10000 rows, 10 policies, DR estimates
critical value: simultaneous 2.53 vs 1.96 for one policy
all 10 true values inside their intervals: naive 1.96 30/40, simultaneous 36/40
standard error: one policy 0.0089, difference between the true best two (same rows) 0.0051
exact true top-2 recovered by the point estimate: 30/40
policies the data cannot yet exclude from the top 2: mean 9.2 of 10
optimism of the reported value of the chosen pair, same rows: +0.0001
optimism of the reported value, choose on half A, report on half B: -0.0004
optimism of the best DR estimate as the pool grows (20 logged samples of 1000 rows each; every policy has the same quality setting)
M= 10 spread of true values 0.028 mean optimism of the chosen estimate +0.0138
M= 100 spread of true values 0.060 mean optimism of the chosen estimate +0.0229
M= 400 spread of true values 0.068 mean optimism of the chosen estimate +0.0266
How to read it. Two quantities are named in the output: optimism is the reported estimate minus the true value for the policies that were chosen (positive means the report flatters them), and the ambiguous count is the number of policies whose upper bound still reaches the second-highest lower bound, so the data cannot exclude them from the top two.
- Estimators. Over 60 logged samples of 3000 rows, the mean bias of IPS is -0.0218 (this comes from clipping at 20 and would shrink with a higher cap, at the cost of variance), SNIPS -0.0046, DR -0.0012; the standard deviation falls from 0.0214 (IPS) to 0.0163 (SNIPS) and 0.0161 (DR).
- Simultaneous intervals. The critical value is 2.53 against 1.96 for a single interval. Over 40 repeats of 10000 rows, intervals built with 1.96 contained all ten true values in 30 of the 40, simultaneous intervals in 36 of the 40. A 95% target would be about 38 of 40, so the simultaneous intervals are still a little narrow here: treat them as approximate, and check their coverage with a simulation like this one when the decision matters. The gap between 30 and 36 is the point.
- Pairing. The standard error of the difference between the true best two candidates (0.0051) is smaller than the standard error of one candidate's estimate (0.0089).
- Selection. The point estimates recovered the true top two in 30 of 40 repeats, and on average 9.2 of the 10 candidates could not yet be excluded from the top two at the simultaneous 95% level. With 10000 rows and this noise, the log does not decide the pair.
- Winner's curse. At 10000 rows the optimism of the chosen pair is near zero (+0.0001), and choosing on half A then reporting on half B gives -0.0004. The curse needs noisy estimates and many near-equal candidates: with 1000 rows and a pool of policies that all share the same quality setting, the chosen estimate is optimistic by +0.0138 for 10 candidates, +0.0229 for 100 and +0.0266 for 400.
Scale: ranking thousands of policies
With thousands of candidates (for example a hyperparameter sweep of bandit policies) the same method applies, with three changes:
- Build the matrix of per-row terms ϕij (row i, policy j) in chunks of policies so memory stays at O(n×chunk); the reward model q^ is fitted once and shared, and the weights are one pass per policy over the log.
- The optimism of the best estimate keeps growing with the pool, so never report the winner's in-sample score. Screen with the full log, keep a few dozen candidates whose upper bounds still reach the top, then re-estimate them on rows not used for screening.
- Simultaneous critical values grow slowly with the number of candidates (for roughly independent estimates, like 2lnM for M candidates; estimates built from shared rows are correlated, which lowers it), so a bootstrap-based critical value is affordable, but near-ties stay unresolved: more candidates means more near-ties.
Recommendation and what flips it
Rank with cross-fitted DR (or SNIPS if no reward model is trustworthy), clipped weights, paired differences and simultaneous intervals. Pick two only if their lower bounds clear the third-best candidate's upper bound; otherwise take the 3 to 5 candidates that cannot be excluded into an online experiment, because the log has no more to say. Overlap flips the plan: if a candidate recommends items the logger rarely or never showed (propensity near 0), no estimator can evaluate it from this log, and it must be tested online or after collecting logs with some randomisation.
Common mistakes
- Comparing click rates on the logged rows, ignoring that each candidate would have shown different items.
- Using logged propensities that are not the true selection probabilities (for example, ignoring a post-processing filter).
- Reporting the winner's own score as its expected performance.
- Treating ten overlapping 95% intervals as one confidence statement.
Running the code
Use Python 3.12 with numpy 2.1.3, SciPy 1.14.1 and scikit-learn 1.5.2. Save each listing to a file and run it with python; all seeds are fixed and the long program finishes in under a minute.
In a marketplace where new items appear constantly and their metadata is sparse, how do you handle item cold start so new items get a fair chance without hurting the experience for everyone else?
Sample Answer
Direct answer
A ranker trained on past clicks cannot rank an item it has never seen shown, so a new item with sparse metadata starts with no evidence and, left alone, never gets any. Give new items two things: a sensible starting estimate (a prior from whatever content exists, shrunk toward the catalogue average) and a bounded exploration budget that gathers evidence fast, ideally with a method that spends impressions where the uncertainty is highest (Thompson sampling). Cap the budget so the cost to everyone else is small and known, require a minimum quality for entry, and stop exploring an item once the evidence says it is weak. Judge it on how quickly good new items are found and how much of the catalogue's CTR is spent finding them.
The mechanism
- Prior for the unknown. Represent a new item's click-through rate (CTR) as a distribution, not a number. A Beta distribution (a distribution over a rate between 0 and 1, described by a count of imaginary clicks and imaginary non-clicks) with mean equal to a content-based guess (category average if metadata is thin) and a strength equal to a few dozen imaginary impressions. Each real impression and click updates it.
- Exploration by sampling. Thompson sampling draws one plausible CTR from each item's current Beta distribution and shows the item with the highest draw. An item with few impressions has a wide distribution, so it sometimes wins and gets shown; as evidence accumulates the distribution narrows and the item competes on its real rate. A weak item is shown less each time its estimate drops.
- Fixed quota as a simple alternative. Reserve a small share of slots (for example 5%) for items below an impression threshold, chosen at random. It is easy to explain and to cap but it spreads impressions evenly, so it spends as much on weak items as on promising ones.
- Exposure-aware training. Log the probability with which each item was shown. Without it, the next model trains on data in which new items are rare and concludes they are bad (new-host or new-listing bias in a marketplace: hosts or sellers with no bookings or reviews yet look worse than they are, so they get fewer impressions, so they stay without reviews). Exposure-aware training corrects for this by weighting each logged example by the inverse of its exposure probability (an item shown with probability 0.1 counts 10 times as much as one shown with probability 1, which stops rarely shown items from being drowned out), or by training on the exploration slice alone, where the choice of item was random.
- Fuse content with collaborative signal. For catalogues with rich content (audio, images, text), map the content embedding to the collaborative embedding space with a model trained on established items, so a new release lands near similar items on day one. Hand over to the collaborative score as the item gains interactions.
- A novelty or uplift term for under-served items. Multiply relevance by a bonus that grows with how under-exposed an item is. Under-exposure is the gap between the impressions an item's relevance would earn and the impressions it has received, written as a share between 0 and 1. For example score = relevance times (1 + γ times under-exposure), where γ is a tuning constant (unrelated to the Beta distribution above) set so that the extra impressions stay inside the exploration budget. Items whose measured uplift stays low lose the bonus; uplift is the extra clicks or sales an item earns because of the added exposure, estimated against a group that did not get the bonus.
A first version needs three of these: the prior (1), the sampling or the quota (2 or 3) and the logged exposure probability (4). The content-to-collaborative mapping (5) pays off when the content is rich, and the novelty term (6) is a tuning layer on top of the others.
Protecting everyone else
- Budget: fix the share of impressions that exploration may use, per surface and per user, and watch the actual share. Size it from the arrival rate: new items per day times the impressions each needs, divided by total daily impressions. With 200 new items a day, 1,000 impressions each (an assumed figure; measure how many your items need) and 5,000,000 impressions a day, that is 0.04, a 4% budget.
- Entry gate: only items that pass a quality check (complete listing, no policy flags) enter the pool.
- Relevance floor: an exploration item must exceed a minimum predicted relevance for the user's context, so a person looking for shoes does not get a random watch.
- Stop rule: retire an item from exploration when its upper confidence bound (an optimistic estimate: the observed rate plus a bonus that is large while impressions are few and shrinks as they accumulate) falls below the established items, or after a maximum number of impressions.
- Fairness among sellers: cap the exploration share any one seller can take so one account uploading hundreds of listings cannot take the whole budget.
Worked example: three policies, 20 seeds
The setup is an assumption for the example: 40 established items with CTRs between 0.05 and 0.08 and 500 impressions of history each, plus 10 new items with no history. Scenario A has 2 good new items (true CTR 0.12) and 8 weak ones (true CTR 0.03); scenario B has 10 weak new items. One item is shown per impression, for 20,000 impressions. Policy "greedy" ranks by observed CTR, which is 0 for an item with no impressions. "Thompson" uses Beta posteriors with a prior of mean 0.06 and strength 20 imaginary impressions. "Quota" is greedy plus a random pick among the new items on 5% of impressions. The reported numbers are averages over 20 seeds. In scenario A the good new items beat the best established ones by construction, so exploration pays; scenario B is the case where new items are no better than the catalogue and exploration is a pure cost.
import numpy as np
# Setup (assumed): 40 established items with known CTRs around 0.05-0.08, and 10 new items.
# Scenario A: 2 of the new items are good (true CTR 0.12), 8 are weak (true CTR 0.03).
# Scenario B: all 10 new items are weak (true CTR 0.03). One item is shown per impression.
def run(policy, seed, new_true, T=20000):
rng = np.random.default_rng(seed)
true = np.concatenate([rng.uniform(0.05, 0.08, 40), new_true])
imps = np.zeros(50); clicks = np.zeros(50)
imps[:40] = 500; clicks[:40] = np.round(true[:40] * 500) # established items carry history
prior_mean, strength = 0.06, 20.0 # new items start from the catalog average
total = 0
for t in range(T):
if policy == "greedy":
score = np.where(imps > 0, clicks / np.maximum(imps, 1), 0.0)
elif policy == "thompson":
a = prior_mean * strength + clicks; b = (1 - prior_mean) * strength + (imps - clicks)
score = rng.beta(a, b)
elif policy == "quota":
score = np.where(imps > 0, clicks / np.maximum(imps, 1), 0.0)
if rng.random() < 0.05:
k = 40 + int(rng.integers(10))
score = np.full(50, -1.0); score[k] = 1.0
k = int(np.argmax(score))
y = rng.random() < true[k]
imps[k] += 1; clicks[k] += y; total += y
found = int((imps[40:42] >= 2000).sum()) # new items 0 and 1 earning 2000+ impressions
wasted = int(imps[42:].sum()) # impressions spent on new items 2..9
return total / T, found, wasted, int(imps[40:].sum())
scenario_a = np.concatenate([np.full(2, 0.12), np.full(8, 0.03)])
print("A: 2 good + 8 weak new items. policy, mean CTR over 20 seeds, good items with 2000+ impressions (mean of 2), impressions on the 8 weak items (mean), seeds finding 0/1/2 good items")
for pol in ["greedy", "thompson", "quota"]:
r = np.array([run(pol, s, scenario_a) for s in range(20)])
n = [int((r[:, 1] == j).sum()) for j in range(3)]
print(f"{pol}, {r[:, 0].mean():.4f}, {r[:, 1].mean():.2f}, {r[:, 2].mean():.0f}, {n[0]}/{n[1]}/{n[2]}")
scenario_b = np.full(10, 0.03)
print("B: all 10 new items weak. policy, mean CTR over 20 seeds, impressions spent on the 10 new items (mean)")
for pol in ["greedy", "thompson", "quota"]:
r = np.array([run(pol, s, scenario_b) for s in range(20)])
print(f"{pol}, {r[:, 0].mean():.4f}, {r[:, 3].mean():.0f}")
# Sizing the budget (illustrative inputs): new items per day x impressions each needs / daily impressions
print("exploration share:", 200 * 1000 / 5_000_000)
Output:
A: 2 good + 8 weak new items. policy, mean CTR over 20 seeds, good items with 2000+ impressions (mean of 2), impressions on the 8 weak items (mean), seeds finding 0/1/2 good items
greedy, 0.0783, 0.00, 0, 20/0/0
thompson, 0.1170, 1.70, 616, 0/6/14
quota, 0.1098, 1.00, 811, 1/18/1
B: all 10 new items weak. policy, mean CTR over 20 seeds, impressions spent on the 10 new items (mean)
greedy, 0.0783, 0
thompson, 0.0700, 1411
quota, 0.0764, 1042
exploration share: 0.04
In scenario A, greedy never gives a new item an impression (0 in the last two columns), so the realized CTR stays at 0.0783 and both good items stay hidden. Thompson sampling reaches 0.1170 and finds on average 1.70 of the 2 good items (both in 14 of 20 seeds), at a cost of 616 impressions spent on weak new items (about 3.1% of 20,000). The 5% quota reaches 0.1098 and finds 1.00 of the 2 on average, spending 811 impressions on weak items (about 4.1%). The quota's 1.00 has a mechanical cause: it hands each new item only about 100 random impressions (5% of 20,000 is 1,000, shared by 10 items), and after that the greedy part shows whichever item has the single highest observed CTR. Once one good item takes the lead it receives nearly every slot, and the second good item gets only its quota share, so exactly one good item is found in 18 of 20 seeds. Thompson sampling keeps both good items' beliefs wide and high, so it splits traffic between them. In this setup, sampling by uncertainty found more good items for fewer wasted impressions than a flat quota.
Scenario B shows what exploration costs when nothing new is good. Greedy keeps 0.0783. Thompson drops to 0.0700 with 1,411 impressions on the new items (about 7.1%), and the quota drops to 0.0764 with 1,042 (about 5.2%). Part of Thompson's larger gap comes from it spreading impressions over every item whose rate is still uncertain, the established ones included. So the cost is real and measurable in a short test, and whether it is repaid depends on whether the catalogue contains new items worth finding: in scenario A the gain (0.0783 to 0.1170) arrives within the 20,000 impressions because the toy's good items are far better than the rest and get found quickly, while in a real marketplace the share of good new items is smaller and the payoff builds up as the found items keep earning. Set the exploration budget as the most CTR you will pay to find items, check it with the scenario B style cost, and keep the holdout group that gets no exploration so the net effect is measured.
How to measure
- Discovery: time and impressions until a good new item has a stable estimate; share of eventually-good items found.
- Cost: CTR and revenue on exploration slots versus the same slots under the established ranking, and overall CTR with a holdout group that gets no exploration.
- Fairness and health: new-seller retention, share of impressions to items less than a week old versus their share of eventual engagement.
Pitfalls
- Boosting new items with a fixed multiplier and no feedback; it keeps weak items on top.
- Exploring in slot 1 on every page. Put exploration where attention is lower or personalize it to relevant context.
- Evaluating by overall CTR in a short test. The cost of exploration shows up immediately, while the benefit depends on how many good new items exist and on how long the found items keep earning, which a short test can miss or overstate; read cost and discovery separately.
Unlock Full Question Bank
Get access to all Recommendation, Ranking, and Personalization interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.