RLS RL, Read as Statistics

ch03_thompson.py

Companion code for Thompson sampling as posterior inference. Needs only Python 3 and NumPy: python code/ch03_thompson.py.

NumPy
"""Chapter 3 companion: Thompson sampling on Bernoulli bandits.

Demonstrates (see content/chapters/03-posterior-sampling.md):
  1. Regret (with standard errors over many runs) of Thompson sampling vs
     UCB1 vs greedy on a fixed Bernoulli bandit (frequentist regret), plus
     Thompson with two misspecified priors.
  2. Probability matching: the frequency with which Thompson sampling picks an
     arm equals the posterior probability that the arm is optimal. Shown as a
     per-arm table and as a calibration (reliability) table.
  3. Bayesian regret: mu drawn from the prior, averaged over draws, compared
     with the Russo--Van Roy bound sqrt(0.5 * K * H(A*) * T).

NumPy only. Run:  python code/ch03_thompson.py
"""
import numpy as np

rng = np.random.default_rng(3)


# ----------------------------------------------------------------- policies
def pick_greedy(N, S, t, a0, b0):
    """Pull each arm once, then the arm with the highest sample mean."""
    runs, K = N.shape
    if t < K:
        return np.full(runs, t)
    means = S / N
    # random tie-breaking: add tiny noise
    return np.argmax(means + 1e-9 * rng.random(means.shape), axis=1)


def pick_ucb1(N, S, t, a0, b0):
    """UCB1: sample mean + sqrt(2 ln t / N_a) (Auer et al. 2002)."""
    runs, K = N.shape
    if t < K:
        return np.full(runs, t)
    bonus = np.sqrt(2.0 * np.log(t + 1) / N)
    return np.argmax(S / N + bonus, axis=1)


def posterior_draw(N, S, a0, b0):
    """One draw from each arm's Beta posterior: Beta(a0 + S, b0 + N - S)."""
    return rng.beta(a0 + S, b0 + N - S)


def pick_thompson(N, S, t, a0, b0):
    """Act greedily on one posterior draw."""
    return np.argmax(posterior_draw(N, S, a0, b0), axis=1)


def p_optimal(N, S, a0, b0, M=300):
    """Monte Carlo posterior P(arm a is optimal | data), one row per run."""
    runs, K = N.shape
    idx = np.stack([np.argmax(posterior_draw(N, S, a0, b0), axis=1) for _ in range(M)])
    return (idx[:, :, None] == np.arange(K)).mean(axis=0)


# --------------------------------------------------------------- simulation
def simulate(policy, mu, T, a0=1.0, b0=1.0, checkpoints=()):
    """Run `policy` for T rounds on `runs` independent bandits.

    mu: array (runs, K), the true arm means of each run.
    Returns cumulative pseudo-regret (runs, T), arms chosen (runs, T), and a
    dict {t: (chosen arm, posterior P(optimal))} at the checkpoint rounds.
    """
    runs, K = mu.shape
    N = np.zeros((runs, K))
    S = np.zeros((runs, K))
    gap = mu.max(axis=1, keepdims=True) - mu
    regret = np.zeros((runs, T))
    arms = np.zeros((runs, T), dtype=np.int8)
    rows = np.arange(runs)
    snaps = {}
    for t in range(T):
        if (t + 1) in checkpoints:
            snaps[t + 1] = [None, p_optimal(N, S, a0, b0)]
        a = policy(N, S, t, a0, b0)
        r = (rng.random(runs) < mu[rows, a]).astype(float)
        N[rows, a] += 1
        S[rows, a] += r
        regret[:, t] = gap[rows, a]
        arms[:, t] = a
        if (t + 1) in checkpoints:
            snaps[t + 1][0] = a.copy()
    return np.cumsum(regret, axis=1), arms, snaps


def mean_se(x):
    return x.mean(), x.std(ddof=1) / np.sqrt(len(x))


def fmt(x):
    m, s = mean_se(x)
    return f"{m:7.1f} ({s:4.1f})"


def kl_bern(p, q):
    return p * np.log(p / q) + (1 - p) * np.log((1 - p) / (1 - q))


# ================================================== experiment 1: regret
K, T, RUNS = 5, 3000, 400
mu_fixed = np.array([0.60, 0.50, 0.45, 0.40, 0.35])
MU = np.tile(mu_fixed, (RUNS, 1))
rev_means = mu_fixed[::-1]  # prior that believes the WORST arm is best
wrong_a = 20 * rev_means
wrong_b = 20 * (1 - rev_means)

configs = [
    ("greedy", pick_greedy, 1.0, 1.0),
    ("UCB1", pick_ucb1, 1.0, 1.0),
    ("Thompson, Beta(1,1)", pick_thompson, 1.0, 1.0),
    ("Thompson, optimistic Beta(40,10)", pick_thompson, 40.0, 10.0),
    ("Thompson, reversed prior (n0=20)", pick_thompson, wrong_a, wrong_b),
]
checks = (10, 50, 200, 1000)

print(f"Experiment 1: fixed instance mu = {mu_fixed.tolist()}, {RUNS} runs, T = {T}")
print("Cumulative pseudo-regret, mean (standard error) over runs")
hdr = f"{'algorithm':34s}" + "".join(f"{'T=' + str(h):>15s}" for h in (100, 500, 1000, 3000)) + "   locked-on-opt"
print(hdr)
snap_ts = None
for name, pol, a0, b0 in configs:
    reg, arms, snaps = simulate(pol, MU, T, a0, b0, checkpoints=checks if name == "Thompson, Beta(1,1)" else ())
    if name == "Thompson, Beta(1,1)":
        snap_ts = snaps
    locked = np.mean((arms[:, -100:] == 0).mean(axis=1) > 0.9)
    cells = "".join(f"{fmt(reg[:, h - 1]):>15s}" for h in (100, 500, 1000, 3000))
    print(f"{name:34s}{cells}   {100 * locked:6.1f}%")
gaps = mu_fixed.max() - mu_fixed[1:]
lb = np.sum(gaps / kl_bern(mu_fixed[1:], mu_fixed.max())) * np.log(T)
print(f"Lai-Robbins asymptotic lower-bound scale, sum(gap/KL) * ln T at T={T}: {lb:.1f}")
print("locked-on-opt = share of runs pulling the best arm in >90% of the last 100 rounds")

# =============================================== experiment 2: matching
print()
print("Experiment 2: probability matching, Thompson Beta(1,1), same 400 runs")
print("selection frequency of each arm at round t  vs  mean posterior P(optimal)")
print(f"{'t':>5s}  {'':8s}" + "".join(f"  arm{a}" + " " * 2 for a in range(K)))
pool_sel, pool_p = [], []
for t in checks:
    chosen, p = snap_ts[t]
    sel = (chosen[:, None] == np.arange(K)).astype(float)
    print(f"{t:5d}  {'chosen':8s}" + "".join(f"  {sel[:, a].mean():.3f} " for a in range(K)))
    print(f"{'':5s}  {'P(opt)':8s}" + "".join(f"  {p[:, a].mean():.3f} " for a in range(K)))
    pool_sel.append(sel.ravel())
    pool_p.append(p.ravel())
pool_sel, pool_p = np.concatenate(pool_sel), np.concatenate(pool_p)

print()
print("Calibration: pool (run, arm, checkpoint); bin by posterior P(optimal)")
print(f"{'bin':>11s} {'count':>6s} {'mean P(opt)':>12s} {'chosen freq':>12s} {'se':>7s}")
edges = [0, 0.05, 0.2, 0.4, 0.6, 0.8, 1.0000001]
for lo, hi in zip(edges[:-1], edges[1:]):
    m = (pool_p >= lo) & (pool_p < hi)
    if m.sum() == 0:
        continue
    f = pool_sel[m].mean()
    se = np.sqrt(f * (1 - f) / m.sum())
    print(f"[{lo:.2f},{min(hi, 1):.2f}) {m.sum():6d} {pool_p[m].mean():12.3f} {f:12.3f} {se:7.3f}")

# ======================================== experiment 3: Bayesian regret
print()
BR_RUNS, BR_T = 1000, 1000
mu_prior = rng.random((BR_RUNS, K))  # mu_a ~ U(0,1), iid: the Beta(1,1) prior
H = np.log(K)  # entropy of A* under a symmetric prior
bound = np.sqrt(0.5 * K * H * BR_T)
print(f"Experiment 3: Bayesian regret, mu_a ~ U(0,1) iid, K={K}, {BR_RUNS} draws of mu, T={BR_T}")
print(f"{'algorithm':34s}{'Bayes regret':>16s}{'max over runs':>16s}")
for name, pol, a0, b0 in configs[:3]:
    reg, _, _ = simulate(pol, mu_prior, BR_T, a0, b0)
    print(f"{name:34s}{fmt(reg[:, -1]):>16s}{reg[:, -1].max():16.1f}")
print(f"Russo-Van Roy bound sqrt(0.5 * K * ln K * T) = {bound:.1f}")