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.
Implement a bootstrap-based Thompson-style exploration method for contextual bandits using an ensemble of online regressors.
Sample Answer
Direct answer
This is a contextual bandit: each round you see a context (features describing the situation), choose one action (an arm), and observe only that action's reward. A reward model predicts each action's reward from the context. Thompson sampling picks the action that looks best under a random draw from the posterior over the reward model, where the posterior is the belief about which model parameters are plausible given the data so far (wide when data is scarce, narrow when it is plentiful). When the model is not conjugate (the posterior has no simple closed form), you can approximate "a draw from the posterior" with "a model trained on a resampled copy of the data". Keep an ensemble of B regressors per action. Each observation is shown to each member with a random weight (the online bootstrap; the bootstrap itself means training on resampled copies of the data, in which some points repeat and some are missing), so members see different data and disagree where data is scarce. Each round, pick one member at random and act greedily on its predictions. Where members agree the policy exploits, where they disagree it explores, and no posterior formula is needed. The ensemble needs members that disagree where data is thin, and there are two ways to create that disagreement: random per-observation weights (the online bootstrap) and random starting prior means. The published bootstrap Thompson sampling of Eckles and Kaptein (2014) relies on the weights: each replicate gives every observation a weight of 0 or 2 with equal probability (the "double-or-nothing" bootstrap, a close relative of the Poisson(1) weights used below), and every replicate starts from the same Beta(1,1) belief about a Bernoulli arm. The ridge simulation below is a different, smaller setting. In it the random starting means are what make the ensemble beat a plain greedy learner (always play the action with the highest predicted reward), while the bootstrap weights alone, from identical starts, did not. How much each source of disagreement matters depends on the model and the starting point, so check it on your own problem.
Why it approximates Thompson sampling
In Thompson sampling you sample parameters θ~ from the posterior given the data so far and play the arm with the best predicted reward under θ~. An action with little data has a wide posterior, so it wins the draw sometimes and gets explored; an action with much data has a narrow posterior and rarely wins by luck. Training a model on a bootstrap resample gives a parameter vector whose spread across resamples mimics that posterior spread: sparse regions of context-action space produce members that differ, dense regions produce members that agree. It is an approximation with no exactness guarantee, and its quality depends on the ensemble size and how much the members differ at the start.
The online algorithm
Per action a keep B ridge regressors (linear models fitted by least squares with an L2 penalty that pulls the weights toward a prior mean) θa,1,…,θa,B over a context vector x∈Rd, each holding a matrix Aa,m∈Rd×d and a vector ba,m∈Rd with θa,m=Aa,m−1ba,m.
Why these two quantities are enough: a ridge regressor with sample weights wi and prior mean θ0 minimises
i∑wi(ri−xi⊤θ)2+λ∥θ−θ0∥2Setting the derivative to zero gives (λI+∑iwixixi⊤)θ=λθ0+∑iwirixi. The bracket is A and the right-hand side is b, and both are plain sums over observations, so each new observation just adds wxx⊤ to A and wrx to b, with no need to keep the old data. The code below checks the solve against scikit-learn's Ridge with sample_weight.
- Choose. Draw a member index m uniformly from 1..B. For every action compute r^a=x⊤θa,m and play the action with the largest value.
- Observe the reward r for the played action a.
- Update with bootstrap weights. For each member m, draw wm∼Poisson(1) and set Aa,m+=wmxx⊤ and ba,m+=wmrx. A Poisson(1) weight (a random whole number that is 0 about 37% of the time, 1 about 37%, 2 about 18% and larger rarely) is the streaming stand-in for "sample with replacement": each point appears 0, 1, 2 or more times, with no need to hold the data. The tiny example below shows what each weight does.
- Initialise with diversity. Aa,m=λI and ba,m=λθa,m0, where each member's prior mean θa,m0 (the vector the ridge penalty pulls toward before any data) is a different random vector. Without this, all members start identical and early exploration depends only on the random weights.
If your online regressors are gradient-trained (logistic regression, a small network) rather than ridge, the same weighting applies: repeat each member's SGD step wm times, or scale its loss by wm. Cost: B times the memory, and the update is B times the work. Choosing needs only the one sampled member's predictions, so serving cost is not multiplied unless you also log propensities (see the last pitfall), which needs all B members' predictions.
The mechanism on two arms, with numbers
One context feature that is always 1 (so A and b are single numbers), λ=1 and five members. First, what the weight does to one observation with reward 2 and prior mean 0. Then two arms: arm 0 (true mean reward 0.6) has 20 observations, arm 1 (true mean 0.8, in fact the better arm) has only 2.
import numpy as np
lam = 1.0
# what a Poisson(1) weight does to ONE observation (context x = 1, reward r = 2, prior mean 0)
for w in (0, 1, 2):
A, b = lam + w * 1.0, w * 2.0
print(f"weight {w}: A = {A:.1f}, b = {b:.1f}, estimate b/A = {b / A:.2f}")
# two arms, five ensemble members, context always 1 (so d = 1 and A, b are single numbers)
rng = np.random.default_rng(3)
B = 5
true_mean = [0.6, 0.8]
n_obs = [20, 2] # arm 0 has plenty of data, arm 1 almost none
prior = rng.normal(size=(2, B)) # each member starts from its own random prior mean
theta = np.zeros((2, B))
for a in (0, 1):
rewards = true_mean[a] + 0.5 * rng.normal(size=n_obs[a])
A = np.full(B, lam)
b = lam * prior[a]
for r in rewards:
w = rng.poisson(1.0, B) # one weight per member for this observation
A += w
b += w * r
theta[a] = b / A
print(f"arm {a}: {n_obs[a]:2d} observations, member estimates {np.round(theta[a], 2)}, spread (sd) {theta[a].std():.2f}")
choice = theta.argmax(axis=0)
print("arm each member would play:", choice)
print("fraction of members choosing arm 0 / arm 1:", (choice == 0).mean(), "/", (choice == 1).mean())
Output:
weight 0: A = 1.0, b = 0.0, estimate b/A = 0.00
weight 1: A = 2.0, b = 2.0, estimate b/A = 1.00
weight 2: A = 3.0, b = 4.0, estimate b/A = 1.33
arm 0: 20 observations, member estimates [0.85 0.58 0.64 0.66 0.56], spread (sd) 0.10
arm 1: 2 observations, member estimates [ 0.26 -0.38 0.25 -0.47 1.05], spread (sd) 0.55
arm each member would play: [0 0 0 0 1]
fraction of members choosing arm 0 / arm 1: 0.8 / 0.2
A weight of 0 hides the observation from that member, 1 shows it once and 2 shows it twice, which is how members end up with different data. Arm 0's five estimates sit close together (spread 0.10) because 20 observations drown out each member's prior; arm 1's estimates are scattered (spread 0.55) because two observations cannot. Each round one member is drawn at random and plays its favourite arm; here 4 of 5 members favour arm 0 and 1 favours arm 1, so the better but poorly known arm is tried about one round in five. As arm 1 collects data its estimates converge toward its true mean, the members increasingly agree, and the fraction of rounds that play it rises if it really is the better arm (an arm that is actually worse would instead see its fraction fall toward zero). The same fraction is the logged propensity, the probability the policy had of choosing that action: 0.2 for arm 1 and 0.8 for arm 0 in this snapshot.
Code, with a reference check
The next program implements the ensemble, checks that a weighted ridge solve equals scikit-learn 1.5.2 Ridge with sample_weight (printed), and compares cumulative regret (the total gap between the best action's expected reward and the played action's, summed over rounds) of three policies over 40 seeds: uniform random, a single greedy ridge regressor, and the bootstrap ensemble with B=20 and prior standard deviation 1, plus two ensemble variants (no prior spread; constant weights instead of Poisson weights). Two environments: linear rewards with a fresh random context each round (5 actions, context dimension d = 4 including a constant feature), and a constant context, which reduces it to a plain multi-armed bandit. Rewards are the linear mean plus Gaussian noise (standard deviation 0.5). This is a simulation of a synthetic environment, not a claim about any production system.
import numpy as np
from sklearn.linear_model import Ridge
LAM = 1.0
class BootstrapTS:
"""B online ridge regressors per arm. Each observation is shown to each member with a
Poisson(1) weight (online bootstrap). Each round: draw one member, act greedily on it."""
def __init__(self, n_arms, d, B, rng, prior_sd=0.0, boot=True):
self.rng, self.B, self.boot = rng, B, boot
self.A = np.tile(LAM * np.eye(d), (n_arms, B, 1, 1)) # (arms, members, d, d)
self.b = LAM * prior_sd * rng.normal(size=(n_arms, B, d)) # ridge pulled toward a random per-member prior mean
def act(self, x):
m = self.rng.integers(self.B)
theta = [np.linalg.solve(self.A[a, m], self.b[a, m]) for a in range(len(self.A))]
return int(np.argmax([t @ x for t in theta]))
def update(self, a, x, r):
w = self.rng.poisson(1.0, self.B).astype(float) if self.boot else np.ones(self.B)
self.A[a] += w[:, None, None] * np.outer(x, x)
self.b[a] += w[:, None] * (r * x)
class Greedy(BootstrapTS):
def __init__(self, n_arms, d, rng):
super().__init__(n_arms, d, 1, rng, 0.0)
def update(self, a, x, r):
self.A[a, 0] += np.outer(x, x); self.b[a, 0] += r * x
def run(policy_name, seed, T, n_arms=5, d=4, constant_context=False):
rng = np.random.default_rng(seed)
theta = rng.normal(size=(n_arms, d))
if policy_name == "bootstrap_ts": pol = BootstrapTS(n_arms, d, 20, rng, 1.0)
elif policy_name == "no_prior_spread": pol = BootstrapTS(n_arms, d, 20, rng, 0.0)
elif policy_name == "no_bootstrap_weights": pol = BootstrapTS(n_arms, d, 20, rng, 1.0, boot=False)
elif policy_name == "greedy": pol = Greedy(n_arms, d, rng)
regret = []
total = 0.0
for t in range(T):
x = np.ones(d) if constant_context else np.concatenate([[1.0], rng.normal(size=d - 1)])
mean = theta @ x
a = rng.integers(n_arms) if policy_name == "random" else pol.act(x)
r = mean[a] + 0.5 * rng.normal()
if policy_name != "random": pol.update(a, x, r)
total += mean.max() - mean[a]
regret.append(total)
return regret
# sanity check: the ridge solve equals sklearn Ridge with sample weights
rng = np.random.default_rng(0)
X, y, w = rng.normal(size=(30, 4)), rng.normal(size=30), rng.poisson(1.0, 30).astype(float)
mine = np.linalg.solve(LAM * np.eye(4) + (X * w[:, None]).T @ X, (X * w[:, None]).T @ y)
ref = Ridge(alpha=LAM, fit_intercept=False).fit(X, y, sample_weight=w).coef_
print("weighted ridge matches sklearn Ridge:", bool(np.allclose(mine, ref)))
horizons = (200, 1000, 3000)
se = lambda v: v.std(ddof=1) / np.sqrt(len(v))
for label, kw in (("rich context (d=4, fresh random context each round)", dict(d=4)),
("constant context (d=1, plain multi-armed bandit)", dict(d=1, constant_context=True))):
print(label)
for name in ("random", "greedy", "bootstrap_ts"):
R = np.array([run(name, s, max(horizons), **kw) for s in range(40)])
print(" ", name.ljust(13), " ".join(f"T={h}: {R[:, h - 1].mean():7.1f} (se {se(R[:, h - 1]):5.1f})" for h in horizons))
print(" ensemble variants at T=1000 (B = 20 in each)")
for name in ("bootstrap_ts", "no_prior_spread", "no_bootstrap_weights"):
R = np.array([run(name, s, 1000, **kw) for s in range(40)])
print(" ", name.ljust(21), f"T=1000: {R[:, 999].mean():7.1f} (se {se(R[:, 999]):5.1f})")
Output:
weighted ridge matches sklearn Ridge: True
rich context (d=4, fresh random context each round)
random T=200: 436.1 (se 16.3) T=1000: 2171.3 (se 77.2) T=3000: 6510.9 (se 218.5)
greedy T=200: 65.4 (se 6.2) T=1000: 184.1 (se 29.2) T=3000: 385.1 (se 75.1)
bootstrap_ts T=200: 69.6 (se 2.6) T=1000: 83.5 (se 2.8) T=3000: 91.5 (se 2.8)
ensemble variants at T=1000 (B = 20 in each)
bootstrap_ts T=1000: 83.5 (se 2.8)
no_prior_spread T=1000: 177.0 (se 28.5)
no_bootstrap_weights T=1000: 54.4 (se 2.1)
constant context (d=1, plain multi-armed bandit)
random T=200: 225.9 (se 16.7) T=1000: 1131.2 (se 82.0) T=3000: 3409.5 (se 247.8)
greedy T=200: 60.9 (se 14.1) T=1000: 292.8 (se 71.0) T=3000: 872.5 (se 213.4)
bootstrap_ts T=200: 21.4 (se 3.1) T=1000: 34.6 (se 9.3) T=3000: 52.9 (se 18.0)
ensemble variants at T=1000 (B = 20 in each)
bootstrap_ts T=1000: 34.6 (se 9.3)
no_prior_spread T=1000: 242.5 (se 64.2)
no_bootstrap_weights T=1000: 20.6 (se 5.4)
Reading the code: self.A has shape (arms, members, d, d) and self.b has shape (arms, members, d), so self.A[a, m] and self.b[a, m] are one member's A and b. act draws one member m, solves θ=A−1b for every arm with that member and returns the arm with the largest theta @ x. update draws one Poisson(1) weight per member (w) and adds w * outer(x, x) and w * r * x to the played arm's matrices for all members at once. prior_sd sets how far apart the members' random prior means are; with 0 every member starts the same. Greedy reuses the class with one member, no random prior and weight 1 every time, which is an ordinary ridge regressor that always plays its current best arm.
Reading it (means over 40 seeds, standard errors in brackets): in both environments, both learning policies are far below random. The bootstrap ensemble's regret grows slowly with the horizon: from 83.5 at T=1000 to 91.5 at T=3000 with a fresh context each round, and from 34.6 to 52.9 with a constant context. The single greedy regressor is worse at the longer horizons in both (385.1 and 872.5 at T=3000), and in the constant-context case its standard error is large (213.4) which is consistent with a policy that in some seeds commits early to a poor action. At T=200 the rich-context ensemble is not ahead (69.6 versus 65.4 for greedy, a gap of less than one standard error of the greedy figure): exploration costs something early and pays off later. The variants block isolates what creates the exploration: removing the spread in the prior means leaves the ensemble at a regret level comparable to the greedy regressor's (177.0 against 184.1 with a fresh context each round; 242.5 against 292.8 with a constant context, each within about one standard error of the greedy figure), while replacing the Poisson weights by a constant weight of 1 gave lower regret with a fresh context each round (54.4 against 83.5, a gap of about 29 against standard errors of 2.1 and 2.8). With a constant context the same ordering appears (20.6 against 34.6), but the gap of 14.0 is inside the noise: the two standard errors combine to about 10.8 (9.32+5.42), so treat the two as tied there. So in this ridge toy the random starting means drive the exploration, and the Poisson weights add spread without lowering regret. Two cautions keep this from being read as a general ranking. The prior spread here (standard deviation 1) matches the spread of the true action parameters, which is a favourable start for the ensemble. And the published method differs: it uses double-or-nothing weights on a Bernoulli bandit, where the weights are its source of disagreement. Whether weights alone are enough therefore depends on the model and the starting point; here, from identical starts, they were not (the no-prior-spread row sits at the greedy level). Check a ranking like this on your own problem before trusting it.
Trade-offs and pitfalls
- Ensemble size. B is the resolution of the posterior you are sampling. Very small B gives few distinct draws and under-explores; larger B costs memory and update time. Treat it as a tuning parameter and check regret or reward on a simulator.
- Diversity at the start. Identical members behave like one greedy model, and the simulation shows it: with the same ensemble but no spread in the prior means, regret at T=1000 is about as high as the single greedy regressor's. Random prior means, or a few random pseudo-observations (made-up data points added to the starting state), supply the initial disagreement.
- Poisson(1) weights approximate resampling only when each member has seen a fair number of points; with very few points the bootstrap spread is coarse.
- Not a calibrated posterior. Do not read ensemble spread as a probability. It is a heuristic for how much to explore.
- Delayed or batched feedback. If rewards arrive in batches, many rounds use the same ensemble; sampling a member per round still diversifies, but updates lag.
- Compare against a baseline. In a context-rich problem a greedy model also gets some exploration from varying contexts, so measure the ensemble against greedy, epsilon-greedy (greedy, but a random action with a small probability epsilon) and, when conjugate, linear Thompson sampling or UCB (upper confidence bound: play the action whose predicted reward plus an uncertainty bonus is largest).
- Safety. Exploration serves bad actions on purpose; cap exploration for high-cost actions and log propensities so the data stays usable for off-policy evaluation. When you sample one member uniformly, the action propensity is the fraction of members that choose it, which is computable from all B members' predictions: in the two-arm example, 1 of 5 members chose arm 1, so its propensity was 0.2.
How would you tackle user cold start using behavior from another domain, such as browsing history from a partner site? Cover how you align representations across domains and the failure modes.
Sample Answer
Direct answer
A cold-start user is someone the target recommender has no interaction history for. If a partner site's browsing history is available (with consent), treat it as a substitute signal: learn a function that maps a user's partner-domain behaviour into the target model's embedding space (the shared coordinate system in which every user and item is a point, a list of numbers, and nearby or aligned points mean similar taste), using the users who exist on both sides to supervise it, then score target items with the mapped vector. Three things decide whether this works: how well the representations are aligned, how much taste is truly shared across the domains, and how many bridge users you have (bridge users are the overlap users defined below: people with history on both sides). The mapped model should be one input to the ranker, blended with popularity and context, and it needs a guard against negative transfer (the partner signal making recommendations worse than having no signal).
Step 1: Fix the target space, then learn a bridge
- Train the target recommender first so every target item has a factor vector qi∈Rd (an embedding: a learned list of d numbers). Users with target history get a vector tu, for example the mean of their clicked items' factors or a vector learned by matrix factorization.
- Featurize the partner behaviour (turn it into numbers a model can use) into xu: a histogram over partner categories or pages, or a pooled embedding of viewed pages. This must not require the target catalog.
- Fit a bridge f on the overlap users (those with both histories, matched through a consented shared identity):
Here ∥⋅∥ is the Euclidean norm (the straight-line length of a vector: square each entry, add, take the square root), λ the regularization weight and Ω a penalty on the size of f. A ridge-regularized linear map (a matrix A with f(x)=xA, fitted with a penalty λ∥A∥2 that keeps its entries small when there are few bridge users) is the baseline, and it has the closed form A=(X⊤X+λI)−1X⊤T, where the rows of X are the overlap users' partner histograms and the rows of T their target vectors; this is the np.linalg.solve line in the program below. a small neural network is the next step if you have enough bridge users.
4. Score a cold user by f(xu)⊤qi for every target item. This is the same dot-product scoring the trained model already uses, so it plugs into candidate retrieval.
Other ways to align representations, each with a cost: share item content features (titles, categories) across domains so item vectors are comparable without users; train a joint model with a shared user tower and separate item towers (a tower is one network that turns a user's or an item's features into a vector) when you can train on both domains together; or use distribution matching when no overlap users exist: make the cloud of mapped partner users look statistically like the cloud of target users, either by training a second network to tell them apart and pushing the map to fool it (adversarial), or by forcing their means and covariances to agree (moment matching), which is the weakest-supervised and least reliable setting.
The bridge on a hand-sized example
Take three partner categories (news, sport, cooking) and two-number target vectors. A cold user spent 60% of their partner views on news, 30% on sport and 10% on cooking, so xu=(0.6,0.3,0.1). Suppose the bridge matrix A has rows (0.2,1.0), (1.5,0.1) and (0.0,0.9). The mapped vector is the histogram times A, and each item is scored by a dot product with it. The program also fits a ridge bridge on four overlap users to show the closed form and checks that it is a minimum.
import numpy as np
# Partner site has 3 page categories (news, sport, cooking); the target model has 2-d item vectors.
# The bridge A maps a partner histogram (3 numbers) to a target taste vector (2 numbers).
A = np.array([[0.2, 1.0],
[1.5, 0.1],
[0.0, 0.9]])
x_u = np.array([0.6, 0.3, 0.1]) # cold user: 60% of views on news, 30% sport, 10% cooking
t_hat = x_u @ A # mapped target vector
items = {"item_a": np.array([0.1, 1.0]), "item_b": np.array([1.0, 0.0])}
print("mapped vector f(x_u) =", np.round(t_hat, 3))
for name, q in items.items():
print(f"score {name} = f(x_u) . q = {t_hat @ q:.3f}")
# The ridge bridge in closed form, on 4 overlap users with 3-category histograms and known 2-d target vectors.
X = np.array([[0.6, 0.3, 0.1], [0.1, 0.8, 0.1], [0.2, 0.2, 0.6], [0.5, 0.1, 0.4]])
T = np.array([[0.4, 1.0], [1.2, 0.2], [0.1, 0.9], [0.5, 0.8]])
lam = 1.0
A_ridge = np.linalg.solve(X.T @ X + lam * np.eye(3), X.T @ T)
print("\nridge bridge A = (X^T X + lam I)^-1 X^T T:\n", np.round(A_ridge, 3))
print("fit error on overlap users (sum of squared errors):", round(float(((X @ A_ridge - T) ** 2).sum()), 4))
# check the closed form really minimises the penalised objective: nudging A in any direction raises it
def objective(M):
return ((X @ M - T) ** 2).sum() + lam * (M ** 2).sum()
rng = np.random.default_rng(0)
worse = all(objective(A_ridge + 0.01 * rng.normal(size=A_ridge.shape)) > objective(A_ridge) for _ in range(100))
print("every one of 100 random nudges raises the penalised objective:", worse)
# What alpha does: correlation between a user's partner-site taste and target taste, 8-d, many users.
for alpha in (0.0, 0.5, 0.9):
z = rng.normal(size=(20000, 8))
zp = alpha * z + np.sqrt(1 - alpha ** 2) * rng.normal(size=z.shape)
corr = np.corrcoef(z[:, 0], zp[:, 0])[0, 1]
print(f"alpha {alpha}: correlation between the two tastes {corr:.2f}, share of partner-taste variance that is shared {alpha ** 2:.2f}")
Output:
mapped vector f(x_u) = [0.57 0.72]
score item_a = f(x_u) . q = 0.777
score item_b = f(x_u) . q = 0.570
ridge bridge A = (X^T X + lam I)^-1 X^T T:
[[0.23 0.569]
[0.584 0.224]
[0.112 0.453]]
fit error on overlap users (sum of squared errors): 1.2127
every one of 100 random nudges raises the penalised objective: True
alpha 0.0: correlation between the two tastes 0.00, share of partner-taste variance that is shared 0.00
alpha 0.5: correlation between the two tastes 0.50, share of partner-taste variance that is shared 0.25
alpha 0.9: correlation between the two tastes 0.90, share of partner-taste variance that is shared 0.81
Reading it: the mapped vector is 0.6⋅(0.2,1.0)+0.3⋅(1.5,0.1)+0.1⋅(0.0,0.9)=(0.57,0.72), so item_a with vector (0.1,1.0) scores 0.057+0.72=0.777 and item_b with vector (1.0,0.0) scores 0.570; this user is placed nearer item_a. The ridge solve gives the best matrix for the four overlap users under the penalty (the nudge test shows no nearby matrix does better), and the last block explains alpha: it is the correlation between a person's taste as seen on the partner site and their taste as seen in the target. At 0.9 the two sites are near mirrors of one person's taste (two shops selling similar goods); at 0.5 about a quarter of the partner-side variation is shared; at 0.0 the partner site says nothing about target taste (a recipe site against a banking app).
Worked experiment on synthetic data
Stand-in: the data are synthetic. Each user has an 8-dimensional latent taste. Their partner browsing is generated from a version of that taste correlated with it at level α (called alpha in the code), and their target clicks from the true taste plus an item popularity effect. The bridge is the ridge map above, fit on overlap users. The comparison is a popularity baseline on the same cold users. Metric: hit@10, the share of a user's 5 held-out target clicks that land in the top 10 recommended, averaged over 8 seeds.
How the generator works, in order: z is a user's true taste, 8 random numbers. zp is the taste as it shows on the partner site, alpha * z plus independent noise scaled so that the variance stays 1. Partner browsing is 20 page views, each page chosen with probability given by a softmax (exponentiate the scores W zp, then divide by their total so they sum to 1) and drawn with multinomial, which simply counts how many of the 20 views land on each page; dividing by 20 gives the histogram x. Target clicks are drawn in the same way from V z + pop, so they depend on the true taste and on a popularity effect; 15 clicks form the history that defines the overlap users' target vector (their mean item vector) and 5 are held out for scoring.
import numpy as np
D, N_TGT, N_PART = 8, 400, 300
K_HIST, TOP = 15, 10
N_COLD = 300
def run(seed, overlap, alpha):
rng = np.random.default_rng(seed)
V = rng.normal(size=(N_TGT, D)) # target item factors (known from the trained model)
pop = rng.normal(scale=1.0, size=N_TGT) # popularity bias per target item
W = rng.normal(size=(N_PART, D)) # partner-site item factors
def make_users(n):
z = rng.normal(size=(n, D)) # latent taste
zp = alpha * z + np.sqrt(1 - alpha**2) * rng.normal(size=(n, D)) # taste as seen on the partner site
# partner browsing: 20 page views drawn by softmax(W zp)
lp = zp @ W.T
pp = np.exp(lp - lp.max(1, keepdims=True)); pp /= pp.sum(1, keepdims=True)
x = np.stack([rng.multinomial(20, p) for p in pp]).astype(float)
x /= x.sum(1, keepdims=True)
# target behaviour: K_HIST clicks drawn by softmax(V z + pop)
lt = z @ V.T + pop
pt = np.exp(lt - lt.max(1, keepdims=True)); pt /= pt.sum(1, keepdims=True)
hist = [rng.choice(N_TGT, size=K_HIST, p=p) for p in pt]
heldout = [rng.choice(N_TGT, size=5, p=p) for p in pt]
return x, hist, heldout
x_o, hist_o, _ = make_users(overlap)
# target-side user vector for overlap users: least-squares fit of the user's clicks to item factors
T = np.stack([V[h].mean(0) for h in hist_o]) # mean factor of clicked items
lam = 1.0
A = np.linalg.solve(x_o.T @ x_o + lam * np.eye(N_PART), x_o.T @ T) # ridge map: partner histogram -> target vector
x_c, _, held_c = make_users(N_COLD)
pred = x_c @ A @ V.T # cold users: partner behaviour only
hit_map, hit_pop = [], []
pop_top = set(np.argsort(-pop)[:TOP])
for r in range(N_COLD):
top = set(np.argsort(-pred[r])[:TOP])
hit_map.append(np.mean([i in top for i in held_c[r]]))
hit_pop.append(np.mean([i in pop_top for i in held_c[r]]))
return np.mean(hit_map), np.mean(hit_pop)
print("hit@10 on 5 held-out clicks, mean over 8 seeds (cold users have partner data only)")
print("overlap alpha mapped popularity")
for overlap in (30, 300, 3000):
for alpha in (0.0, 0.5, 0.9):
res = np.array([run(s, overlap, alpha) for s in range(8)])
print(f"{overlap:7d} {alpha:5.1f} {res[:,0].mean():.3f} {res[:,1].mean():.3f}")
Output:
hit@10 on 5 held-out clicks, mean over 8 seeds (cold users have partner data only)
overlap alpha mapped popularity
30 0.0 0.075 0.119
30 0.5 0.109 0.121
30 0.9 0.239 0.122
300 0.0 0.068 0.132
300 0.5 0.154 0.117
300 0.9 0.389 0.124
3000 0.0 0.076 0.123
3000 0.5 0.191 0.122
3000 0.9 0.429 0.117
What the table shows (synthetic data, so the pattern matters, not the absolute values):
- With no shared taste (
alpha0.0) the mapped model scores 0.068 to 0.076, below popularity at 0.119 to 0.132, whatever the overlap size. This is negative transfer. The mapped scores also ignore popularity, which is why a blend with popularity is the safer production design. - With strong shared taste (
alpha0.9) the mapped model beats popularity, and more bridge users help: 0.239 with 30, 0.389 with 300 and 0.429 with 3000. - With moderate shared taste (
alpha0.5) the mapped model is below popularity at 30 overlap users (0.109 against 0.121) and above it at 300 and 3000 (0.154 and 0.191 against 0.117 and 0.122).
Failure modes
- Too few or unrepresentative bridge users. People who hold accounts on both sites differ from the cold users you want to serve (more engaged, different demographics), so the map fits them and generalizes poorly. Check: compare feature distributions of overlap versus cold users.
- Negative transfer. Browsing intent on a partner site (research, window shopping) may not predict target behaviour (purchases). Check: evaluate the mapped model against popularity on held-out overlap users per segment, and fall back when it loses.
- Distribution shift and drift. Partner catalogs, traffic mix and tracking rules change, so f goes stale. Monitor the input distribution and the mapped model's hit rate over time.
- Coverage and privacy. Only some cold users have partner data, matching depends on consented identity, and some jurisdictions restrict combining data across sites. The system must degrade gracefully to non-personalized ranking and honour deletion.
- Feedback contamination. Once cold users receive mapped recommendations, their clicks become training data biased toward what the map suggested. Log which source produced each recommendation and keep an exploration slice.
Putting it into the ranker
Use the mapped score as a feature with a confidence signal (number of partner events, bridge-model error on similar users). Blend with popularity and context in the ranking stage, and shift weight to the user's own target history as it accumulates (a few interactions already beat most cross-domain signals). Validate with an A/B test on new users only, with hit rate or downstream engagement over the first sessions as the metric.
Running the code
Python 3.12 with numpy installed, saved as cross_domain_cold_start.py; the hand-sized program (numpy only) is bridge_by_hand.py. Run each with python <file>. No downloads are needed.
Explain exposure bias and feedback loops in recommender systems: how they distort training and evaluation, and how you would mitigate and measure them.
Sample Answer
The idea in plain words
A recommender only observes feedback on what it shows. (The rule the live system used to decide what to show is its logging policy, written μ below.) Exposure bias is that selection effect: an item that was never shown has no clicks, and "no clicks" is not the same as "not liked". A feedback loop is what happens when the model is retrained on data its own earlier choices created: what it showed yesterday decides what it learns today, which decides what it shows tomorrow. Two failures follow. Training is distorted, because the labels are missing not at random (whether a label exists depends on what the system chose to show, not on chance, so the observed clicks are a skewed sample), so the model learns the logging policy's habits as if they were user taste. Evaluation is distorted, because a test set built from logged interactions can only reward recommendations of items that were already being shown.
How exposure bias distorts training
A click is the product of exposure and appeal:
P(click on item i)=P(shown)×P(click∣shown, item i)Appeal is the second factor, and it is only observable where the first factor was non-zero. Three consequences:
- Unseen items look worthless. If unobserved pairs are treated as negatives (the usual implicit-feedback setup), the model learns that items the old system rarely showed are bad.
- Counts reward past exposure. A model whose score tracks click counts, not clicks per impression, ranks by how often an item was shown. More exposure yields more clicks, which yields a higher score, and so on.
- Estimates are noisy for rarely shown items, so a few unlucky early impressions can bury a good item for good.
How it distorts evaluation
Offline metrics (hit rate or recall on held-out interactions) count a hit only when the recommended item appears in the logged test set. Items the old policy never showed cannot appear there, so a model that mimics the old policy scores well and a model that surfaces good new items scores poorly. The fix is counterfactual (off-policy) evaluation: estimating how a different policy would have performed using only logs written by another policy. With a logging policy that shows item a with probability μ(a∣x) in context x (the user and situation features at that moment), the inverse-propensity-scored (IPS) estimate of a new policy π's average reward is
V^(π)=n1i=1∑nμ(ai∣xi)π(ai∣xi)riwhere ri is the observed reward (for example a click) and n the number of logged events. It is unbiased only if μ>0 wherever π>0, which a purely greedy logger (one that always shows its current best guess) cannot satisfy, and it has high variance when μ is small. Both facts argue for logging some randomness.
IPS on numbers. The program below first applies the formula by hand to a four-event log (each event lists the probability μ that the logger showed the item it did show, the probability π that the new policy would have shown it, and whether it was clicked), then shows what goes wrong when the logger never shows an item the new policy wants (three items a, b and c; c is never logged).
import numpy as np
# Part 1: four logged events. mu = logger's probability of the shown item, pi = new policy's.
mu = np.array([0.5, 0.2, 0.5, 0.2])
pi = np.array([0.5, 0.5, 0.1, 0.5])
click = np.array([1, 0, 0, 1])
w = pi / mu
print("weights pi/mu:", w)
print("IPS estimate:", round(float((w * click).mean()), 4))
print("plain click rate of the log:", float(click.mean()))
# Part 2: item c has a true click rate of 0.6 but the logger never shows it (mu = 0).
true_ctr = np.array([0.1, 0.3, 0.6])
mu3 = np.array([0.7, 0.3, 0.0])
pi3 = np.array([0.2, 0.3, 0.5])
print("true value of the new policy:", round(float(pi3 @ true_ctr), 4))
rng = np.random.default_rng(0)
n = 200000
a_i = rng.choice(3, size=n, p=mu3)
r_i = rng.random(n) < true_ctr[a_i]
ips = (pi3[a_i] / mu3[a_i] * r_i).mean()
print("IPS estimate from the log:", round(float(ips), 4))
Output:
weights pi/mu: [1. 2.5 0.2 2.5]
IPS estimate: 0.875
plain click rate of the log: 0.5
true value of the new policy: 0.41
IPS estimate from the log: 0.1101
Reading it: in part 1 events the new policy likes more than the logger did (events 2 and 4, weight 2.5) count 2.5 times, an event it likes less (event 3, weight 0.2) counts one fifth, and only clicked events add anything, so the estimate is (1.0+0+0+2.5)/4=0.875, while the raw click rate of the log is 0.5. In part 2 the true value is 0.2⋅0.1+0.3⋅0.3+0.5⋅0.6=0.41, but item c never appears in the log, so its share of the new policy's value (0.30) is invisible and the estimate lands near 0.11 however much data you collect. That is the μ>0 condition in action: no weight can rescue an item with no logged events.
Worked example: the loop in a closed-loop simulation
40 items, each with a hidden true click probability when shown (drawn from a Beta(2, 8) distribution, a bell-like curve on 0 to 1 skewed toward small values, mean 0.2). Each round the system shows 5 items, each gets 500 impressions, and each impression is clicked independently with the item's probability, so the click count is a binomial draw. Three policies: click-count ranks by raw clicks so far; ctr ranks by smoothed clicks per impression, (clicks+1)/(impressions+10) (as if every item started with 1 click in 10 imaginary impressions, a prior of 0.1 that stops one lucky click on a single impression from ranking an item first); ctr+explore is the same but one of the five slots is a uniformly random item each round. "Value" is the true mean appeal of the final slate divided by that of the best possible 5-item slate. "Never shown" is the share of the 40 items with no impressions. "Best item shown" is the share of runs whose truly best item is in the final slate. Each cell averages 40 seeds, at three horizons (10, 50 and 400 rounds). The impression Gini is the inequality of impressions across items (0 if all 40 items get equal impressions, near 1 if a few get all). Concretely, 5 items sharing all impressions equally out of 40 gives exactly 1−5/40=0.875, the value the click-count rows show: it means the policy behaves as if only 5 items exist.
import numpy as np
N, SLOTS = 40, 5
def run(policy, T, seed):
rng = np.random.default_rng(seed)
appeal = rng.beta(2, 8, N) # each item's true click probability when seen
imp = np.zeros(N); clk = np.zeros(N)
for t in range(T):
if policy == "click-count":
score = clk + rng.random(N) * 1e-3 # ranks by raw clicks, ignores how often an item was shown
else:
score = (clk + 1) / (imp + 10) + rng.random(N) * 1e-6 # smoothed CTR: clicks per impression
shown = list(np.argsort(-score)[:SLOTS])
if policy == "ctr+explore":
shown[-1] = rng.integers(N) # the last slot is a uniformly random item
shown = list(dict.fromkeys(shown))
shown = np.array(shown)
imp[shown] += 500
clk[shown] += rng.binomial(500, appeal[shown])
top = np.argsort(-(clk + 1) / (imp + 10))[:SLOTS]
final_shown = np.argsort(-((clk + 1) / (imp + 10)))[:SLOTS]
share = np.sort(imp)[::-1] / imp.sum()
best = int(np.argmax(appeal))
return dict(value=appeal[final_shown].mean() / np.sort(appeal)[::-1][:SLOTS].mean(),
gini=((2*(np.arange(1,N+1)*np.sort(imp)).sum()/(N*imp.sum()))-(N+1)/N), unseen=(imp == 0).mean(), found=float(best in final_shown))
print(f"{'policy':14s} {'T':>5s} {'value vs best slate':>20s} {'impression Gini':>16s} {'never shown':>12s} {'best item shown':>16s}")
for policy in ["click-count", "ctr", "ctr+explore"]:
for T in [10, 50, 400]:
r = [run(policy, T, s) for s in range(40)]
print(f"{policy:14s} {T:5d} {np.mean([x['value'] for x in r]):20.3f} {np.mean([x['gini'] for x in r]):16.3f} "
f"{np.mean([x['unseen'] for x in r]):12.3f} {np.mean([x['found'] for x in r]):16.3f}")
Output:
policy T value vs best slate impression Gini never shown best item shown
click-count 10 0.544 0.875 0.875 0.175
click-count 50 0.540 0.875 0.875 0.175
click-count 400 0.539 0.875 0.875 0.175
ctr 10 0.590 0.870 0.826 0.225
ctr 50 0.590 0.874 0.826 0.225
ctr 400 0.590 0.875 0.826 0.225
ctr+explore 10 0.765 0.826 0.692 0.550
ctr+explore 50 0.947 0.749 0.250 0.850
ctr+explore 400 1.000 0.725 0.000 1.000
Reading it:
- Click-count locks in after the first slate: value 0.544, 0.540 and 0.539 at 10, 50 and 400 rounds, 87.5% of items never shown, and the best item is in the final slate in only 17.5% of runs. More data does not help, because the data come from the five items the policy already chose.
- Smoothed CTR (click-through rate, clicks per impression) fixes the unit (it normalizes by impressions) but is still greedy: value stays at 0.590 across horizons, and 82.6% of items are never shown. The prior of 0.10 for an unseen item sits below the smoothed rate of most items already on the slate, so an unseen item is ranked below them and is tried only when slate items sink under 0.10. Correcting the metric does not remove the selection effect.
- One random slot per round changes the trajectory: value 0.765 at 10 rounds, 0.947 at 50 and 1.000 at 400; never-shown falls to 0.250 and then 0; the best item is in the final slate in 55%, 85% and 100% of runs; the impression Gini falls from 0.826 to 0.725. The cost is visible too: one slot in five shows a random item, a price in short-term clicks that should be budgeted. (This simulation measures learning of item appeal, not user experience.)
Mitigation and how to measure it
| Mitigation | What it does | What to measure |
|---|---|---|
| Exploration slots, or a bandit (an algorithm that deliberately balances showing its best guess against trying uncertain items) that explores in proportion to uncertainty | Gives unseen or uncertain items impressions so their appeal can be estimated | Share of items with fewer than a minimum number of impressions; time to first estimate for a new item |
| Randomized holdout slice, small share of traffic | Provides unbiased appeal estimates and the propensities IPS needs | Rank correlation between exposure and holdout CTR |
| Train on click per impression, with propensity weights, not raw counts | Removes the exposure term from the label | Correlation between a model's score and an item's past exposure after controlling for holdout CTR |
| Freshness and decay | Stops old exposure from dominating forever | Age distribution of the recommended items |
| Diversity and calibration constraints in re-ranking | Caps how concentrated any slate can be | Head share, catalogue coverage, Gini over time |
| UX changes: separate "new" shelves, user controls | Creates exposure that is not driven by the model's own score | Share of interactions from non-model surfaces |
Start with the first three rows: exploration and a randomized slice are the two that create new information, and impression-normalized training with propensity weights removes the exposure term from the labels. The rest are cheaper supporting controls, and only exploration slots are demonstrated above.
To measure the loop itself, track exposure concentration (Gini, share of items below an impression floor; a rising Gini means exposure is concentrating onto fewer items) over time; concentration that keeps rising while the randomized-slice CTRs of the items stay unchanged points to the loop rather than to a change in user taste.
Common mistakes
- Evaluating a new model on logs of the old one and reading the number as a forecast.
- Normalizing by impressions but keeping a purely greedy policy, as the table shows.
- Adding exploration without logging the propensities, which makes later counterfactual evaluation impossible.
- Treating the loop as a data-quality bug: it is a property of the system, and it only goes away when the system changes what it shows.
Intuitively derive the O(log T) regret bound for UCB1. Which assumptions does it need, and where do they fail in practice?
Sample Answer
The idea
A multi-armed bandit has several options (arms, for example candidate items to show); each pull of an arm returns a random reward, and you want the most total reward over T pulls. Regret is the reward you gave up compared with always pulling the best arm. If arm i has mean reward μi, the best arm has mean μ∗, and the gap is Δi=μ∗−μi, then the expected regret after T rounds is
R(T)=i∑ΔiE[Ni(T)]where Ni(T) is the number of times arm i was pulled and E[⋅] is the expectation, the average over many repeated runs of the same experiment. So the whole analysis is about how often a bad arm can still be pulled.
UCB1 (upper confidence bound) plays, at round t, the arm maximising "average reward so far plus an uncertainty bonus":
indexi(t)=xˉi+ni2lntwith xˉi the average reward of arm i and ni the number of times it has been pulled. The idea is optimism under uncertainty: an arm with few pulls has a large bonus, so it gets tried; as it is pulled the bonus shrinks, and the arm stays in play only if its average is competitive. Regret is O(lnT) (read: it grows no faster than a constant times lnT, so doubling the horizon adds a fixed amount instead of doubling the regret): a bad arm is pulled about lnT/Δi2 times, which costs Δi per pull, so about lnT/Δi in total.
Intuitive derivation, in three steps
Step 1: the index is a valid upper bound almost always. If rewards lie in [0,1] and are independent draws with a fixed mean per arm, Hoeffding's inequality says the chance that an average of n draws exceeds its mean by ϵ is at most e−2nϵ2. In words: averages of many bounded draws stay close to their mean, and the chance of a large miss shrinks exponentially in the number of draws. With n=100 draws and ϵ=0.1 the bound is e−2=0.135. With ϵ=2lnt/n this is e−4lnt=t−4. So at round t the true mean of any arm sits below its index with probability at least 1−t−4, and the mean of a pulled arm sits within its bonus of its average, again except with probability on the order of t−4. For a feel for the bonus, at t=100 an arm pulled 10 times has bonus 2ln100/10=0.960 and one pulled 100 times has bonus 0.303: pulling an arm shrinks its bonus, while time passing slowly raises it for arms that are ignored.
Step 2: a bad arm can only be chosen while it is under-explored. On the good event where all indices are valid, arm i is chosen only if its index is at least the best arm's index, and the best arm's index is at least μ∗. The index of arm i is its average plus its bonus. On the good event the average is within one bonus of the true mean (xˉi≤μi+2lnt/ni), so the index is at most μi+22lnt/ni: the factor 2 is one bonus from the index itself plus one from the estimation error. So choosing arm i requires μ∗≤μi+22lnt/ni, that is
ni≤Δi28lntOnce an arm has been pulled more than 8lnT/Δi2 times, it can be chosen again only on a bad event.
Step 3: add up the bad events. Each bad event has probability of order t−4 at round t for a given pull count. A union over the at most t possible pull counts makes it at most t⋅t−4=t−3 per round and per arm. The sum ∑t≥1t−3 converges: the program below finds 1.2021 for the first million rounds and 1.2020 for the first hundred, so almost all of it comes from the first few rounds. Two such events per round give about 2.4 in this simplified accounting, a constant that does not depend on T, which is the point: later rounds almost never add bad events. Hence
E[Ni(T)]≤Δi28lnT+C,R(T)≤i:Δi>0∑(Δi8lnT+CΔi)with C a constant free of T (the original analysis of Auer, Cesa-Bianchi and Fischer works out an explicit one with the details this sketch skips). Two things to notice: small gaps are expensive (1/Δi), and the regret is logarithmic because the bonus grows only with lnt while each pull shrinks it like 1/ni.
The numbers behind the proof, and one arm by hand
The program computes the Hoeffding bound for one concrete case, the bonus at a few points, the sum from Step 3, and the threshold for one arm. For an arm with gap 0.2 and T=1000 the threshold is 8ln1000/0.22=1381.6 pulls, which would cost at most 0.2×1381.6=276.3 regret. The simulation in the next section measures 113.7 pulls for that arm (a regret of 22.7), about twelve times fewer than the threshold: the proof must hold for every set of arms and every unlucky stretch of draws, so its constant 8 is a worst-case ceiling.
import numpy as np
# Hoeffding: chance that the average of n draws in [0, 1] exceeds its mean by eps is at most exp(-2 n eps^2)
n, eps = 100, 0.1
print(f"Hoeffding bound, n={n}, eps={eps}: {np.exp(-2 * n * eps ** 2):.3f}")
# The UCB1 bonus sqrt(2 ln t / n) at a few points, and the failure probability it buys: t^-4
for t, n_i in [(100, 10), (100, 100), (1000, 10)]:
bonus = np.sqrt(2 * np.log(t) / n_i)
print(f"t={t:<5d} n_i={n_i:<4d} bonus={bonus:.3f} failure probability t^-4 = {t ** -4.0:.0e}")
# Step 3: why the bad events add up to a constant. At round t, one index is invalid with probability at most
# t * t^-4 = t^-3 (a union over the t possible pull counts). Sum over all rounds:
rounds = np.arange(1, 1_000_001, dtype=float)
total = np.sum(rounds ** -3.0)
print(f"sum over rounds of t^-3 (1 to 1,000,000): {total:.4f}; with 2 such events per round: {2 * total:.3f}")
print(f"the same sum up to t=100: {np.sum(rounds[:100] ** -3.0):.4f}")
# One arm by hand: gap 0.2, T = 1000
gap, T = 0.2, 1000
thr = 8 * np.log(T) / gap ** 2
print(f"\ngap {gap}, T={T}: threshold 8 ln T / gap^2 = {thr:.1f} pulls; worst-case regret from this arm = {gap * thr:.1f}")
print(f"measured mean pulls of this arm at T={T} (table below): 113.7, regret from it = {gap * 113.7:.1f}")
Output:
Hoeffding bound, n=100, eps=0.1: 0.135
t=100 n_i=10 bonus=0.960 failure probability t^-4 = 1e-08
t=100 n_i=100 bonus=0.303 failure probability t^-4 = 1e-08
t=1000 n_i=10 bonus=1.175 failure probability t^-4 = 1e-12
sum over rounds of t^-3 (1 to 1,000,000): 1.2021; with 2 such events per round: 2.404
the same sum up to t=100: 1.2020
gap 0.2, T=1000: threshold 8 ln T / gap^2 = 1381.6 pulls; worst-case regret from this arm = 276.3
measured mean pulls of this arm at T=1000 (table below): 113.7, regret from it = 22.7
Worked example
Four Bernoulli arms (reward 1 with probability μi, else 0) with means 0.7, 0.6, 0.5 and 0.4, so the gaps are 0.1, 0.2 and 0.3. UCB1 runs 300 times in parallel with different random draws; the program prints the average number of pulls of each suboptimal arm against the threshold 8lnT/Δi2, the average regret at doubling horizons, and then a second experiment where the assumptions fail: at round 8000 the arms' means are reversed, with the regret of each 4000-round window printed next to the same window of the run without a reversal.
import numpy as np
MEANS = np.array([0.7, 0.6, 0.5, 0.4]) # Bernoulli arms in [0, 1]; arm 0 is best
GAPS = MEANS[0] - MEANS
K, SEEDS = len(MEANS), 300
def ucb1(means_at, T, seed):
"""UCB1: play argmax of (empirical mean + sqrt(2 ln t / pulls)). means_at(t) gives the arm means at time t."""
rng = np.random.default_rng(seed)
n = np.zeros((SEEDS, K)); s = np.zeros((SEEDS, K)); rows = np.arange(SEEDS)
pulls_at = {0: np.zeros(K)}
for t in range(1, T + 1):
a = np.full(SEEDS, t - 1) if t <= K else (s / n + np.sqrt(2 * np.log(t) / n)).argmax(axis=1)
r = (rng.random(SEEDS) < means_at(t)[a]).astype(float)
n[rows, a] += 1; s[rows, a] += r
pulls_at[t] = n.mean(axis=0).copy()
return pulls_at
T_LIST = [1000, 2000, 4000, 8000, 16000, 32000]
pulls = ucb1(lambda t: MEANS, T_LIST[-1], 0)
print("stationary arms: mean number of pulls of each suboptimal arm vs the threshold 8 ln(T) / gap^2")
print("T arm gap mean pulls threshold")
for T in T_LIST:
if T not in (1000, 8000, 32000):
continue
for i in (1, 2, 3):
print(f"{T:<7d} {i} {GAPS[i]:.1f} {pulls[T][i]:9.1f} {8 * np.log(T) / GAPS[i] ** 2:9.1f}")
reg = [float(np.dot(GAPS, pulls[T])) for T in T_LIST]
print("T mean regret added since the previous (half as long) horizon")
for k, T in enumerate(T_LIST):
print(f"{T:<6d} {reg[k]:11.1f} " + ("-" if k == 0 else f"{reg[k] - reg[k-1]:.1f}"))
# assumption failure: the best arm changes at t = 8000 (arm 3 becomes the best, arm 0 the worst)
def drifting(t):
return MEANS if t <= 8000 else MEANS[::-1]
p = ucb1(drifting, 32000, 0)
def regret_between(q, t0, t1, switched):
"""Regret in rounds t0+1..t1 against the best arm of that period, from the change in mean pull counts."""
d = q[t1] - q[t0]
best = MEANS[::-1] if (switched and t1 > 8000) else MEANS
return float(np.sum(d * (best.max() - best)))
print("\nbest arm switches at t = 8000; regret accrued in each window against that window's best arm")
print("window with the switch same rounds, no switch")
for t0 in range(0, 32000, 4000):
t1 = t0 + 4000
print(f"rounds {t0:5d}-{t1:5d}: {regret_between(p, t0, t1, True):12.1f} {regret_between(pulls, t0, t1, False):12.1f}")
Output:
stationary arms: mean number of pulls of each suboptimal arm vs the threshold 8 ln(T) / gap^2
T arm gap mean pulls threshold
1000 1 0.1 227.7 5526.2
1000 2 0.2 113.7 1381.6
1000 3 0.3 68.2 614.0
8000 1 0.1 787.6 7189.8
8000 2 0.2 283.7 1797.4
8000 3 0.3 143.4 798.9
32000 1 0.1 1317.8 8298.8
32000 2 0.2 404.5 2074.7
32000 3 0.3 191.6 922.1
T mean regret added since the previous (half as long) horizon
1000 66.0 -
2000 98.2 32.2
4000 137.3 39.1
8000 178.5 41.3
16000 222.9 44.4
32000 270.1 47.3
best arm switches at t = 8000; regret accrued in each window against that window's best arm
window with the switch same rounds, no switch
rounds 0- 4000: 137.3 137.3
rounds 4000- 8000: 41.3 41.3
rounds 8000-12000: 58.8 26.1
rounds 12000-16000: 42.9 18.2
rounds 16000-20000: 55.2 14.1
rounds 20000-24000: 44.8 12.5
rounds 24000-28000: 35.6 11.0
rounds 28000-32000: 28.7 9.6
Reading it:
- The threshold is a ceiling, not a prediction. At T=32000 the arm with gap 0.1 was pulled 1317.8 times on average against a threshold of 8298.8. The constant 8 comes from worst-case reasoning, so real pull counts sit well below it.
- Regret grows slowly. Doubling T from 1000 to 32000 adds 32.2, 39.1, 41.3, 44.4 and 47.3 to the average regret. A policy with linear regret would roughly double the total at every doubling; here the total rises by about a fifth (222.9 to 270.1 from 16000 to 32000), so regret is clearly sublinear. The added amounts are still creeping upward at the largest horizon rather than sitting at one constant, which is what a pre-asymptotic stretch looks like: the logarithmic rate describes the long run, and six horizons cannot pin it down or show where it settles.
- A reversal costs regret that decays slowly. After the means are reversed at round 8000, the next 4000 rounds add 58.8 regret (measured against the new best arm), and the later windows add between 28.7 and 55.2, against 9.6 to 26.1 for the same rounds in the run without a reversal. UCB1 does recover (the window regret falls from 58.8 to 28.7 by the end), but it stays well above the stationary rate through round 32000, because the averages of the formerly good arms were built over thousands of pulls and change slowly. Its guarantee was never about a moving best arm, and windowed or discounted statistics are the usual repair. A slower or smaller drift was not run.
Assumptions and where they fail
- Bounded rewards (or at least light tails), so Hoeffding applies. Revenue per session or dwell time has heavy tails, so the bonus is too small and the algorithm under-explores; use a rescaled or robust index.
- Stationary arms: each arm's mean never changes. Click rates drift with time of day, season and novelty. Windowed or discounted averages are the usual repair.
- Independent draws: outcome of one pull tells you nothing about the next beyond the arm mean. Repeated impressions to one user, or interference between users, break this.
- Immediate feedback: the counts ni are up to date. With delayed conversions or batched updates the algorithm acts on stale counts and picks the same arm for a whole batch.
- No context and a small fixed arm set: with a very large catalog every arm needs about lnT/Δ2 pulls just to be ruled out, and with user features you want a contextual method (for example a linear UCB) instead.
Pitfalls
- Treating 8lnT/Δ2 as an accurate count of bad pulls (see the output).
- Forgetting that the bound depends on the gaps: the 1/Δi term in the bound grows as an arm gets closer to the best one, so near-ties need many pulls to separate even though each wrong pull costs little.
- Tuning the bonus scale down for speed and still quoting the guarantee; the proof needs the stated bonus.
Running the code
Use Python 3.12 with numpy 2.1.3. Save each listing to a file and run it with python; seeds are fixed and each program takes a few seconds.
Derive the inverse propensity scoring estimator for the value of a new policy from logged bandit feedback, and discuss its bias and variance behavior.
Sample Answer
Direct answer
Logged bandit feedback is a set of tuples (context x, action a, reward r, propensity p) collected while an older logging policy π0 chose the actions. The inverse propensity scoring (IPS) estimator for a new policy π is the average of r⋅π(a∣x)/π0(a∣x). The derivation is a change of measure (rewriting an average taken under one probability distribution as an average under another, paying for the switch with a ratio of probabilities): the expectation of reward under π equals the expectation under π0 of the reward times the ratio of the two action probabilities. It is unbiased whenever π0 gives non-zero probability to every action π can take, and its variance is n1(E[w2r2]−V2), which grows with the second moment (the average of the square, E[w2r2]) of the importance weight w=π/π0 and therefore explodes when the logger rarely shows what the new policy likes.
Derivation
Setup. Contexts x∼P(x). The logger draws a∼π0(⋅∣x). The reward distribution given (x,a) has mean m(x,a)=E[r∣x,a]. The value of a policy π is the expected reward when it acts:
V(π)=Ex[a∑π(a∣x)m(x,a)]Step 1: multiply and divide inside the sum by π0(a∣x), allowed wherever π0(a∣x)>0 (this is the positivity assumption: if π(a∣x)>0 then π0(a∣x)>0, otherwise terms are missing):
V(π)=Ex[a∑π0(a∣x)π0(a∣x)π(a∣x)m(x,a)]Step 2 has three small moves, taken one at a time.
(2a) A sum of the form ∑aπ0(a∣x)f(a) is by definition the average of f when the action is drawn from π0(⋅∣x). Here f(a)=w(x,a)m(x,a) with w(x,a)=π(a∣x)/π0(a∣x), so
V(π)=ExEa∼π0(⋅∣x)[w(x,a)m(x,a)](2b) m(x,a)=E[r∣x,a] is the average reward once the context and action are fixed. Once they are fixed, w(x,a) is just a number, and a constant can be moved inside an average, so w(x,a)m(x,a)=E[w(x,a)r∣x,a]. This is the step that lets the observed reward r stand in for its mean m.
(2c) Averaging an average over the remaining randomness gives the average over the whole logged process (the law of total expectation: the mean of the conditional means is the overall mean):
V(π)=Ex,a∼π0,r[w(x,a)r]Step 3: replace the expectation with the sample mean over the log:
V^IPS=n1i=1∑nπ0(ai∣xi)π(ai∣xi)riBecause each term has expectation V(π) and the rows are independent and identically distributed (i.i.d.: each row is drawn separately from the same process), E[V^IPS]=V(π) exactly. Nothing about the reward model was assumed.
The same two forms of V, and three logged rows, as numbers. The setup is the one used later: three user segments, three videos, mean watch times m in seconds, an epsilon-greedy logger (with probability ϵ it picks a video uniformly at random, otherwise it shows video 0, so video 0 has propensity 1−ϵ+ϵ/3 and the others ϵ/3), here with ϵ=0.2. The last lines check the gamma second moment used later: a gamma distribution with shape k and mean m is a right-skewed positive distribution with variance m2/k, so E[r2]=m2/k+m2=m2(1+1/k).
import numpy as np
p_x = np.array([0.5, 0.3, 0.2])
m = np.array([[40.0, 90.0, 60.0], [70.0, 30.0, 80.0], [50.0, 55.0, 120.0]]) # mean watch seconds
pi_new = np.array([[0.1, 0.8, 0.1], [0.1, 0.1, 0.8], [0.1, 0.1, 0.8]])
eps = 0.2
pi0 = np.full((3, 3), eps / 3); pi0[:, 0] += 1 - eps # 0.8667 on video 0, 0.0667 elsewhere
w = pi_new / pi0
# Step 1 and 2 as sums: the same number from the target form and from the logger form
target_form = (p_x[:, None] * pi_new * m).sum()
logger_form = (p_x[:, None] * pi0 * w * m).sum()
print(f"V = sum_x P(x) sum_a pi(a|x) m(x,a) = {target_form:.4f}")
print(f" = sum_x P(x) sum_a pi0(a|x) w(x,a) m(x,a) = {logger_form:.4f}")
print("weights w(x,a) = pi/pi0:")
print(np.round(w, 3))
# Three logged rows (segment, shown video, watch seconds) and their IPS terms
rows = [(0, 1, 95.0), (1, 0, 65.0), (2, 2, 130.0)]
print("\nrow segment video watch pi0 pi weight w*watch")
terms = []
for k, (x, a, r) in enumerate(rows):
terms.append(w[x, a] * r)
print(f"{k:3d} {x:7d} {a:5d} {r:5.0f} {pi0[x, a]:.4f} {pi_new[x, a]:.2f} {w[x, a]:6.3f} {w[x, a] * r:8.2f}")
print(f"mean of the three terms = {np.mean(terms):.2f} seconds (true value {target_form:.2f}; three rows are far too few)")
# Gamma with shape k and mean m: variance m^2 / k, so E[r^2] = m^2/k + m^2
k = 2.0
rng = np.random.default_rng(0)
draws = rng.gamma(k, 60.0 / k, size=1_000_000)
print(f"\ngamma shape 2, mean 60: sample mean {draws.mean():.2f}, sample E[r^2] {np.mean(draws ** 2):.0f}, formula m^2(1+1/k) = {60.0 ** 2 * (1 + 1 / k):.0f}")
V = sum_x P(x) sum_a pi(a|x) m(x,a) = 84.5000
= sum_x P(x) sum_a pi0(a|x) w(x,a) m(x,a) = 84.5000
weights w(x,a) = pi/pi0:
[[ 0.115 12. 1.5 ]
[ 0.115 1.5 12. ]
[ 0.115 1.5 12. ]]
row segment video watch pi0 pi weight w*watch
0 0 1 95 0.0667 0.80 12.000 1140.00
1 1 0 65 0.8667 0.10 0.115 7.50
2 2 2 130 0.0667 0.80 12.000 1560.00
mean of the three terms = 902.50 seconds (true value 84.50; three rows are far too few)
gamma shape 2, mean 60: sample mean 60.07, sample E[r^2] 5414, formula m^2(1+1/k) = 5400
Reading it: the target form and the logger form of V give the same 84.5000 seconds, which is Step 1 and Step 2 checked on numbers. The weight matrix shows where the trouble sits: 12 for the two videos per segment that the new policy favours but the logger rarely shows, 0.115 for video 0. In the three rows, rows 0 and 2 are favourite videos with weight 12, so each contributes more than a thousand to the sum, while row 1 contributes 7.5; their mean, 902.50, is wildly off the true 84.50, which shows what the variance formula means: with so few rows a single heavy-weight row decides the answer, and the average only converges because many rows are used. The simulated second moment of a gamma(shape 2, mean 60) matches the formula (5414 against 5400).
Bias and variance
Bias. Zero under positivity and correct propensities. If positivity fails, the estimator is missing the terms where π0=0 and its bias is −∑xP(x)∑a:π0(a∣x)=0π(a∣x)m(x,a). If the stored propensities are wrong (say π~0), the mean is E[πr/π~0] and is biased in whichever direction the error pushes the weights.
Variance. One row has variance E[w2r2]−V2 (the mean of the square minus the square of the mean; the mean of one row is V). To turn E[w2r2] into a sum over actions, apply the same steps as in Step 2: the action is drawn from π0, so E[w2r2]=Ex∑aπ0(a∣x)w(x,a)2E[r2∣x,a], and π0w2=π0π2/π02=π2/π0. Dividing by n for the average of n independent rows, the average of n rows has
Var(V^IPS)=n1(Ex[a∑π0(a∣x)π(a∣x)2E[r2∣x,a]]−V(π)2)The term π2/π0 is the culprit: halving π0 at an action the new policy favours doubles its contribution to the variance. This is why the estimate is trustworthy for policies close to the logger and noisy for ones that differ a lot, and why the number of logged rows needed scales with E[w2], not with n alone.
Clipping. Capping the weight at M gives V^M=n1∑min(wi,M)ri with bias E[(min(w,M)−w)r]. For non-negative rewards this bias is non-positive (the estimate is pessimistic), and it shrinks to zero as M grows.
Continuous rewards such as watch time
The derivation never used that r is 0/1. Any real-valued reward works because only E[r∣x,a] appears. The log schema needs four fields per impression: the context (for example the user segment), the shown video, the watch time in seconds, and the logged probability of that video. What changes in practice is the second moment E[r2∣x,a] in the variance, which is large for long-tailed watch times, so the same weights hurt more than for clicks. Common remedies are to cap the watch time at a business-meaningful ceiling and to use the variance-reducing estimators: self-normalised IPS (SNIPS, which divides ∑wiri by ∑wi instead of n, trading a small bias for a steadier estimate) and doubly robust (DR, which fits a reward model and uses it as a baseline, then applies IPS only to the model's errors on the logged rows, so large weights multiply small residuals).
Checking the formulas on numbers
Three user segments (probabilities 0.5, 0.3, 0.2), three videos, and watch time drawn from a gamma distribution with shape 2 (so E[r2]=m2(1+1/2)) and a mean m(x,a) in seconds. The logger is epsilon-greedy around video 0. The new policy puts 0.8 on one video per segment and 0.1 on the others. The program computes the exact variance and the exact clipping bias from the formulas above, and compares the exact variance and mean with the empirical ones over 2000 simulated logs of 3000 rows. In the printed table, exact_std is one-row variance/n from the formula and empirical_std is the standard deviation of the 2000 simulated estimates. This is a synthetic setup with a known reward distribution; with real logs only the empirical side is available.
import numpy as np
# Logged schema: (user_segment x, shown_video a, watch_seconds r, propensity pi0(a|x)).
# Three segments, three videos; watch time is Gamma(shape 2) with mean m[x, a] seconds.
p_x = np.array([0.5, 0.3, 0.2])
m = np.array([[40.0, 90.0, 60.0],
[70.0, 30.0, 80.0],
[50.0, 55.0, 120.0]])
shape = 2.0
second_moment = m ** 2 * (1 + 1 / shape) # E[r^2 | x, a] for a gamma with this shape
pi_new = np.array([[0.1, 0.8, 0.1],
[0.1, 0.1, 0.8],
[0.1, 0.1, 0.8]])
def make_logging(eps):
pi0 = np.full((3, 3), eps / 3)
pi0[:, 0] += 1 - eps # epsilon-greedy around video 0
return pi0
def exact(pi0, clip=None):
w = pi_new / pi0
wc = w if clip is None else np.minimum(w, clip)
value = float((p_x[:, None] * pi_new * m).sum())
mean_est = float((p_x[:, None] * pi0 * wc * m).sum())
var_one = float((p_x[:, None] * pi0 * wc ** 2 * second_moment).sum()) - mean_est ** 2
return value, mean_est, var_one
def simulate(pi0, n, rng, clip=None):
x = rng.choice(3, size=n, p=p_x)
a = (rng.random(n)[:, None] > np.cumsum(pi0[x], axis=1)).sum(axis=1)
r = rng.gamma(shape, m[x, a] / shape)
w = pi_new[x, a] / pi0[x, a]
if clip is not None:
w = np.minimum(w, clip)
return np.mean(w * r)
n, runs = 3000, 2000
rng = np.random.default_rng(0)
print("eps exact_std empirical_std exact_mean empirical_mean")
for eps in [0.5, 0.2, 0.05]:
pi0 = make_logging(eps)
value, mean_est, var_one = exact(pi0)
est = np.array([simulate(pi0, n, rng) for _ in range(runs)])
print(f"{eps:<5} {np.sqrt(var_one / n):9.3f} {est.std():13.3f} {mean_est:10.3f} {est.mean():14.3f}")
print(f"true value V(new policy) = {value:.3f} seconds")
pi0 = make_logging(0.05)
print("clip exact_bias exact_std")
for clip in [None, 20.0, 8.0, 3.0]:
value, mean_est, var_one = exact(pi0, clip)
print(f"{str(clip):<6} {mean_est - value:+10.3f} {np.sqrt(var_one / n):9.3f}")
Output:
eps exact_std empirical_std exact_mean empirical_mean
0.5 3.836 3.866 84.500 84.342
0.2 6.350 6.212 84.500 84.166
0.05 12.975 13.349 84.500 84.853
true value V(new policy) = 84.500 seconds
clip exact_bias exact_std
None +0.000 12.975
20.0 -43.400 5.455
8.0 -62.000 2.317
3.0 -72.250 0.910
The empirical standard deviation matches the exact one at each logging randomness level, and the empirical mean matches the exact mean of 84.500 seconds, which equals the true value of the new policy: that is the unbiasedness result checked on data. The standard deviation grows from 3.836 to 12.975 seconds as the exploration rate ϵ falls from 0.5 to 0.05, a factor of about 3.4, because the propensity of the favoured videos falls from 0.167 to 0.017. The clipping rows (on the ϵ=0.05 logger) show the trade: a cap of 20 cuts the standard deviation from 12.975 to 5.455 but costs 43.400 seconds of bias, and a cap of 3 leaves a bias of 72.250 seconds. The caps here are far below the weights the favoured actions carry, so the bias is large; a cap should be chosen from the weight distribution and checked against unclipped and self-normalised estimates.
When does a cap help? In the run above the weights that carry the value are all large (the favoured videos have weight 48 on the 0.05 logger), so every cap shown cuts into signal. A cap helps when the large weights belong to rarely logged actions that add noise but little value. The next program (exact formulas again) adds a fourth video, shown by the logger with probability 0.0002 and by the new policy with probability 0.10, so its weight is 500; its mean watch time is a short 20 seconds.
import numpy as np
# Four videos. Video 3 is almost never logged (propensity 0.0002) and the new policy would show it 10% of the time,
# so its weight is 500; its watch time is short, so those rows add noise but little value.
p_x = np.array([0.5, 0.3, 0.2])
m = np.array([[40.0, 90.0, 60.0, 20.0], [70.0, 30.0, 80.0, 20.0], [50.0, 55.0, 120.0, 20.0]])
second_moment = m ** 2 * 1.5 # gamma with shape 2
pi0 = np.tile([0.80, 0.10, 0.0998, 0.0002], (3, 1))
pi_new = np.tile([0.30, 0.30, 0.30, 0.10], (3, 1))
n = 3000
value = float((p_x[:, None] * pi_new * m).sum())
print(f"true value {value:.3f} s; largest weight {np.max(pi_new / pi0):.0f}")
print("cap M exact_bias exact_std exact_rmse")
for cap in [None, 500.0, 50.0, 20.0, 10.0, 5.0, 2.0]:
w = pi_new / pi0 if cap is None else np.minimum(pi_new / pi0, cap)
mean_est = float((p_x[:, None] * pi0 * w * m).sum())
var_one = float((p_x[:, None] * pi0 * w ** 2 * second_moment).sum()) - mean_est ** 2
bias, std = mean_est - value, np.sqrt(var_one / n)
print(f"{str(cap):7s} {bias:+10.3f} {std:9.3f} {np.hypot(bias, std):10.3f}")
true value 60.200 s; largest weight 500
cap M exact_bias exact_std exact_rmse
None +0.000 3.760 3.760
500.0 +0.000 3.760 3.760
50.0 -1.800 2.076 2.748
20.0 -1.920 2.057 2.814
10.0 -1.960 2.055 2.840
5.0 -1.980 2.054 2.853
2.0 -16.323 1.348 16.379
Reading it: with no cap, the exact standard deviation is 3.760 seconds. Caps from 50 down to 5 give up 1.8 to 2.0 seconds of bias but cut the standard deviation to about 2.05 to 2.08, so the root mean squared error (the combined miss, bias2+std2) falls from 3.760 to between 2.748 and 2.853, about a quarter lower. A cap of 2 clips the ordinary weight of 3 as well and the bias jumps to -16.3 seconds. So clipping is the right tool when a few rows with huge weights dominate and their actions matter little, and the wrong one when the cap sits below the weights that carry the gain. On real logs you do not know the true value, so sweep the cap, watch the estimate and its bootstrap interval, and keep the cap above the bulk of the weights.
Pitfalls
- Using π in the denominator, or the greedy-action probability for every row, instead of the stored π0(ai∣xi).
- Claiming unbiasedness when positivity fails or when the propensity was logged before a re-ranking or filtering step.
- Quoting the standard error of the weighted mean as if the weights were fixed: when E[w2] is large the normal approximation (the bell-curve shortcut for how the estimate varies) is poor, so bootstrap (recompute the estimate on many resamples of the rows, drawn with replacement, and read the interval from their spread) and report the effective sample size, (∑iwi)2/∑iwi2, the number of equally weighted rows that would give the same precision (it is far below n when a few weights dominate).
- Applying a high weight cap and calling the result unbiased.
Unlock Full Question Bank
Get access to all 20 Recommendation, Ranking, and Personalization interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.