Module contents
Lesson 4 of 37Core 110 min

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 XtX_t, choose AtA_t, and receive only that action’s reward.

A policy π(a∣x)\pi(a\mid x) assigns probabilities to available actions. If q(x,a)=E[R∣X=x,A=a]q(x,a)=\mathbb E[R\mid X=x,A=a] and contexts are i.i.d. from a stable distribution, its value is

V(π)=EX∑aπ(a∣X)q(X,a).V(\pi)=\mathbb E_X\sum_a\pi(a\mid X)q(X,a).

A learned policy can be compared with the best in class Π\Pi; 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 xt,a∈Rdx_{t,a}\in\mathbb R^d for each context–action pair, and E[Rt∣Ht−1,Xt,At=a]=xt,aTθ∗\mathbb E[R_t\mid\mathcal H_{t-1},X_t,A_t=a]=x_{t,a}^{\mathsf T}\theta^*. For earlier observations, with λ>0\lambda>0,

At=λI+∑s<txsxsT,bt=∑s<txsRs,θ^t=At−1bt.A_t=\lambda I+\sum_{s<t}x_sx_s^{\mathsf T},\qquad b_t=\sum_{s<t}x_sR_s,\qquad \widehat\theta_t=A_t^{-1}b_t.

Regularization makes AtA_t positive definite even before data. The LinUCB index chooses a maximum of

xt,aTθ^t+αtxt,aTAt−1xt,a.x_{t,a}^{\mathsf T}\widehat\theta_t+\alpha_t\sqrt{x_{t,a}^{\mathsf T}A_t^{-1}x_{t,a}}.

The first part estimates reward and the second is larger in poorly observed directions. If the true parameter lies in ellipsoid ∥θ−θ^t∥At≤αt\|\theta-\widehat\theta_t\|_{A_t}\leq\alpha_t, Cauchy–Schwarz in dual norms shows the maximum of xTθx^{\mathsf T}\theta over that set is exactly the index. An α\alpha chosen for convenience draws an ellipsoid and defines a policy, but is not itself a statistical guarantee.

InteractiveExplore an unknown direction

Preparing the ellipsoid.

Move the context and add observations to see how the ellipsoid and indices change.

For a correct linear model, bounded-norm adaptive features, conditionally centered RR-subgaussian noise, and ∥θ∗∥2≤S\|\theta^*\|_2\leq S, one simultaneous confidence construction uses, with probability at least 1−δ1-\delta,

βt=R2log⁡ ⁣(det⁡(At)1/2det⁡(λI)1/2δ)+λ S.\beta_t=R\sqrt{2\log\!\left(\frac{\det(A_t)^{1/2}}{\det(\lambda I)^{1/2}\delta}\right)}+\sqrt\lambda\,S.

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 xx and rr, At+1=At+xxTA_{t+1}=A_t+xx^{\mathsf T} and bt+1=bt+xrb_{t+1}=b_t+xr. Since AtA_t is invertible, Sherman–Morrison gives

At+1−1=At−1−At−1xxTAt−11+xTAt−1x.A_{t+1}^{-1}=A_t^{-1}-\frac{A_t^{-1}xx^{\mathsf T}A_t^{-1}}{1+x^{\mathsf T}A_t^{-1}x}.

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 ut=xtTAt−1xtu_t=x_t^{\mathsf T}A_t^{-1}x_t denote the actually chosen vector. The matrix determinant lemma gives det⁡(At+1)=det⁡(At)(1+ut)\det(A_{t+1})=\det(A_t)(1+u_t). Since min⁡(1,u)≤2log⁡(1+u)\min(1,u)\leq2\log(1+u) for u≥0u\geq0, the elliptical potential lemma states

∑t=1Tmin⁡(1,ut)≤2log⁡det⁡AT+1det⁡A1≤2dlog⁡ ⁣(1+TL2λd),\sum_{t=1}^T\min(1,u_t)\leq2\log\frac{\det A_{T+1}}{\det A_1} \leq2d\log\!\left(1+\frac{TL^2}{\lambda d}\right),

if ∥xt∥2≤L\|x_t\|_2\leq L and A1=λIA_1=\lambda I. The last inequality applies arithmetic versus geometric means to eigenvalues and uses tr⁡(AT+1)≤λd+TL2\operatorname{tr}(A_{T+1})\leq\lambda d+TL^2. Clipping min⁡(1,ut)\min(1,u_t) does not vanish without another assumption.

For example, if λ≥L2\lambda\geq L^2, then ut≤1u_t\leq1. On the confidence event, optimism and index selection imply instantaneous regret at most 2βtut2\beta_t\sqrt{u_t}. Cauchy–Schwarz and the lemma give

RT≤2βT2Tdlog⁡ ⁣(1+TL2λd).R_T\leq2\beta_T\sqrt{2Td\log\!\left(1+\frac{TL^2}{\lambda d}\right)}.

With fixed parameters and confidence, its usual order is O(dTlog⁡T)O(d\sqrt T\log T), 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 ε\varepsilon-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.

InteractiveRecommendation with changing preferences

Preparing the reproducible recommender.

Compare choices and exploration under an explicit synthetic model; after drift, regret uses each round’s best article.

What can be learned from logs

Now suppose logs D={(xi,ai,ri,μi)}i=1nD=\{(x_i,a_i,r_i,\mu_i)\}_{i=1}^n, where μi=μ(ai∣xi)\mu_i=\mu(a_i\mid x_i) 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 μ(a∣x)>0\mu(a\mid x)>0 whenever π(a∣x)>0\pi(a\mid x)>0 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

V^IPS=1n∑i=1nπ(ai∣xi)μ(ai∣xi)ri.\widehat V_{\mathrm{IPS}}=\frac1n\sum_{i=1}^n\frac{\pi(a_i\mid x_i)}{\mu(a_i\mid x_i)}r_i.

Condition on X=xX=x and sum over logged action: distribution factor μ(a∣x)\mu(a\mid x) cancels the denominator, leaving ∑aπ(a∣x)q(x,a)\sum_a\pi(a\mid x)q(x,a). Thus IPS is unbiased for a fixed target policy and correct propensities. If Y=π(A∣X)R/μ(A∣X)Y=\pi(A\mid X)R/\mu(A\mid X) has finite second moment, its variance is

Var⁡(V^IPS)=1n[EX∑aπ(a∣X)2μ(a∣X)E[R2∣X,a]−V(π)2].\operatorname{Var}(\widehat V_{\mathrm{IPS}})=\frac1n\left[ \mathbb E_X\sum_a\frac{\pi(a\mid X)^2}{\mu(a\mid X)}\mathbb E[R^2\mid X,a]-V(\pi)^2\right].

Sums in these formulas are restricted to actions with π(a∣x)>0\pi(a\mid x)>0; when both π\pi and μ\mu are zero, their contribution is zero and ratio 0/00/0 is not evaluated. Division by nn 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 q^(x,a)\widehat q(x,a) and averages ∑aπ(a∣x)q^(x,a)\sum_a\pi(a\mid x)\widehat q(x,a). 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:

V^DR=1n∑i[∑aπ(a∣xi)q^(xi,a)+π(ai∣xi)μ^(ai∣xi)(ri−q^(xi,ai))].\widehat V_{\mathrm{DR}}=\frac1n\sum_i\left[ \sum_a\pi(a\mid x_i)\widehat q(x_i,a)+ \frac{\pi(a_i\mid x_i)}{\widehat\mu(a_i\mid x_i)}\bigl(r_i-\widehat q(x_i,a_i)\bigr)\right].

For models fixed independently of evaluation data, conditional bias at xx is ∑a:π(a∣x)>0π(a∣x)(q^−q)(1−μ/μ^)\sum_{a:\pi(a\mid x)>0}\pi(a\mid x)(\widehat q-q)(1-\mu/\widehat\mu), 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.

InteractivePropensities and variance

Preparing evaluation replicates.

Compare estimators on simulated logs and observe what happens as effective support falls.

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.

[ ]Linear bandits and classification as a banditBrowser
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.

[ ]DM, IPS, SNIPS, and doubly robustBrowser
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

ProofWhat IPS corrects and how much it can vary
Prove: Prove IPS unbiasedness and calculate its variance.
0
Observations (X,A,R) are i.i.d. Logging policy μ and target policy π are fixed independently of the sample; μ(a|x)>0 wherever π(a|x)>0. Let q(x,a)=E[R|X=x,A=a] and m₂(x,a)=E[R²|X=x,A=a]. Assume the weighted variable has finite second moment. Target value is V=E_X Σa π(a|X)q(X,a).

Step 1 of 3. What is the conditional mean of Y=π(A|X)R/μ(A|X) given X?

ProofDeterminants and cumulative exploration
Prove: Prove a version of the elliptical potential lemma.
0
Let A₀=λI in dimension d, with λ>0, and Aₜ=Aₜ₋₁+xₜxₜᵀ. Vectors may be arbitrary, including adaptive, and satisfy ||xₜ||₂≤L. Define uₜ=xₜᵀAₜ₋₁⁻¹xₜ.

Step 1 of 3. How does the determinant change when xₜ is added?

NumericChoose between two indices
For x=(1,2), α=0.5, A₁=diag(2,8), b₁=(2,0), A₂=diag(1,4), and b₂=(0,6; 0,8) (using decimal commas), calculate the second action’s index: xᵀA₂⁻¹b₂+α√(xᵀA₂⁻¹x).
QuizNearly deterministic propensities
You want to evaluate a policy recommending an action with positive probability where the logging policy never chooses it. What follows without extra assumptions?
CodeEvaluate with a doubly robust correction
Implement dr_estimate(logs, pi, q_hat). logs is a dictionary with actions, rewards, and propensities, vectors of length n>0; actions contains integer indices from 0 to K−1, rewards finite real values, and propensities observed logging probabilities in (0,1]. pi and q_hat are finite (n,K) matrices, K>0: each pi row is a probability distribution and q_hat[i,a] predicts reward. Return the mean of Σa pi[i,a]·q_hat[i,a]+pi[i,actions[i]]/propensities[i]·(rewards[i]−q_hat[i,actions[i]]). Validate shapes, indices, probabilities, and finiteness with ValueError; do not modify inputs. If the result or a necessary intermediate calculation is not representable as float64, you may raise ValueError rather than return infinity or NaN. Support for unobserved actions is assumed and cannot be checked from logged-action propensities alone. Model and policy were fixed using data independent of evaluation.
import numpy as np

def dr_estimate(logs, pi, q_hat):
  pass
Shift+Enter to run
[ ]Check the LinUCB indexBrowser
import math
print('Índice 2:', 1 + math.sqrt(2)/2, 'índice 1:', 1.5)