Contextual bandits: LinUCB, linear Thompson sampling and off-policy evaluation
Contextual bandits learn policies whose best action varies with context. Derive LinUCB and elliptical potential, examine linear Thompson sampling, and evaluate logged policies using DM, IPS, SNIPS, and doubly robust estimation.
After this lesson you can
- Formulate personalized decisions as contextual bandits with policy-class regret.
- Implement LinUCB and linear Thompson sampling with rank-one updates.
- Prove the elliptical potential lemma and obtain LinUCB regret order.
- Estimate logged-policy value using DM, IPS, SNIPS, and doubly robust methods.
- Design propensity logging for future policy evaluation.
Before you start
A different action for every context
The previous lesson had a fixed best arm. A recommender receives session information before selecting an article: the best article can change by context. A rule maximizing the global average may ignore a useful alternative for a small group. In a contextual bandit, observe , choose , and receive only that action’s reward.
A policy assigns probabilities to available actions. If and contexts are i.i.d. from a stable distribution, its value is
A learned policy can be compared with the best in class ; comparison with the best action in every context needs a stronger reference. Under a realizable linear model and finite available actions, the best contextual policy chooses a maximum of its true predicted mean reward. With adaptive contexts or drift, redefine reference and assumptions: dynamic regret against each round’s best action is not automatically stationary regret in the following theorem.
Ridge and optimism in a direction
Assume feature vector for each context–action pair, and . For earlier observations, with ,
Regularization makes positive definite even before data. The LinUCB index chooses a maximum of
The first part estimates reward and the second is larger in poorly observed directions. If the true parameter lies in ellipsoid , Cauchy–Schwarz in dual norms shows the maximum of over that set is exactly the index. An chosen for convenience draws an ellipsoid and defines a policy, but is not itself a statistical guarantee.
Preparing the ellipsoid.
For a correct linear model, bounded-norm adaptive features, conditionally centered -subgaussian noise, and , one simultaneous confidence construction uses, with probability at least ,
Conditions and proof appear in Abbasi-Yadkori, Pál and Szepesvári. Simultaneous confidence supports adaptive actions under those assumptions; it does not guarantee coverage if the model changes or noise violates them.
Update without inverting from scratch
After observing and , and . Since is invertible, Sherman–Morrison gives
The denominator is positive. The rank-one update avoids cubic inversion each round; a Cholesky factor can improve numerical stability. Disjoint LinUCB maintains one vector and matrix per action. A hybrid variant adds shared and action-specific parameters with cross terms; it is not equivalent to fitting two independent regressions and ignoring their covariances.
Elliptical potential and exploration cost
Let denote the actually chosen vector. The matrix determinant lemma gives . Since for , the elliptical potential lemma states
if and . The last inequality applies arithmetic versus geometric means to eigenvalues and uses . Clipping does not vanish without another assumption.
For example, if , then . On the confidence event, optimism and index selection imply instantaneous regret at most . Cauchy–Schwarz and the lemma give
With fixed parameters and confidence, its usual order is , with remaining dependencies in constants and logarithms. This derivation concerns the shared model and high-probability event described. Disjoint parameters, nonlinear rewards, or drift need their own assumptions and analysis.
Alternatives and a changing environment
In linear Thompson sampling, draw a parameter from its posterior and choose the optimal action for that sample. A normal prior and normal likelihood with known variance yield a conjugate normal posterior. If reward is a Bernoulli click, a normal parameter distribution may be useful approximation, but is not the exact conjugate posterior for that model. Contextual -greedy uses the estimator for prediction and retains random exploration.
A neural representation with Bayesian last layer or ensemble is another option. Their uncertainty depends on training and calibration; they do not automatically inherit the linear guarantee. Riquelme and colleagues compare variants across datasets, not establish a universal winner.
Preparing the reproducible recommender.
What can be learned from logs
Now suppose logs , where is the true probability with which the logging policy chose the action. If logging depends on history, that probability must also condition on information available at decision time. Record eligible distribution, policy version, and effective propensity after filters and business rules; a probability before those filters may be incorrect.
Without that information, propensity can sometimes be reconstructed from a known policy, and the direct method can still be used with model assumptions. But if the target policy chooses an action with positive probability where the logging policy never chooses it, its general value is not identified from those data alone. Support means whenever in relevant contexts. Very small support is not zero: it identifies in principle but can cause enormous variance.
With i.i.d. logs, well-defined rewards, and support, the inverse propensity scoring estimator is
Condition on and sum over logged action: distribution factor cancels the denominator, leaving . Thus IPS is unbiased for a fixed target policy and correct propensities. If has finite second moment, its variance is
Sums in these formulas are restricted to actions with ; when both and are zero, their contribution is zero and ratio is not evaluated. Division by uses independent logs. Small logging probability amplifies the second moment. Weight clipping reduces rare-record influence but generally introduces bias and must be declared. If the target is trained and evaluated on the same sample, the proof does not apply without controlling dependence.
Four estimators and their limits
The direct method (DM) learns predictor and averages . It may have low variance but depends on model quality, particularly when extrapolating rarely observed actions. SNIPS divides the weighted reward sum by the weight sum. It often stabilizes scale, but the ratio is generally biased in finite samples and undefined when weights sum to zero.
The doubly robust estimator combines a prediction for all actions with a residual for the observed action:
For models fixed independently of evaluation data, conditional bias at is , with positive denominators for those actions. It vanishes if propensity or reward model is correct. Separate training and evaluation, or cross-fitting, avoids assuming a model fitted on the same rewards is fixed. Double robustness does not create support or prevent high variance; estimated or clipped propensities require stating the actual estimator. See Dudík, Langford and Li.
Preparing evaluation replicates.
Learning a policy by optimizing the same evaluation can overfit weights and logged rewards. Counterfactual risk minimization incorporates this issue when learning from partial feedback; maintain separate evaluation and study sensitivity to large weights. In deployment, define safety and exploration constraints, log the propensity of the policy actually executed, and compare segments before expanding traffic.
The following hybrid model shares one parameter vector across actions and retains another per action. Shared feature z(x,a) also depends on action. To expose rank-one updating it uses the joint matrix: equivalent to hybrid ridge, but not intended as the most efficient implementation with many arms. Thompson covariance corresponds to a Gaussian prior and unit-variance Gaussian likelihood; for binary Iris rewards it is a working approximation, not an exact Bernoulli posterior.
import numpy as np
from sklearn.datasets import load_iris
def features(x, action, n_actions):
# Bloque compartido: una interacción entre contexto y acción.
z = x * (2 * action / (n_actions - 1) - 1)
phi = np.zeros(len(x) * (n_actions + 1))
phi[:len(x)] = z
start = len(x) * (1 + action)
phi[start:start + len(x)] = x
return phi
def sm_update(inverse, x):
v = inverse @ x
return inverse - np.outer(v, v) / (1.0 + x @ v)
def run_bandit(X, rewards, method, seed, alpha=.5, epsilon=.1):
# rewards[t,a] contiene todas las recompensas solo para medir regret;
# la política observa únicamente rewards[t, selected].
rng = np.random.default_rng(seed)
n, d = X.shape
k = rewards.shape[1]
size = d * (k + 1) if method == 'hibrido' else d * k
inverse = np.eye(size)
b = np.zeros(size)
regret = 0.0
total = 0.0
for t, x in enumerate(X):
phis = []
for a in range(k):
if method == 'hibrido':
phi = features(x, a, k)
else:
phi = np.zeros(size)
phi[a*d:(a+1)*d] = x
phis.append(phi)
phis = np.asarray(phis)
mean = inverse @ b
values = phis @ mean
if method in ('ucb', 'hibrido'):
bonus = np.sqrt(np.maximum(0, np.sum((phis @ inverse) * phis, axis=1)))
action = int(np.argmax(values + alpha * bonus))
elif method == 'thompson':
# Cholesky de la covarianza conjunta, sin invertir por ronda.
sample = mean + np.linalg.cholesky(inverse) @ rng.normal(size=size)
action = int(np.argmax(phis @ sample))
elif method == 'epsilon':
action = int(rng.integers(k)) if rng.random() < epsilon else int(np.argmax(values))
else:
raise ValueError('Método desconocido')
phi = phis[action]
reward = rewards[t, action]
inverse = sm_update(inverse, phi)
b += reward * phi
total += reward
regret += rewards[t].max() - reward
return total / n, regret
# Comprobar Sherman-Morrison frente a inversión directa.
rng = np.random.default_rng(2026)
u = rng.normal(size=4)
assert np.allclose(sm_update(np.eye(4), u), np.linalg.inv(np.eye(4) + np.outer(u, u)))
# Datos sintéticos: recompensa lineal por acción y ruido gaussiano común
# precalculado; todos los métodos reciben los mismos contextos y recompensas.
k, d, n = 3, 3, 240
X_syn = rng.normal(size=(n, d))
theta = np.array([[.4, -.2, .1], [-.1, .35, .2], [.1, .1, -.35]])
expected = X_syn @ theta.T
noise = rng.normal(scale=.1, size=expected.shape)
R_syn = expected + noise
methods = ('ucb', 'hibrido', 'thompson', 'epsilon')
for i, method in enumerate(methods):
mean_reward, realized = run_bandit(X_syn, R_syn, method, 31+i)
print('Sintético', method, 'recompensa media', round(mean_reward, 4),
'regret contra máximo realizado', round(realized, 4))
# Iris: dividir antes de calcular la escala. Cada fila se usa una vez.
iris = load_iris()
order = np.random.default_rng(41).permutation(len(iris.target))
train, evaluation = order[:90], order[90:]
mu = iris.data[train].mean(axis=0)
scale = iris.data[train].std(axis=0)
scale[scale == 0] = 1
X = (iris.data[evaluation] - mu) / scale
X = np.column_stack((np.ones(len(X)), X))
R = (np.arange(3)[None, :] == iris.target[evaluation, None]).astype(float)
for i, method in enumerate(methods):
score, regret = run_bandit(X, R, method, 91+i)
print('Iris', method, 'acierto online', round(score, 4), 'errores', int(regret))The synthetic example shows regret relative to each row’s best realized outcome, including noise; it is not pseudo-regret against expected means. In Iris the policy trains online on 60 evaluation rows: the prior 90 only fix scale. Different selection seeds do not make methods independent replicates, and one run does not establish a general ranking.
Iris contains full labels, allowing target-policy value to be known on held-out rows. Real logs show only chosen-action reward and lack that true value. The target policy and direct model are trained only on training data; the latter uses only logged rewards. Evaluation retains contexts, actions, rewards, and exact propensities. Each replicate resamples logging actions on the same evaluation rows: it measures logging uncertainty conditional on that set, not population uncertainty.
import numpy as np
from sklearn.datasets import load_iris
iris = load_iris()
rng = np.random.default_rng(72)
order = rng.permutation(len(iris.target))
train, test = order[:90], order[90:]
mean = iris.data[train].mean(axis=0)
scale = iris.data[train].std(axis=0)
scale[scale == 0] = 1
X = np.column_stack((np.ones(len(order)), (iris.data - mean) / scale))
y = iris.target
k, d = 3, X.shape[1]
# Política objetivo aprendida con etiquetas completas de entrenamiento.
onehot = (y[train, None] == np.arange(k)).astype(float)
coef = np.linalg.solve(X[train].T @ X[train] + np.eye(d), X[train].T @ onehot)
target = np.argmax(X[test] @ coef, axis=1)
truth = float(np.mean(target == y[test]))
def logging_probs(x, epsilon):
# La regla de referencia está fijada antes de observar la etiqueta.
favorite = (x[:, 1] > 0).astype(int)
probabilities = np.full((len(x), k), epsilon / k)
probabilities[np.arange(len(x)), favorite] += 1 - epsilon
return probabilities
def draw_log(indices, epsilon, generator):
p = logging_probs(X[indices], epsilon)
u = generator.random(len(indices))
actions = (u[:, None] > np.cumsum(p, axis=1)).sum(axis=1)
actions = np.minimum(actions, k-1)
reward = (actions == y[indices]).astype(float)
return actions, reward, p[np.arange(len(indices)), actions]
def reward_model(actions, rewards):
# Una regresión ridge por acción, entrenada con los registros de train.
q = np.zeros((len(test), k))
for a in range(k):
subset = actions == a
xa = X[train][subset]
beta = np.linalg.solve(xa.T @ xa + np.eye(d), xa.T @ rewards[subset])
q[:, a] = X[test] @ beta
return np.clip(q, 0, 1)
def evaluate(actions, rewards, propensity, target, q, target_propensity):
rows = np.arange(len(actions))
if (np.any(~np.isfinite(propensity)) or np.any((propensity <= 0) | (propensity > 1))
or np.any(~np.isfinite(target_propensity)) or np.any((target_propensity <= 0) | (target_propensity > 1))):
raise ValueError('Falta soporte de la política objetivo o la propensión no es válida')
weight = (actions == target) / propensity
dm = float(q[rows, target].mean())
ips = float(np.mean(weight * rewards))
snips = float(np.sum(weight * rewards) / weight.sum()) if weight.sum() else np.nan
dr = float(np.mean(q[rows, target] + weight * (rewards - q[rows, actions])))
ess = float(weight.sum()**2 / np.sum(weight**2)) if np.any(weight) else 0.0
return dm, ips, snips, dr, ess
# Una acción registrada puede tener probabilidad positiva aunque la acción
# objetivo sea imposible en ese mismo contexto.
try:
evaluate(np.array([0]), np.array([1.]), np.array([1.]),
np.array([1]), np.array([[.5, .5, .5]]), np.array([0.]))
except ValueError:
pass
else:
raise AssertionError('Debe detectarse la ausencia de soporte objetivo')
print('Iris: train', len(train), 'evaluación', len(test), 'valor real', round(truth, 4))
for epsilon in (.05, .2, 1.0):
# Para cada nivel se mantiene fijo un modelo de recompensa de train.
generator = np.random.default_rng(100 + int(epsilon * 100))
a_train, r_train, _ = draw_log(train, epsilon, generator)
q = reward_model(a_train, r_train)
target_propensity = logging_probs(X[test], epsilon)[np.arange(len(test)), target]
estimates = []
for _ in range(200):
actions, reward, propensity = draw_log(test, epsilon, generator)
estimates.append(evaluate(actions, reward, propensity, target, q, target_propensity))
estimates = np.asarray(estimates)
print('epsilon', epsilon, 'propensión mínima', epsilon/k)
for j, name in enumerate(('DM', 'IPS', 'SNIPS', 'DR')):
values = estimates[:, j]
finite = values[np.isfinite(values)]
print(name, 'media', round(float(finite.mean()), 4),
'desviación', round(float(finite.std()), 4),
'réplicas definidas', len(finite))
print('ESS medio', round(float(estimates[:, 4].mean()), 2))Logging probability of the favorite action is 1−ε+ε/3; for others it is ε/3. With ε>0 there is support, but small propensity may yield large weights. The function also receives target-action propensity in each context: knowing only observed-action propensity cannot check support. This check on observed rows does not guarantee support for every possible context. DM depends on the model; IPS is conditionally unbiased with correct propensities; SNIPS is a generally finite-sample-biased ratio undefined if weights sum to zero. DR combines model and weighted residual, and separate fitting avoids using evaluated rewards to train that model. Neither support nor unbiasedness ensures low variance.
Exercises
Step 1 of 3. What is the conditional mean of Y=π(A|X)R/μ(A|X) given X?
Step 1 of 3. How does the determinant change when xₜ is added?
import numpy as np
def dr_estimate(logs, pi, q_hat):
pass
import math
print('Índice 2:', 1 + math.sqrt(2)/2, 'índice 1:', 1.5)